1. 程式人生 > >(轉)FFMPEG filter使用實例(實現視頻縮放,裁剪,水印等)

(轉)FFMPEG filter使用實例(實現視頻縮放,裁剪,水印等)

mina fort clean target mes dev 更多 nom 連接

本文轉載自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:[email protected]"; 具體含義是 width 和 height 表示添加網格的寬和高,thickness表示網格的線寬,color表示顏色 。

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

(轉)FFMPEG filter使用實例(實現視頻縮放,裁剪,水印等)