(转)FFMPEG filter使用实例(实现视频缩放,裁剪,水印等)

本文转载自http://blog.csdn.net/li_wen01/article/details/62442162

 

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:将一路输入覆盖到另一路之上,合并输出为一路视频 

下面上代码:

  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文件如下:

 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  

运行结果如下:

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 来查询。结果如下:

 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

posted @ 2019-01-09 21:58  jiu~  阅读(2183)  评论(0编辑  收藏  举报