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

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 plain copy 在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 <stdio.h>  
  23.   
  24. #define __STDC_CONSTANT_MACROS  
  25.   
  26. #ifdef _WIN32  
  27. #define snprintf _snprintf  
  28. //Windows  
  29. extern "C"  
  30. {  
  31. #include "libavcodec/avcodec.h"  
  32. #include "libavformat/avformat.h"  
  33. #include "libavfilter/avfiltergraph.h"  
  34. #include "libavfilter/avcodec.h"  
  35. #include "libavfilter/buffersink.h"  
  36. #include "libavfilter/buffersrc.h"  
  37. #include "libavutil/avutil.h"  
  38. #include "libswscale/swscale.h"  
  39. #include "SDL/SDL.h"  
  40. };  
  41. #else  
  42. //Linux...  
  43. #ifdef __cplusplus  
  44. extern "C"  
  45. {  
  46. #endif  
  47. #include <libavcodec/avcodec.h>  
  48. #include <libavformat/avformat.h>  
  49. #include <libavfilter/avfiltergraph.h>  
  50. #include <libavfilter/avcodec.h>  
  51. #include <libavfilter/buffersink.h>  
  52. #include <libavfilter/buffersrc.h>  
  53. #include <libavutil/avutil.h>  
  54. #include <libswscale/swscale.h>  
  55. #include <SDL/SDL.h>  
  56. #ifdef __cplusplus  
  57. };  
  58. #endif  
  59. #endif  
  60.   
  61. //Enable SDL?  
  62. #define ENABLE_SDL 1  
  63. //Output YUV data?  
  64. #define ENABLE_YUVFILE 0  
  65.   
  66. const char *filter_descr = "movie=my_logo.png[wm];[in][wm]overlay=5:5[out]";  
  67.   
  68. static AVFormatContext *pFormatCtx;  
  69. static AVCodecContext *pCodecCtx;  
  70. AVFilterContext *buffersink_ctx;  
  71. AVFilterContext *buffersrc_ctx;  
  72. AVFilterGraph *filter_graph;  
  73. static int video_stream_index = -1;  
  74. static int64_t last_pts = AV_NOPTS_VALUE;  
  75.   
  76.   
  77.   
  78.   
  79. static int open_input_file(const char *filename)  
  80. {  
  81.     int ret;  
  82.     AVCodec *dec;  
  83.   
  84.     if ((ret = avformat_open_input(&pFormatCtx, filename, NULL, NULL)) < 0) {  
  85.         printf( "Cannot open input file\n");  
  86.         return ret;  
  87.     }  
  88.   
  89.     if ((ret = avformat_find_stream_info(pFormatCtx, NULL)) < 0) {  
  90.         printf( "Cannot find stream information\n");  
  91.         return ret;  
  92.     }  
  93.   
  94.     /* select the video stream */  
  95.     ret = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);  
  96.     if (ret < 0) {  
  97.         printf( "Cannot find a video stream in the input file\n");  
  98.         return ret;  
  99.     }  
  100.     video_stream_index = ret;  
  101.     pCodecCtx = pFormatCtx->streams[video_stream_index]->codec;  
  102.   
  103.     /* init the video decoder */  
  104.     if ((ret = avcodec_open2(pCodecCtx, dec, NULL)) < 0) {  
  105.         printf( "Cannot open video decoder\n");  
  106.         return ret;  
  107.     }  
  108.   
  109.     return 0;  
  110. }  
  111.   
  112. static int init_filters(const char *filters_descr)  
  113. {  
  114.     char args[512];  
  115.     int ret;  
  116.     AVFilter *buffersrc  = avfilter_get_by_name("buffer");  
  117.     AVFilter *buffersink = avfilter_get_by_name("ffbuffersink");  
  118.     AVFilterInOut *outputs = avfilter_inout_alloc();  
  119.     AVFilterInOut *inputs  = avfilter_inout_alloc();  
  120.     enum PixelFormat pix_fmts[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };  
  121.     AVBufferSinkParams *buffersink_params;  
  122.   
  123.     filter_graph = avfilter_graph_alloc();  
  124.   
  125.     /* buffer video source: the decoded frames from the decoder will be inserted here. */  
  126.     snprintf(args, sizeof(args),  
  127.             "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",  
  128.             pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,  
  129.             pCodecCtx->time_base.num, pCodecCtx->time_base.den,  
  130.             pCodecCtx->sample_aspect_ratio.num, pCodecCtx->sample_aspect_ratio.den);  
  131.   
  132.     ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",  
  133.                                        args, NULL, filter_graph);  
  134.     if (ret < 0) {  
  135.         printf("Cannot create buffer source\n");  
  136.         return ret;  
  137.     }  
  138.   
  139.     /* buffer video sink: to terminate the filter chain. */  
  140.     buffersink_params = av_buffersink_params_alloc();  
  141.     buffersink_params->pixel_fmts = pix_fmts;  
  142.     ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",  
  143.                                        NULL, buffersink_params, filter_graph);  
  144.     av_free(buffersink_params);  
  145.     if (ret < 0) {  
  146.         printf("Cannot create buffer sink\n");  
  147.         return ret;  
  148.     }  
  149.   
  150.     /* Endpoints for the filter graph. */  
  151.     outputs->name       = av_strdup("in");  
  152.     outputs->filter_ctx = buffersrc_ctx;  
  153.     outputs->pad_idx    = 0;  
  154.     outputs->next       = NULL;  
  155.   
  156.     inputs->name       = av_strdup("out");  
  157.     inputs->filter_ctx = buffersink_ctx;  
  158.     inputs->pad_idx    = 0;  
  159.     inputs->next       = NULL;  
  160.   
  161.     if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr,  
  162.                                     &inputs, &outputs, NULL)) < 0)  
  163.         return ret;  
  164.   
  165.     if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)  
  166.         return ret;  
  167.     return 0;  
  168. }  
  169.   
  170.   
  171. int main(int argc, char* argv[])  
  172. {  
  173.     int ret;  
  174.     AVPacket packet;  
  175.     AVFrame frame;  
  176.     int got_frame;  
  177.   
  178.     avcodec_register_all();  
  179.     av_register_all();  
  180.     avfilter_register_all();  
  181.   
  182.     if ((ret = open_input_file("cuc_ieschool.flv")) < 0)  
  183.         goto end;  
  184.     if ((ret = init_filters(filter_descr)) < 0)  
  185.         goto end;  
  186. #if ENABLE_YUVFILE  
  187.     FILE *fp_yuv=fopen("test.yuv","wb+");  
  188. #endif  
  189. #if ENABLE_SDL  
  190.     SDL_Surface *screen;   
  191.     SDL_Overlay *bmp;   
  192.     SDL_Rect rect;  
  193.     if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {    
  194.         printf( "Could not initialize SDL - %s\n", SDL_GetError());   
  195.         return -1;  
  196.     }   
  197.     screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 0, 0);  
  198.     if(!screen) {    
  199.         printf("SDL: could not set video mode - exiting\n");    
  200.         return -1;  
  201.     }  
  202.     bmp = SDL_CreateYUVOverlay(pCodecCtx->width, pCodecCtx->height,SDL_YV12_OVERLAY, screen);   
  203.   
  204.     SDL_WM_SetCaption("Simplest FFmpeg Video Filter",NULL);  
  205. #endif  
  206.   
  207.     /* read all packets */  
  208.     while (1) {  
  209.         AVFilterBufferRef *picref;  
  210.         if ((ret = av_read_frame(pFormatCtx, &packet)) < 0)  
  211.             break;  
  212.   
  213.         if (packet.stream_index == video_stream_index) {  
  214.             avcodec_get_frame_defaults(&frame);  
  215.             got_frame = 0;  
  216.             ret = avcodec_decode_video2(pCodecCtx, &frame, &got_frame, &packet);  
  217.             if (ret < 0) {  
  218.                 printf( "Error decoding video\n");  
  219.                 break;  
  220.             }  
  221.   
  222.             if (got_frame) {  
  223.                 frame.pts = av_frame_get_best_effort_timestamp(&frame);  
  224.                   
  225.                 /* push the decoded frame into the filtergraph */  
  226.                 if (av_buffersrc_add_frame(buffersrc_ctx, &frame) < 0) {  
  227.                     printf( "Error while feeding the filtergraph\n");  
  228.                     break;  
  229.                 }  
  230.   
  231.                 /* pull filtered pictures from the filtergraph */  
  232.                 while (1) {  
  233.                     ret = av_buffersink_get_buffer_ref(buffersink_ctx, &picref, 0);  
  234.                     if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)  
  235.                         break;  
  236.                     if (ret < 0)  
  237.                         goto end;  
  238.   
  239.                     if (picref) {  
  240. #if ENABLE_YUVFILE  
  241.                         int y_size=picref->video->w*picref->video->h;  
  242.                         fwrite(picref->data[0],1,y_size,fp_yuv);     //Y  
  243.                         fwrite(picref->data[1],1,y_size/4,fp_yuv);   //U  
  244.                         fwrite(picref->data[2],1,y_size/4,fp_yuv);   //V  
  245. #endif  
  246.                           
  247. #if ENABLE_SDL  
  248.                         SDL_LockYUVOverlay(bmp);  
  249.                         int y_size=picref->video->w*picref->video->h;  
  250.                         memcpy(bmp->pixels[0],picref->data[0],y_size);   //Y  
  251.                         memcpy(bmp->pixels[2],picref->data[1],y_size/4); //U  
  252.                         memcpy(bmp->pixels[1],picref->data[2],y_size/4); //V   
  253.                         bmp->pitches[0]=picref->linesize[0];  
  254.                         bmp->pitches[2]=picref->linesize[1];     
  255.                         bmp->pitches[1]=picref->linesize[2];  
  256.                         SDL_UnlockYUVOverlay(bmp);   
  257.                         rect.x = 0;      
  258.                         rect.y = 0;      
  259.                         rect.w = picref->video->w;      
  260.                         rect.h = picref->video->h;      
  261.                         SDL_DisplayYUVOverlay(bmp, &rect);   
  262.                         //Delay 40ms  
  263.                         SDL_Delay(40);  
  264. #endif  
  265.                         avfilter_unref_bufferp(&picref);  
  266.                     }  
  267.                 }  
  268.             }  
  269.         }  
  270.         av_free_packet(&packet);  
  271.     }  
  272. #if ENABLE_YUVFILE  
  273.     fclose(fp_yuv);  
  274. #endif  
  275. end:  
  276.     avfilter_graph_free(&filter_graph);  
  277.     if (pCodecCtx)  
  278.         avcodec_close(pCodecCtx);  
  279.     avformat_close_input(&pFormatCtx);  
  280.   
  281.     if (ret < 0 && ret != AVERROR_EOF) {  
  282.         char buf[1024];  
  283.         av_strerror(ret, buf, sizeof(buf));  
  284.         printf("Error occurred: %s\n", buf);  
  285.         return -1;  
  286.     }  
  287.   
  288.     return 0;  
  289. }  


结果

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

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


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


 

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

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

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



输出的YUV文件如图所示。



下载


simplest ffmpeg video filter


项目主页

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

Github:https://github.com/leixiaohua1020/simplest_ffmpeg_video_filter

开源中国:http://git.oschina.net/leixiaohua1020/simplest_ffmpeg_video_filter


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上已经修正该问题。


更新-1.2 (2015.2.13)=========================================

这次考虑到了跨平台的要求,调整了源代码。经过这次调整之后,源代码可以在以下平台编译通过:

VC++:打开sln文件即可编译,无需配置。

cl.exe:打开compile_cl.bat即可命令行下使用cl.exe进行编译,注意可能需要按照VC的安装路径调整脚本里面的参数。编译命令如下。

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. ::VS2010 Environment  
  2. call "D:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"  
  3. ::include  
  4. @set INCLUDE=include;%INCLUDE%  
  5. ::lib  
  6. @set LIB=lib;%LIB%  
  7. ::compile and link  
  8. cl simplest_ffmpeg_video_filter.cpp /MD /link SDL.lib SDLmain.lib avcodec.lib ^  
  9. avformat.lib avutil.lib avdevice.lib avfilter.lib postproc.lib swresample.lib swscale.lib ^  
  10. /SUBSYSTEM:WINDOWS /OPT:NOREF  

MinGW:MinGW命令行下运行compile_mingw.sh即可使用MinGW的g++进行编译。编译命令如下。

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. g++ simplest_ffmpeg_video_filter.cpp -g -o simplest_ffmpeg_video_filter.exe \  
  2. -I /usr/local/include -L /usr/local/lib \  
  3. -lmingw32 -lSDLmain -lSDL -lavformat -lavcodec -lavutil -lavfilter -lswscale  

GCC(Linux):Linux命令行下运行compile_gcc.sh即可使用GCC进行编译。编译命令如下。

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. gcc simplest_ffmpeg_video_filter.cpp -g -o simplest_ffmpeg_video_filter.out \  
  2. -I /usr/local/include -L /usr/local/lib \  
  3. -lSDLmain -lSDL -lavformat -lavcodec -lavutil -lavfilter -lswscale  

GCC(Mac):终端下运行compile_gcc_mac.sh即可使用GCC进行编译。编译命令如下。

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. gcc simplest_ffmpeg_video_filter.cpp -g -o simplest_ffmpeg_video_filter.out \  
  2. -framework Cocoa -I /usr/local/include -L /usr/local/lib \  
  3. -lSDLmain -lSDL -lavformat -lavcodec -lavutil -lavfilter -lswscale  

PS:相关的编译命令已经保存到了工程文件夹中


CSDN下载地址:http://download.csdn.net/detail/leixiaohua1020/8445551

SourceForge上已经更新。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值