FFMPEG 最简滤镜filter使用实例(实现视频缩放,裁剪,水印等)

 FFMPEG官网给出了FFMPEG 滤镜使用的实例,它是将视频中的像素点替换成字符,然后从终端输出。我在该实例的基础上稍微的做了修改,使它能够保存滤镜处理过后的文件。在上代码之前先明白几个概念:

    Filter:代表单个filter 
    FilterPad:代表一个filter的输入或输出端口,每个filter都可以有多个输入和多个输出,只有输出pad的filter称为source,只有输入pad的filter称为sink 
    FilterLink:若一个filter的输出pad和另一个filter的输入pad名字相同,即认为两个filter之间建立了link 
    FilterChain:代表一串相互连接的filters,除了source和sink外,要求每个filter的输入输出pad都有对应的输出和输入pad 

经典示例:

    图中的一系列操作共使用了四个filter,分别是 
    splite:将输入的流进行分裂复制,分两路输出。 
    crop:根据给定的参数,对视频进行裁剪 
    vflip:根据给定参数,对视频进行翻转等操作 
    overlay:将一路输入覆盖到另一路之上,合并输出为一路视频 

下面上代码:

 

[objc] view plain copy

 

 print?

  1. /*=============================================================================  
  2. #     FileName: filter_video.c  
  3. #         Desc: an example of ffmpeg fileter 
  4. #       Author: licaibiao  
  5. #   LastChange: 2017-03-16   
  6. =============================================================================*/   
  7. #define _XOPEN_SOURCE 600 /* for usleep */  
  8. #include <unistd.h>  
  9.   
  10. #include "avcodec.h"  
  11. #include "avformat.h"  
  12. #include "avfiltergraph.h"  
  13. #include "avcodec.h"  
  14. #include "buffersink.h"  
  15. #include "buffersrc.h"  
  16. #include "opt.h"  
  17.   
  18. #define SAVE_FILE  
  19.   
  20. const charchar *filter_descr = "scale=iw*2:ih*2";  
  21. static AVFormatContext *fmt_ctx;  
  22. static AVCodecContext *dec_ctx;  
  23. AVFilterContext *buffersink_ctx;  
  24. AVFilterContext *buffersrc_ctx;  
  25. AVFilterGraph *filter_graph;  
  26. static int video_stream_index = -1;  
  27. static int64_t last_pts = AV_NOPTS_VALUE;  
  28.   
  29. static int open_input_file(const charchar *filename)  
  30. {  
  31.     int ret;  
  32.     AVCodec *dec;  
  33.   
  34.     if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {  
  35.         av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");  
  36.         return ret;  
  37.     }  
  38.   
  39.     if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {  
  40.         av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");  
  41.         return ret;  
  42.     }  
  43.   
  44.     /* select the video stream  判断流是否正常 */  
  45.     ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);  
  46.     if (ret < 0) {  
  47.         av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n");  
  48.         return ret;  
  49.     }  
  50.     video_stream_index = ret;  
  51.     dec_ctx = fmt_ctx->streams[video_stream_index]->codec;  
  52.     av_opt_set_int(dec_ctx, "refcounted_frames", 1, 0); /* refcounted_frames 帧引用计数 */  
  53.   
  54.     /* init the video decoder */  
  55.     if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {  
  56.         av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");  
  57.         return ret;  
  58.     }  
  59.   
  60.     return 0;  
  61. }  
  62.   
  63. static int init_filters(const charchar *filters_descr)  
  64. {  
  65.     char args[512];  
  66.     int ret = 0;  
  67.     AVFilter *buffersrc  = avfilter_get_by_name("buffer");     /* 输入buffer filter */  
  68.     AVFilter *buffersink = avfilter_get_by_name("buffersink"); /* 输出buffer filter */  
  69.     AVFilterInOut *outputs = avfilter_inout_alloc();  
  70.     AVFilterInOut *inputs  = avfilter_inout_alloc();  
  71.     AVRational time_base = fmt_ctx->streams[video_stream_index]->time_base;   /* 时间基数 */  
  72.   
  73. #ifndef SAVE_FILE  
  74.     enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE };  
  75. #else  
  76.     enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE };  
  77. #endif  
  78.   
  79.     filter_graph = avfilter_graph_alloc();                     /* 创建graph  */  
  80.     if (!outputs || !inputs || !filter_graph) {  
  81.         ret = AVERROR(ENOMEM);  
  82.         goto end;  
  83.     }  
  84.   
  85.     /* buffer video source: the decoded frames from the decoder will be inserted here. */  
  86.     snprintf(args, sizeof(args),  
  87.             "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",  
  88.             dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,  
  89.             time_base.num, time_base.den,  
  90.             dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);  
  91.   
  92.     /* 创建并向FilterGraph中添加一个Filter */  
  93.     ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",  
  94.                                        args, NULL, filter_graph);             
  95.     if (ret < 0) {  
  96.         av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");  
  97.         goto end;  
  98.     }  
  99.   
  100.     /* buffer video sink: to terminate the filter chain. */  
  101.     ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",  
  102.                                        NULL, NULL, filter_graph);            
  103.     if (ret < 0) {  
  104.         av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");  
  105.         goto end;  
  106.     }  
  107.   
  108.      /* Set a binary option to an integer list. */  
  109.     ret = av_opt_set_int_list(buffersink_ctx, "pix_fmts", pix_fmts,  
  110.                               AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);     
  111.     if (ret < 0) {  
  112.         av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\n");  
  113.         goto end;  
  114.     }  
  115.   
  116.     /* 
  117.      * Set the endpoints for the filter graph. The filter_graph will 
  118.      * be linked to the graph described by filters_descr. 
  119.      */  
  120.   
  121.     /* 
  122.      * The buffer source output must be connected to the input pad of 
  123.      * the first filter described by filters_descr; since the first 
  124.      * filter input label is not specified, it is set to "in" by 
  125.      * default. 
  126.      */  
  127.     outputs->name       = av_strdup("in");  
  128.     outputs->filter_ctx = buffersrc_ctx;  
  129.     outputs->pad_idx    = 0;  
  130.     outputs->next       = NULL;  
  131.   
  132.     /* 
  133.      * The buffer sink input must be connected to the output pad of 
  134.      * the last filter described by filters_descr; since the last 
  135.      * filter output label is not specified, it is set to "out" by 
  136.      * default. 
  137.      */  
  138.     inputs->name       = av_strdup("out");  
  139.     inputs->filter_ctx = buffersink_ctx;  
  140.     inputs->pad_idx    = 0;  
  141.     inputs->next       = NULL;  
  142.   
  143.     /* Add a graph described by a string to a graph */  
  144.     if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr,  
  145.                                     &inputs, &outputs, NULL)) < 0)      
  146.         goto end;  
  147.   
  148.     /* Check validity and configure all the links and formats in the graph */  
  149.     if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)     
  150.         goto end;  
  151.   
  152. end:  
  153.     avfilter_inout_free(&inputs);  
  154.     avfilter_inout_free(&outputs);  
  155.   
  156.     return ret;  
  157. }  
  158.   
  159. #ifndef SAVE_FILE  
  160. static void display_frame(const AVFrame *frame, AVRational time_base)  
  161. {  
  162.     int x, y;  
  163.     uint8_t *p0, *p;  
  164.     int64_t delay;  
  165.   
  166.     if (frame->pts != AV_NOPTS_VALUE) {  
  167.         if (last_pts != AV_NOPTS_VALUE) {  
  168.             /* sleep roughly the right amount of time; 
  169.              * usleep is in microseconds, just like AV_TIME_BASE. */  
  170.              /* 计算 pts 是用来把时间戳从一个时基调整到另外一个时基时候用的函数 */  
  171.             delay = av_rescale_q(frame->pts - last_pts,  
  172.                                  time_base, AV_TIME_BASE_Q);  
  173.             if (delay > 0 && delay < 1000000)  
  174.                 usleep(delay);  
  175.         }  
  176.         last_pts = frame->pts;  
  177.     }  
  178.   
  179.     /* Trivial ASCII grayscale display. */  
  180.     p0 = frame->data[0];  
  181.     puts("\033c");  
  182.     for (y = 0; y < frame->height; y++) {  
  183.         p = p0;  
  184.         for (x = 0; x < frame->width; x++)  
  185.             putchar(" .-+#"[*(p++) / 52]);  
  186.         putchar('\n');  
  187.         p0 += frame->linesize[0];  
  188.     }  
  189.     fflush(stdout);  
  190. }  
  191. #else  
  192. FILEFILE * file_fd;  
  193. static void write_frame(const AVFrame *frame)  
  194. {  
  195.     static int printf_flag = 0;  
  196.     if(!printf_flag){  
  197.         printf_flag = 1;  
  198.         printf("frame widht=%d,frame height=%d\n",frame->width,frame->height);  
  199.           
  200.         if(frame->format==AV_PIX_FMT_YUV420P){  
  201.             printf("format is yuv420p\n");  
  202.         }  
  203.         else{  
  204.             printf("formet is = %d \n",frame->format);  
  205.         }  
  206.       
  207.     }  
  208.   
  209.     fwrite(frame->data[0],1,frame->width*frame->height,file_fd);  
  210.     fwrite(frame->data[1],1,frame->width/2*frame->height/2,file_fd);  
  211.     fwrite(frame->data[2],1,frame->width/2*frame->height/2,file_fd);  
  212. }  
  213.   
  214. #endif  
  215.   
  216. int main(int argc, charchar **argv)  
  217. {  
  218.     int ret;  
  219.     AVPacket packet;  
  220.     AVFrame *frame = av_frame_alloc();  
  221.     AVFrame *filt_frame = av_frame_alloc();  
  222.     int got_frame;  
  223.   
  224. #ifdef SAVE_FILE  
  225.     file_fd = fopen("test.yuv","wb+");  
  226. #endif  
  227.   
  228.     if (!frame || !filt_frame) {  
  229.         perror("Could not allocate frame");  
  230.         exit(1);  
  231.     }  
  232.     if (argc != 2) {  
  233.         fprintf(stderr, "Usage: %s file\n", argv[0]);  
  234.         exit(1);  
  235.     }  
  236.   
  237.     av_register_all();  
  238.     avfilter_register_all();  
  239.   
  240.     if ((ret = open_input_file(argv[1])) < 0)  
  241.         goto end;  
  242.     if ((ret = init_filters(filter_descr)) < 0)  
  243.         goto end;  
  244.   
  245.     /* read all packets */  
  246.     while (1) {  
  247.         if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)  
  248.             break;  
  249.   
  250.         if (packet.stream_index == video_stream_index) {  
  251.             got_frame = 0;  
  252.             ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, &packet);  
  253.             if (ret < 0) {  
  254.                 av_log(NULL, AV_LOG_ERROR, "Error decoding video\n");  
  255.                 break;  
  256.             }  
  257.   
  258.             if (got_frame) {  
  259.                 frame->pts = av_frame_get_best_effort_timestamp(frame);    /* pts: Presentation Time Stamp */  
  260.   
  261.                 /* push the decoded frame into the filtergraph */  
  262.                 if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {  
  263.                     av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");  
  264.                     break;  
  265.                 }  
  266.   
  267.                 /* pull filtered frames from the filtergraph */  
  268.                 while (1) {  
  269.                     ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);  
  270.                     if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)  
  271.                         break;  
  272.                     if (ret < 0)  
  273.                         goto end;  
  274. #ifndef SAVE_FILE  
  275.                     display_frame(filt_frame, buffersink_ctx->inputs[0]->time_base);  
  276. #else  
  277.                     write_frame(filt_frame);  
  278. #endif  
  279.                     av_frame_unref(filt_frame);  
  280.                 }  
  281.                 /* Unreference all the buffers referenced by frame and reset the frame fields. */  
  282.                 av_frame_unref(frame);  
  283.             }  
  284.         }  
  285.         av_packet_unref(&packet);  
  286.     }  
  287. end:  
  288.     avfilter_graph_free(&filter_graph);  
  289.     avcodec_close(dec_ctx);  
  290.     avformat_close_input(&fmt_ctx);  
  291.     av_frame_free(&frame);  
  292.     av_frame_free(&filt_frame);  
  293.   
  294.     if (ret < 0 && ret != AVERROR_EOF) {  
  295.         fprintf(stderr, "Error occurred: %s\n", av_err2str(ret));  
  296.         exit(1);  
  297.     }  
  298. #ifdef SAVE_FILE  
  299.     fclose(file_fd);  
  300. #endif  
  301.     exit(0);  
  302. }  

 

该工程中,我的Makefile文件如下:

 

[objc] view plain copy

 

 print?

  1. OUT_APP      = test  
  2. INCLUDE_PATH = /usr/local/include/  
  3. INCLUDE = -I$(INCLUDE_PATH)libavutil/ -I$(INCLUDE_PATH)libavdevice/ \  
  4.             -I$(INCLUDE_PATH)libavcodec/ -I$(INCLUDE_PATH)libswresample \  
  5.             -I$(INCLUDE_PATH)libavfilter/ -I$(INCLUDE_PATH)libavformat \  
  6.             -I$(INCLUDE_PATH)libswscale/  
  7.   
  8. FFMPEG_LIBS = -lavformat -lavutil -lavdevice -lavcodec -lswresample -lavfilter -lswscale  
  9. SDL_LIBS    =   
  10. LIBS        = $(FFMPEG_LIBS)$(SDL_LIBS)  
  11.   
  12. COMPILE_OPTS = $(INCLUDE)  
  13. C            = c  
  14. OBJ          = o  
  15. C_COMPILER   = cc  
  16. C_FLAGS      = $(COMPILE_OPTS) $(CPPFLAGS) $(CFLAGS)  
  17.   
  18. LINK         = cc -o   
  19. LINK_OPTS    = -lz -lm  -lpthread  
  20. LINK_OBJ     = test.o   
  21.   
  22. .$(C).$(OBJ):  
  23.     $(C_COMPILER) -c $(C_FLAGS) $<  
  24.   
  25.   
  26. $(OUT_APP): $(LINK_OBJ)  
  27.     $(LINK)$@  $(LINK_OBJ)  $(LIBS) $(LINK_OPTS)  
  28.   
  29. clean:  
  30.         -rm -rf *.$(OBJ) $(OUT_APP) core *.core *~ *yuv  

 

运行结果如下:

 

[objc] view plain copy

 

 print?

  1. licaibiao@ubuntu:~/test/FFMPEG/filter$ ls  
  2. Makefile  school.flv  test  test.c  test.o  
  3. licaibiao@ubuntu:~/test/FFMPEG/filter$ ./test school.flv  
  4. [flv @ 0x12c16c0] video stream discovered after head already parsed  
  5. [flv @ 0x12c16c0] audio stream discovered after head already parsed  
  6. frame widht=1024,frame height=576  
  7. format is yuv420p  
  8. licaibiao@ubuntu:~/test/FFMPEG/filter$ ls  
  9. Makefile  school.flv  test  test.c  test.o  test.yuv  

 

    在这里,我打印出来了输出视频的格式和图片的长和宽,该实例生成的是一个YUV420 格式的视频,使用YUV播放器播放视频的时候,需要设置正确的视频长度和宽度。在代码中通过设置enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE };来设置输出格式。

    过滤器的参数设置是通过const char *filter_descr = "scale=iw*2:ih*2"; 来设置。它表示将视频的长和框都拉伸到原来的两倍。具体的filter参数可以通过命令:ffmpeg -filters 来查询。结果如下:

 

[objc] view plain copy

 

 print?

  1. Filters:  
  2.   T.. = Timeline support  
  3.   .S. = Slice threading  
  4.   ..C = Command support  
  5.   A = Audio input/output  
  6.   V = Video input/output  
  7.   N = Dynamic number and/or type of input/output  
  8.   | = Source or sink filter  
  9.  ... abench            A->A       Benchmark part of a filtergraph.  
  10.  ... acompressor       A->A       Audio compressor.  
  11.  ... acrossfade        AA->A      Cross fade two input audio streams.  
  12.  ... acrusher          A->A       Reduce audio bit resolution.  
  13. .............................................................................  

 

    在上面的代码中,我们设置的是将图片拉升到原来图像的两倍,其显示效果如下,可能是截图的问题,这里看好像没有拉伸到两倍。

原图

 

 

拉伸后

 

 

在上面的代码中,我们设置的是:

    const char *filter_descr = "scale=iw*2:ih*2";   iw 表示输入视频的宽,ih表示输入视频的高。可以任意比例的缩放视频。这里*2 表示放大两倍,如果是/2表示缩小两倍。

视频缩放还可以直接设置:

     const char *filter_descr = "scale=320:240"; 设置视频输出宽为320,高位240,当然也是可以随意的设置其他的参数。

 

视频的裁剪可以设置为:

    const char *filter_descr = "crop=320:240:0:0";   具体含义是 crop=width:height:x:y,其中 width 和 height 表示裁剪后的尺寸,x:y 表示裁剪区域的左上角坐标。

  

视频添加一个网格水印可以设置为:

    const char *filter_descr = "drawgrid=width=100:height=100:thickness=2:color=red@0.5";    具体含义是 width 和 height 表示添加网格的宽和高,thickness表示网格的线宽,color表示颜色 。其效果如下:

    更多filter参数的使用,可以直接参考ffmpeg 的官方文档:http://www.ffmpeg.org/ffmpeg-filters.html

时间: 2024-09-19 09:08:14

FFMPEG 最简滤镜filter使用实例(实现视频缩放,裁剪,水印等)的相关文章

FFMPEG基于内存的转码实例——输入输出视频均在内存

我在6月份写了篇文章<FFMPEG基于内存的转码实例>,讲如何把视频转码后放到内存,然后通过网络发送出去.但该文章只完成了一半,即输入的数据依然是从磁盘文件中读取.在实际应用中,有很多数据是放到内存的,比如播放从服务器接收到的视频,就是在内存中的.时隔2个月,项目终于完成了,虽然在收尾阶段会花费大量时间,但也算空闲了点.于是就继续完善. 本文中,假定的使用场合是,有一个已经放到内存的视频,需要将它转码成另一种封装格式,还是放到内存中.由于是测试,首先将视频从文件中读取到内存,最后会将转换好的视

photoshop碎片滤镜的使用实例介绍

  photoshop作为图片处理工具的佼佼者,今天小编教大家photoshop碎片滤镜的使用,教程比较基础,希望能对大家有所帮助! 方法/步骤 如图所示,我们点击箭头所指的photoshop软件图标,打开photoshop软件. 如图所示,我们点击箭头所指的"文件"这一项. 如图所示,在弹出的列表菜单中,我们点击箭头所指的"打开(O)..."这一项. 如图所示,我们选择一张图片,接下来我们点击箭头所指的"打开"按钮. 如图所示,点击"

AngularJS过滤器filter用法实例分析_AngularJS

本文实例讲述了AngularJS过滤器filter用法.分享给大家供大家参考,具体如下: 这节我们来看看angularjs的过滤器filter. 在我们开发中经常需要在页面显示给用户的信息需要一定处理格式化,才能显示给用户.比如时间本地化,或者yyyy-MM-dd HH:mm:ss格式,数字精度格式化,本地化,人名格式化等等.在angularjs中为我们提供了叫filter的指令,让我们能够很轻易就能做到着一些列的功能,angularjs内部为我们提供了number等很多内置的filter.并且

Application 简介绍与计数器实例

application 简介绍与计数器实例 event-handling方法描述 application_start()发生当应用程序的开始 这是他第一次收到任何用户的要求. application_end()发生当应用程序正在关闭的时候,通常而言,是因为网络服务器正在重新启动. application_beginrequest()中,发生在每个请求的应用得到的,就在这个页面代码被执行. application_endrequest() 简单存值实例 <%@ page language="

编码-FFMPEG实时解码RTP传输的H264流视频花屏

问题描述 FFMPEG实时解码RTP传输的H264流视频花屏 自己用QT写的程序,在PC上采集视频编码RTP打包发送.如果发送给自己,然后用VLC播放的话是可以正常显示的(尽管延迟会不断增大,这个问题再待解决),但是用自己编的软件确无法正常显示,能看到一瞬间有部分画面正常,然后一会画面就糊掉了. 同样的代码, 我在树莓派上,用OPENMAX硬件加速编码,然后同样的打包方式发送,发送给树莓派自己或者给PC,都能正常地显示. 不知道这个是哪部分出了原因?到底是FFMPEG编码部分出问题,还是接收的代

【FFMpeg视频开发与应用基础】八、 调用FFMpeg SDK实现视频缩放

<FFMpeg视频开发与应用基础--使用FFMpeg工具与SDK>视频教程已经在"CSDN学院"上线,视频中包含了从0开始逐行代码实现FFMpeg视频开发的过程,欢迎观看!链接地址:FFMpeg视频开发与应用基础--使用FFMpeg工具与SDK Github工程代码地址:FFmpeg_Tutorial 视频缩放是视频开发中一项最基本的功能.通过对视频的像素数据进行采样或插值,可以将低分辨率的视频转换到更高的分辨率,或者将高分辨率的视频转换为更低的分辨率.通过FFMpeg提供

ffmpeg获取mp4文件中的第一个视频帧的时间戳是怎么设定的?

问题描述 ffmpeg获取mp4文件中的第一个视频帧的时间戳是怎么设定的? ffmpeg获取mp4文件中的第一个视频帧的时间戳是怎么设定的?是在mp4录制时指定的吗?从第二帧开始mp4writesample的时间戳是与前一帧的差值,第一帧的时间戳是哪来的?

asp.net中上传图片文件实例(给上传图片加水印)

本款asp教程.net教程是一款asp.net教程中上传图片文件实例(给上传图片加水印)哦,他先是把图片上传服务器,然后增加图片水印,再把图片保存到数据库教程. // 涉及命名空间 using system; using system.collections; using system.componentmodel; using system.data; using system.data.sqlclient; using system.drawing; using system.drawing

ASP.NET MVC入门 10、Action Filter与内置的Filter实现(实例-防盗链)

前一篇中我们已经了解了Action Filter与内置的Filter实现,现在我们就来 写一个实例.就写一个防盗链的Filter吧. 首先继承自FilterAttribute 类同时实现IActionFilter接口,代码如下: /**//// <summary>/// 防盗链Filter./// </summary>public class AntiOutSiteLinkAttribute : ActionFilterAttribute, IActionFilter{ publi