最简单的基于FFmpeg的AVfilter例子(水印叠加)

来源:互联网 发布:人工智能威胁论 提出人 编辑:程序博客网 时间:2024/05/23 00:11

FFMPEG中有一个类库:libavfilter。该类库提供了各种视音频过滤器。之前一直没有怎么使用过这个类库,最近看了一下它的使用说明,发现还是很强大的,有很多现成的filter供使用,完成视频的处理很方便。在此将它的一个例子基础上完成了一个水印叠加器,并且移植到了VC2010下,方便开发人员学习研究它的使用方法。

该例子完成了一个水印叠加的功能。可以将一张透明背景的PNG图片作为水印叠加到一个视频文件上。需要注意的是,其叠加工作是在解码后的YUV像素数据的基础上完成的。程序支持使用SDL显示叠加后的YUV数据。也可以将叠加后的YUV输出成文件。

流程图(2014.9.29更新)

下面附一张使用FFmpeg的libavfilter的流程图。可以看出使用libavfilter还是需要做不少的初始化工作的。但是使用的时候还是比较简单的,就两个重要的函数:av_buffersrc_add_frame()和av_buffersink_get_buffer_ref()。

PS:这张图中只列出了和libavfilter有关的函数和结构体。代码中其它函数可以参考:100行代码实现最简单的基于FFMPEG+SDL的视频播放器(SDL1.x)



代码

下面直接贴上代码:

 

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /*  
  2.  * 最简单的基于FFmpeg的AVFilter例子(叠加水印) 
  3.  * Simplest FFmpeg AVfilter Example (Watermark) 
  4.  * 
  5.  * 雷霄骅 Lei Xiaohua 
  6.  * leixiaohua1020@126.com 
  7.  * 中国传媒大学/数字电视技术 
  8.  * Communication University of China / Digital TV Technology 
  9.  * http://blog.csdn.net/leixiaohua1020 
  10.  *  
  11.  * 本程序使用FFmpeg的AVfilter实现了视频的水印叠加功能。 
  12.  * 可以将一张PNG图片作为水印叠加到视频上。 
  13.  * 是最简单的FFmpeg的AVFilter方面的教程。 
  14.  * 适合FFmpeg的初学者。 
  15.  * 
  16.  * This software uses FFmpeg's AVFilter to add watermark in a video file. 
  17.  * It can add a PNG format picture as watermark to a video file. 
  18.  * It's the simplest example based on FFmpeg's AVFilter.  
  19.  * Suitable for beginner of FFmpeg  
  20.  * 
  21.  */  
  22. #include "stdafx.h"  
  23.   
  24. #define ENABLE_SDL 1  
  25. #define ENABLE_YUVFILE 1  
  26.   
  27. extern "C"  
  28. {  
  29. #include "libavcodec/avcodec.h"  
  30. #include "libavformat/avformat.h"  
  31. #include "libavfilter/avfiltergraph.h"  
  32. #include "libavfilter/avcodec.h"  
  33. #include "libavfilter/buffersink.h"  
  34. #include "libavfilter/buffersrc.h"  
  35. #include "libavutil/avutil.h"  
  36. #include "libswscale/swscale.h"  
  37.     //SDL  
  38. #include "sdl/SDL.h"  
  39. #include "sdl/SDL_thread.h"  
  40. };  
  41.   
  42. const char *filter_descr = "movie=my_logo.png[wm];[in][wm]overlay=5:5[out]";  
  43.   
  44. static AVFormatContext *pFormatCtx;  
  45. static AVCodecContext *pCodecCtx;  
  46. AVFilterContext *buffersink_ctx;  
  47. AVFilterContext *buffersrc_ctx;  
  48. AVFilterGraph *filter_graph;  
  49. static int video_stream_index = -1;  
  50. static int64_t last_pts = AV_NOPTS_VALUE;  
  51.   
  52.   
  53.   
  54.   
  55. static int open_input_file(const char *filename)  
  56. {  
  57.     int ret;  
  58.     AVCodec *dec;  
  59.   
  60.     if ((ret = avformat_open_input(&pFormatCtx, filename, NULL, NULL)) < 0) {  
  61.         av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");  
  62.         return ret;  
  63.     }  
  64.   
  65.     if ((ret = avformat_find_stream_info(pFormatCtx, NULL)) < 0) {  
  66.         av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");  
  67.         return ret;  
  68.     }  
  69.   
  70.     /* select the video stream */  
  71.     ret = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);  
  72.     if (ret < 0) {  
  73.         av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n");  
  74.         return ret;  
  75.     }  
  76.     video_stream_index = ret;  
  77.     pCodecCtx = pFormatCtx->streams[video_stream_index]->codec;  
  78.   
  79.     /* init the video decoder */  
  80.     if ((ret = avcodec_open2(pCodecCtx, dec, NULL)) < 0) {  
  81.         av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");  
  82.         return ret;  
  83.     }  
  84.   
  85.     return 0;  
  86. }  
  87.   
  88. static int init_filters(const char *filters_descr)  
  89. {  
  90.     char args[512];  
  91.     int ret;  
  92.     AVFilter *buffersrc  = avfilter_get_by_name("buffer");  
  93.     AVFilter *buffersink = avfilter_get_by_name("ffbuffersink");  
  94.     AVFilterInOut *outputs = avfilter_inout_alloc();  
  95.     AVFilterInOut *inputs  = avfilter_inout_alloc();  
  96.     enum PixelFormat pix_fmts[] = { PIX_FMT_GRAY8, PIX_FMT_NONE };  
  97.     AVBufferSinkParams *buffersink_params;  
  98.   
  99.     filter_graph = avfilter_graph_alloc();  
  100.   
  101.     /* buffer video source: the decoded frames from the decoder will be inserted here. */  
  102.     _snprintf(args, sizeof(args),  
  103.             "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",  
  104.             pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,  
  105.             pCodecCtx->time_base.num, pCodecCtx->time_base.den,  
  106.             pCodecCtx->sample_aspect_ratio.num, pCodecCtx->sample_aspect_ratio.den);  
  107.   
  108.     ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",  
  109.                                        args, NULL, filter_graph);  
  110.     if (ret < 0) {  
  111.         av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");  
  112.         return ret;  
  113.     }  
  114.   
  115.     /* buffer video sink: to terminate the filter chain. */  
  116.     buffersink_params = av_buffersink_params_alloc();  
  117.     buffersink_params->pixel_fmts = pix_fmts;  
  118.     ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",  
  119.                                        NULL, buffersink_params, filter_graph);  
  120.     av_free(buffersink_params);  
  121.     if (ret < 0) {  
  122.         av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");  
  123.         return ret;  
  124.     }  
  125.   
  126.     /* Endpoints for the filter graph. */  
  127.     outputs->name       = av_strdup("in");  
  128.     outputs->filter_ctx = buffersrc_ctx;  
  129.     outputs->pad_idx    = 0;  
  130.     outputs->next       = NULL;  
  131.   
  132.     inputs->name       = av_strdup("out");  
  133.     inputs->filter_ctx = buffersink_ctx;  
  134.     inputs->pad_idx    = 0;  
  135.     inputs->next       = NULL;  
  136.   
  137.     if ((ret = avfilter_graph_parse(filter_graph, filters_descr,  
  138.                                     &inputs, &outputs, NULL)) < 0)  
  139.         return ret;  
  140.   
  141.     if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)  
  142.         return ret;  
  143.     return 0;  
  144. }  
  145.   
  146.   
  147. int _tmain(int argc, _TCHAR* argv[])  
  148. {  
  149.     int ret;  
  150.     AVPacket packet;  
  151.     AVFrame frame;  
  152.     int got_frame;  
  153.   
  154.     if (argc != 2) {  
  155.         fprintf(stderr, "Usage: %s file\n", argv[0]);  
  156.         return -1;  
  157.     }  
  158.   
  159.     avcodec_register_all();  
  160.     av_register_all();  
  161.     avfilter_register_all();  
  162.   
  163.     if ((ret = open_input_file(argv[1])) < 0)  
  164.         goto end;  
  165.     if ((ret = init_filters(filter_descr)) < 0)  
  166.         goto end;  
  167. #if ENABLE_YUVFILE  
  168.     FILE *fp_yuv=fopen("test.yuv","wb+");  
  169. #endif  
  170. #if ENABLE_SDL  
  171.     SDL_Surface *screen;   
  172.     SDL_Overlay *bmp;   
  173.     SDL_Rect rect;  
  174.     if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {    
  175.         printf( "Could not initialize SDL - %s\n", SDL_GetError());   
  176.         return -1;  
  177.     }   
  178.     screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 0, 0);  
  179.     if(!screen) {    
  180.         printf("SDL: could not set video mode - exiting\n");    
  181.         return -1;  
  182.     }  
  183.     bmp = SDL_CreateYUVOverlay(pCodecCtx->width, pCodecCtx->height,SDL_YV12_OVERLAY, screen);   
  184. #endif  
  185.   
  186.     /* read all packets */  
  187.     while (1) {  
  188.         AVFilterBufferRef *picref;  
  189.         if ((ret = av_read_frame(pFormatCtx, &packet)) < 0)  
  190.             break;  
  191.   
  192.         if (packet.stream_index == video_stream_index) {  
  193.             avcodec_get_frame_defaults(&frame);  
  194.             got_frame = 0;  
  195.             ret = avcodec_decode_video2(pCodecCtx, &frame, &got_frame, &packet);  
  196.             if (ret < 0) {  
  197.                 av_log(NULL, AV_LOG_ERROR, "Error decoding video\n");  
  198.                 break;  
  199.             }  
  200.   
  201.             if (got_frame) {  
  202.                 frame.pts = av_frame_get_best_effort_timestamp(&frame);  
  203.                   
  204.                 /* push the decoded frame into the filtergraph */  
  205.                 if (av_buffersrc_add_frame(buffersrc_ctx, &frame) < 0) {  
  206.                     av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");  
  207.                     break;  
  208.                 }  
  209.   
  210.                 /* pull filtered pictures from the filtergraph */  
  211.                 while (1) {  
  212.                     ret = av_buffersink_get_buffer_ref(buffersink_ctx, &picref, 0);  
  213.                     if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)  
  214.                         break;  
  215.                     if (ret < 0)  
  216.                         goto end;  
  217.   
  218.                     if (picref) {  
  219. #if ENABLE_YUVFILE  
  220.                         int y_size=picref->video->w*picref->video->h;  
  221.                         fwrite(picref->data[0],1,y_size,fp_yuv);  
  222.                         fwrite(picref->data[1],1,y_size/4,fp_yuv);  
  223.                         fwrite(picref->data[2],1,y_size/4,fp_yuv);  
  224. #endif  
  225.                           
  226. #if ENABLE_SDL  
  227.                         SDL_LockYUVOverlay(bmp);  
  228.                         bmp->pixels[0]=picref->data[0];  
  229.                         bmp->pixels[2]=picref->data[1];  
  230.                         bmp->pixels[1]=picref->data[2];       
  231.                         bmp->pitches[0]=picref->linesize[0];  
  232.                         bmp->pitches[2]=picref->linesize[1];     
  233.                         bmp->pitches[1]=picref->linesize[2];  
  234.                         SDL_UnlockYUVOverlay(bmp);   
  235.                         rect.x = 0;      
  236.                         rect.y = 0;      
  237.                         rect.w = picref->video->w;      
  238.                         rect.h = picref->video->h;      
  239.                         SDL_DisplayYUVOverlay(bmp, &rect);   
  240.                         //Delay 40ms  
  241.                         SDL_Delay(40);  
  242. #endif  
  243.                         avfilter_unref_bufferp(&picref);  
  244.                     }  
  245.                 }  
  246.             }  
  247.         }  
  248.         av_free_packet(&packet);  
  249.     }  
  250. #if ENABLE_YUVFILE  
  251.     fclose(fp_yuv);  
  252. #endif  
  253. end:  
  254.     avfilter_graph_free(&filter_graph);  
  255.     if (pCodecCtx)  
  256.         avcodec_close(pCodecCtx);  
  257.     avformat_close_input(&pFormatCtx);  
  258.   
  259.     if (ret < 0 && ret != AVERROR_EOF) {  
  260.         char buf[1024];  
  261.         av_strerror(ret, buf, sizeof(buf));  
  262.         fprintf(stderr, "Error occurred: %s\n", buf);  
  263.         return -1;  
  264.     }  
  265.   
  266.     return 0;  
  267. }  

 

 

程序的运行效果如图所示。

需要叠加的水印为一张PNG(透明)图片(在这里是my_logo.png)。


需要叠加的视频为一个普通的FLV格式的视频(在这里是cuc_ieschool.flv)。


 

程序运行的时候,会通过SDL显示水印叠加的结果,如图所示。此外,也可以将水印叠加后的解码数据输出成文件。

注:SDL显示和输出YUV可以通过程序最前面的宏控制:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #define ENABLE_SDL 1  
  2. #define ENABLE_YUVFILE 1  



输出的YUV文件如图所示。



SourceForge项目主页:

https://sourceforge.net/projects/simplestffmpegvideofilter/

CSDN项目下载地址:

http://download.csdn.net/detail/leixiaohua1020/7465861

注:由于失误,CSDN上的项目少了一个SDL.dll文件,去SDL官网
http://www.libsdl.org/download-1.2.php
下载一个Runtime Libraries即可

PUDN源代码下载(修复了SDL问题):

http://www.pudn.com/downloads644/sourcecode/multimedia/detail2605264.html


SourceForge上项目已经修正该问题。

0 0