title: ffmpeg_sample解讀_filtering_video
date: 2020-10-28 10:15:02
tags: [讀書筆記]
typora-copy-images-to: ./imgs
typora-root-url: ./imgs
總結(jié)
和之前的類似.初始化過濾器.從參數(shù)中讀進(jìn)來str也會(huì)轉(zhuǎn)換成過濾器.然后把他們連接起來,冉家解碼視頻.取出解碼后的幀,送入過濾器處理.取出處理完的幀,然后展示出來.流程和前幾個(gè)過濾器的都差不多.主要都是在看過濾器的連接和添加
流程圖
graph TB
if[init_filters]
-->afgbn[avfilter_get_by_name]
-->afia[avfilter_inout_alloc]
-->afga[avfilter_graph_alloc]
-->afgcf[avfilter_graph_create_filter]
-->aosil[av_opt_set_int_list]
-->afgpp[avfilter_graph_parse_ptr]
-->afgc[avfilter_graph_config]
-->arf{av_read_frame>0?}
-->|yes|acsp[avcodec_send_packet]
arf-->|no|free[free]
acsp-->acrf{avcodec_receive_frame>0?}
-->|no|free[free]
acrf-->|yes|abaff[av_buffersrc_add_frame_flags]
-->absgf[av_buffersink_get_frame]
-->df[display_frame]
-->free[free]
image-20201029112249767
代碼
/**
* @file
* API example for decoding and filtering
* @example filtering_video.c
*/
#define _XOPEN_SOURCE 600 /* for usleep */
#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>
const char *filter_descr = "scale=78:24,transpose=cclock";
/* other way:
scale=78:24 [scl]; [scl] transpose=cclock // assumes "[in]" and "[out]" to be input output pads respectively
*/
static AVFormatContext *fmt_ctx;
static AVCodecContext *dec_ctx;
AVFilterContext *buffersink_ctx;//出參的過濾器上下文
AVFilterContext *buffersrc_ctx;//入?yún)⒌倪^濾器上下文
AVFilterGraph *filter_graph;
static int video_stream_index = -1;
static int64_t last_pts = AV_NOPTS_VALUE;
/**
* 打開輸入文件,和音頻處理類似. 解碼出幀后.放入過濾器中處理
* 過濾器有一個(gè)輸入過濾器,一個(gè)輸出過濾器.中又混合了string組成的過濾器.通過 AVFilterGraph 連接起來
* @param filename
* @return
*/
static int open_input_file(const char *filename)
{
int ret;
AVCodec *dec;
//打開文件.創(chuàng)建ftm_ctx格式上下文
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;
}
/* select the video stream */
//選擇視頻流,得到索引,獲取解碼器
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;
//創(chuàng)建解碼器上下文
/* create decoding context */
dec_ctx = avcodec_alloc_context3(dec);
if (!dec_ctx)
return AVERROR(ENOMEM);
//把視頻流中的解碼參數(shù)拷貝到解碼器上下文中
avcodec_parameters_to_context(dec_ctx, fmt_ctx->streams[video_stream_index]->codecpar);
/* init the video decoder */
//用解碼器來設(shè)置解碼器上下文的參數(shù)
if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");
return ret;
}
return 0;
}
/**
* 初始化過濾器
* @param filters_descr
* @return
*/
static int init_filters(const char *filters_descr)
{
char args[512];
int ret = 0;
//數(shù)據(jù)輸入輸出過濾器以及 分配的輸入輸出buf
const AVFilter *buffersrc = avfilter_get_by_name("buffer");
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_GRAY8, AV_PIX_FMT_NONE };
//初始化過濾器圖形.用來連接多個(gè)過濾器
filter_graph = avfilter_graph_alloc();
if (!outputs || !inputs || !filter_graph) {
ret = AVERROR(ENOMEM);
goto end;
}
//把參數(shù)都寫到 args里
/* 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);
//用args 參數(shù)和buufersrc初始化過濾器上下文,并添加到 過濾器圖形中, 返回改過濾器上下文
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;
}
//初始化另一個(gè)過濾器上下文,添加到過濾器圖形匯總,
/* buffer video sink: to terminate the filter chain. */
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;
}
//設(shè)置 pix_fmts屬性
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.
*/
//把兩個(gè)輸入輸出的 上下文綁定到這兩個(gè) inout的結(jié)構(gòu)體上,
// 這里我理解是,因?yàn)橛袀€(gè)字符串傳入的過濾器.這里是一種連接字符串產(chǎn)生的過濾器和上邊創(chuàng)建過濾器的方式
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.
*/
//這個(gè)輸出的input結(jié)構(gòu)體必須和 desrc 里的最好一個(gè)過濾器相連
inputs->name = av_strdup("out");
inputs->filter_ctx = buffersink_ctx;
inputs->pad_idx = 0;
inputs->next = NULL;
//把字符串解析出的過濾器和 inout 中的輸入輸出過濾器連接起來
if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr,
&inputs, &outputs, NULL)) < 0)
goto end;
//進(jìn)行配置
if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
goto end;
end:
avfilter_inout_free(&inputs);
avfilter_inout_free(&outputs);
return ret;
}
static void display_frame(const AVFrame *frame, AVRational time_base)
{
int x, y;
uint8_t *p0, *p;
int64_t delay;
if (frame->pts != AV_NOPTS_VALUE) {
if (last_pts != AV_NOPTS_VALUE) {
/* sleep roughly the right amount of time;
* usleep is in microseconds, just like AV_TIME_BASE. */
delay = av_rescale_q(frame->pts - last_pts,
time_base, AV_TIME_BASE_Q);
if (delay > 0 && delay < 1000000)
usleep(delay);
}
last_pts = frame->pts;
}
/* Trivial ASCII grayscale display. */
p0 = frame->data[0];
puts("\033c");
for (y = 0; y < frame->height; y++) {
p = p0;
for (x = 0; x < frame->width; x++)
putchar(" .-+#"[*(p++) / 52]);
putchar('\n');
p0 += frame->linesize[0];
}
fflush(stdout);
}
int filtering_video_main(int argc, char **argv)
{
int ret;
AVPacket packet;
AVFrame *frame;
AVFrame *filt_frame;
if (argc != 2) {
fprintf(stderr, "Usage: %s file\n", argv[0]);
exit(1);
}
frame = av_frame_alloc();
filt_frame = av_frame_alloc();
if (!frame || !filt_frame) {
perror("Could not allocate frame");
exit(1);
}
if ((ret = open_input_file(argv[1])) < 0)
goto end;
if ((ret = init_filters(filter_descr)) < 0)
goto end;
/* read all packets */
while (1) {
//讀取packet
if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
break;
//處理視頻
if (packet.stream_index == video_stream_index) {
//數(shù)據(jù)發(fā)送到解碼器
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) {
//解碼器中取出幀
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;
/* push the decoded frame into the filtergraph */
//把解碼后的幀數(shù)據(jù)放入過濾器圖中處理,
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) {//的到過濾器處理完的結(jié)果.輸出幀
ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
break;
if (ret < 0)
goto end;
//展示幀數(shù)據(jù).釋放幀
display_frame(filt_frame, buffersink_ctx->inputs[0]->time_base);
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);
}