Filter,可以認(rèn)為是一些預(yù)定義的范式,可以實(shí)現(xiàn)類似積木的多種功能的自由組合。每個(gè)filter都有固定數(shù)目的輸入和輸出,而且實(shí)際使用中不允許有空 懸的輸入輸出端。使用文本描述時(shí)我們可以通過標(biāo)識(shí)符指定輸入和輸出端口,將不同filter串聯(lián)起來(lái),構(gòu)成更復(fù)雜的filter。這就形成了嵌套的 filter。當(dāng)然每個(gè)filter可以通過ffmpeg/ffplay命令行實(shí)現(xiàn),但通常filter更方便。
Filter能做什么?
比較常見的有:
- 音視頻的倍速播放
- 視頻添加刪除Logo
- 視頻畫中畫
- 放大縮小
- 畫面裁剪
源碼
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/opt.h>
static AVFormatContext *fmt_ctx;
static AVCodecContext *dec_ctx;
AVFilterContext *buffersink_ctx;
AVFilterContext *buffersrc_ctx;
AVFilterGraph *filter_graph;
static int video_stream_index = -1;
//打開輸入文件
static int open_input_file(const char *filename)
{
int ret;
AVCodec *dec;
if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
return ret;
}
if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
return ret;
}
//選擇視頻流
ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n");
return ret;
}
video_stream_index = ret;
/* create decoding context */
dec_ctx = avcodec_alloc_context3(dec);
if (!dec_ctx)
return AVERROR(ENOMEM);
avcodec_parameters_to_context(dec_ctx, fmt_ctx->streams[video_stream_index]->codecpar);
//初始化解碼器
if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");
return ret;
}
return 0;
}
//初始化filter
static int init_filters(const char *filters_descr)
{
char args[512];
int ret = 0;
//濾鏡輸入緩沖區(qū),解碼器解碼后的數(shù)據(jù)都會(huì)放到buffer中,是一個(gè)特殊的filter
const AVFilter *buffersrc = avfilter_get_by_name("buffer");
//濾鏡輸出緩沖區(qū),濾鏡處理完后輸出的數(shù)據(jù)都會(huì)放在buffersink中,是一個(gè)特殊的filter
const AVFilter *buffersink = avfilter_get_by_name("buffersink");
AVFilterInOut *outputs = avfilter_inout_alloc();
AVFilterInOut *inputs = avfilter_inout_alloc();
AVRational time_base = fmt_ctx->streams[video_stream_index]->time_base;
enum AVPixelFormat pix_fmts[] = {AV_PIX_FMT_YUV420P, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE};
//創(chuàng)建filter圖,會(huì)包含本次使用到的所有過濾器
filter_graph = avfilter_graph_alloc();
if (!outputs || !inputs || !filter_graph) {
ret = AVERROR(ENOMEM);
goto end;
}
/* buffer video source: the decoded frames from the decoder will be inserted here. */
snprintf(args, sizeof(args),
"video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,
time_base.num, time_base.den,
dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
//創(chuàng)建過濾器實(shí)例并將其添加到現(xiàn)有g(shù)raph中
ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
args, NULL, filter_graph);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
goto end;
}
/* 緩沖視頻接收器: 終止過濾器鏈 */
ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
NULL, NULL, filter_graph);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
goto end;
}
ret = av_opt_set_int_list(buffersink_ctx, "pix_fmts", pix_fmts,
AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\n");
goto end;
}
/*
* Set the endpoints for the filter graph. The filter_graph will
* be linked to the graph described by filters_descr.
*/
/*
* The buffer source output must be connected to the input pad of
* the first filter described by filters_descr; since the first
* filter input label is not specified, it is set to "in" by
* default.
*/
outputs->name = av_strdup("in");
outputs->filter_ctx = buffersrc_ctx;
outputs->pad_idx = 0;
outputs->next = NULL;
/*
* The buffer sink input must be connected to the output pad of
* the last filter described by filters_descr; since the last
* filter output label is not specified, it is set to "out" by
* default.
*/
inputs->name = av_strdup("out");
inputs->filter_ctx = buffersink_ctx;
inputs->pad_idx = 0;
inputs->next = NULL;
//將由字符串描述的圖形添加到圖形中
if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr,
&inputs, &outputs, NULL)) < 0)
goto end;
if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
goto end;
end:
avfilter_inout_free(&inputs);
avfilter_inout_free(&outputs);
return ret;
}
//保存YUV數(shù)據(jù)
static int save_frame(AVFrame *filt_frame, FILE *out){
av_log(NULL, AV_LOG_DEBUG, "do_frame %d\n",filt_frame->format);
if(filt_frame->format==AV_PIX_FMT_YUV420P){
av_log(NULL, AV_LOG_ERROR, "save 1 frame\n");
for(int i=0;i<filt_frame->height;i++){
fwrite(filt_frame->data[0]+filt_frame->linesize[0]*i,1,filt_frame->width,out);
}
for(int i=0;i<filt_frame->height/2;i++){
fwrite(filt_frame->data[1]+filt_frame->linesize[1]*i,1,filt_frame->width/2,out);
}
for(int i=0;i<filt_frame->height/2;i++){
fwrite(filt_frame->data[2]+filt_frame->linesize[2]*i,1,filt_frame->width/2,out);
}
}
fflush(out);
return 0;
}
int main(int argc, char **argv)
{
int ret;
AVPacket packet;
AVFrame *frame;
AVFrame *filt_frame;
FILE *out = NULL;
const char *filter_desc="movie=my_logo.png[wm];[in][wm]overlay=5:5[out]"; //左上角繪制一個(gè)logo圖片
//"drawbox=30:10:64:64:red";//x= 30,y=10,width=64,height=64,color=red,繪制一個(gè)紅色正方形
const char* filename = "/Users/liuwei/Desktop/test.mp4";
const char* outfile = "/Users/liuwei/Desktop/new_test.yuv";
av_log_set_level(AV_LOG_DEBUG);
frame = av_frame_alloc();
filt_frame = av_frame_alloc();
if (!frame || !filt_frame) {
perror("Could not allocate frame");
exit(1);
}
out = fopen(outfile, "wb");
if(!out){
av_log(NULL, AV_LOG_ERROR, "Failed to open yuv file!\n");
exit(-1);
}
if ((ret = open_input_file(filename)) < 0)
goto end;
if ((ret = init_filters(filter_desc)) < 0)
goto end;
/* read all packets */
while (1) {
// 1
if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
break;
if (packet.stream_index == video_stream_index) {
//2
ret = avcodec_send_packet(dec_ctx, &packet);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error while sending a packet to the decoder\n");
break;
}
while (ret >= 0) {
//3
ret = avcodec_receive_frame(dec_ctx, frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
break;
} else if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error while receiving a frame from the decoder\n");
goto end;
}
frame->pts = frame->best_effort_timestamp;
/*4 push the decoded frame into the filtergraph */
if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
break;
}
/* pull filtered frames from the filtergraph */
while (1) {
//5
ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
break;
if (ret < 0)
goto end;
save_frame(filt_frame,out);
av_frame_unref(filt_frame);
}
av_frame_unref(frame);
}
}
av_packet_unref(&packet);
}
end:
avfilter_graph_free(&filter_graph);
avcodec_free_context(&dec_ctx);
avformat_close_input(&fmt_ctx);
av_frame_free(&frame);
av_frame_free(&filt_frame);
if (ret < 0 && ret != AVERROR_EOF) {
fprintf(stderr, "Error occurred: %s\n", av_err2str(ret));
exit(1);
}
exit(0);
}
代碼中關(guān)鍵函數(shù):
avfilter_graph_alloc():為FilterGraph分配內(nèi)存。
avfilter_graph_create_filter():創(chuàng)建并向FilterGraph中添加一個(gè)Filter。
avfilter_graph_parse_ptr():將一串通過字符串描述的Graph添加到FilterGraph中。
avfilter_graph_config():檢查FilterGraph的配置。
av_buffersrc_add_frame():向FilterGraph中加入一個(gè)AVFrame。
av_buffersink_get_frame():從FilterGraph中取出一個(gè)AVFrame。
*filter_desc="movie=my_logo.png[wm];[in][wm]overlay=5:5[out]";
代碼會(huì)將一個(gè)MP4文件在左上角添加一個(gè)圖片后輸出為yuv文件,這個(gè)圖片如果背景是透明的就是水印啦(主要是懶得做透明背景圖片)。

"drawbox=30:10:64:64:red";x= 30,y=10,width=64,height=64,color=red, 繪制一個(gè)紅色正方形

"scale=iw*2:ih*2"視頻縮放,iw 表示輸入視頻的寬,ih表示輸入視頻的高。*2 表示放大兩倍,如果是/2表示縮小兩倍
"crop=320:240:0:0"視頻裁剪,crop=width:height : x : y,其中 width 和 height 表示裁剪后的尺寸,x:y 表示裁剪區(qū)域的左上角坐標(biāo)
還有很多filter可以使用,并且可以實(shí)現(xiàn)自定義filter,這些后面會(huì)慢慢了解。