FFmpeg中avfilter模块的介绍与使用

 更新时间:2023年08月28日 10:51:35   作者:fengbingchun  
FFmpeg中的libavfilter模块(或库)用于filter(过滤器), filter可以有多个输入和多个输出,下面就跟随小编一起简单学习一下它的巨日使用吧

FFmpeg中的libavfilter模块(或库)用于filter(过滤器), filter可以有多个输入和多个输出。为了说明可能发生的事情,考虑以下filtergraph(过滤器图):

该filtergraph将输入流(stream)分成两个流,然后通过crop过滤器和vflip过滤器发送一个流,然后将其与另一个流合并。      可以使用以下命令来实现: 

ffmpeg -i INPUT -vf "split [main][tmp]; [tmp] crop=iw:ih/2:0:0, vflip [flip]; [main][flip] overlay=0:H/2" OUTPUT

结果是将视频的上半部分镜像(mirrored)到输出视频的下半部分:

(1).同一线性链(same linear chain)中的过滤器用逗号分隔,不同线性链中的过滤器用分号分隔。此示例中,crop、vflip位于一个线性链中,split和overlay分别位于另一线性链中。

(2).线性链的连接点用方括号内的名称来标记,此示例中,split filter生成两个与标签[main]和[tmp]相关联的输出。

(3).发送到split的第二个输出(标记为[tmp])的流,通过crop过滤器进行处理,crop掉视频的下半部分,然后垂直翻转(vertically flipped)。

(4).overlay(覆盖或叠加)过滤器接收split过滤器的第一个未改变的输出(标记为[main]),并在其下半部分overlay由crop,vflip过滤器链生成的输出。

(5).某些过滤器接受输入参数列表:它们在过滤器名称和等号之后指定,并以冒号彼此分隔。

(6).存在没有音频/视频输入的所谓源过滤器(so-called source filters),以及没有音频/视频输出的接收器(sink)过滤器。

graph2dot:FFmpeg工具目录中包含的graph2dot程序可用于解析filtergraph描述,并用点语言(dot language)发出相应的文本表示。

filtergraph

(1).过滤器图是连接过滤器的有向图。它可以包含循环,并且一对过滤器之间可以有多个链接(multiple links)。每个链接的一侧都有一个输入板(input pad),将其连接到从中获取输入(input)的一个过滤器,另一侧有一个输出板(output pad),将其连接到接受其输出(output)的一个过滤器。

(2).过滤器图中的每个过滤器都是在应用程序中注册的过滤器类的一个实例(an instance of a filter),它定义了过滤器的功能(features)以及输入和输出板的数量。

(3).没有输入板的过滤器称为"source",没有输出板的过滤器称为"sink"。

注:以上内容主要来自于:http://ffmpeg.org/ffmpeg-filters.html

以下为测试代码:将一幅图像叠加在视频上,类似于为视频添加logo

1.函数open_input_file:

int open_input_file(const char* filename, AVFormatContext** fmt_ctx, AVCodecContext** dec_ctx, int& video_stream_index)
{
    auto ret = avformat_open_input(fmt_ctx, filename, nullptr, nullptr);
    if (ret < 0) {
        av_log(nullptr, AV_LOG_ERROR, "Cannot open input file\n");
        print_error_string(ret);
        return ret;
    }
    if ((ret = avformat_find_stream_info(*fmt_ctx, nullptr)) < 0) {
        av_log(nullptr, AV_LOG_ERROR, "Cannot find stream information\n");
        print_error_string(ret);
        return ret;
    }
    // select the video stream
    AVCodec* dec = nullptr;
    ret = av_find_best_stream(*fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
    if (ret < 0) {
        av_log(nullptr, AV_LOG_ERROR, "Cannot find a video stream in the input file\n");
        print_error_string(ret);
        return ret;
    }
    video_stream_index = ret;
    // create decoding context
    *dec_ctx = avcodec_alloc_context3(dec);
    if (!dec_ctx) {
        ret = AVERROR(ENOMEM);
        print_error_string(ret);
        return ret;
    }
    ret = avcodec_parameters_to_context(*dec_ctx, (*fmt_ctx)->streams[video_stream_index]->codecpar);
    if (ret < 0) {
        print_error_string(ret);
        return ret;
    }
    // init the video decoder
    if ((ret = avcodec_open2(*dec_ctx, dec, nullptr)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");
        return ret;
    }
    return 0;
}

2.函数init_filters:

int init_filters(const char* filters_descr, const AVCodecContext* dec_ctx, const AVRational& time_base, AVFilterGraph** filter_graph, AVFilterContext** buffersink_ctx, AVFilterContext** buffersrc_ctx)
{
    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();
    *filter_graph = avfilter_graph_alloc();
    if (!outputs || !inputs || !filter_graph || !buffersrc || !buffersink) {
        return AVERROR(ENOMEM);
    }
    // buffer video source: the decoded frames from the decoder will be inserted here.
    char args[512];
    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);
    auto ret = avfilter_graph_create_filter(buffersrc_ctx, buffersrc, "in",
        args, nullptr, *filter_graph);
    if (ret < 0) {
        av_log(nullptr, AV_LOG_ERROR, "Cannot create buffer source\n");
        print_error_string(ret);
        return ret;
    }
    // buffer video sink: to terminate the filter chain.
    ret = avfilter_graph_create_filter(buffersink_ctx, buffersink, "out",
        nullptr, nullptr, *filter_graph);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
        print_error_string(ret);
        return ret;
    }
    enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE };
    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");
        print_error_string(ret);
        return ret;
    }
    //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 = nullptr;
    // 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 = nullptr;
    if ((ret = avfilter_graph_parse_ptr(*filter_graph, filters_descr,
        &inputs, &outputs, nullptr)) < 0) {
        print_error_string(ret);
        return ret;
    }
    if ((ret = avfilter_graph_config(*filter_graph, nullptr)) < 0) {
        print_error_string(ret);
        return ret;
    }
    avfilter_inout_free(&inputs);
    avfilter_inout_free(&outputs);
    return ret;
}

3.入口函数test_ffmpeg_libavfilter_movie:接收一个参数,视频文件;为了便于显示,将图像宽、高各缩小一半

int test_ffmpeg_libavfilter_movie(const char* filename)
{
    AVFormatContext* fmt_ctx = nullptr;
    AVCodecContext* dec_ctx = nullptr;
    int video_stream_index = -1;
    auto ret = open_input_file(filename, &fmt_ctx, &dec_ctx, video_stream_index);
    if (ret < 0 || !fmt_ctx || !dec_ctx) {
        fprintf(stderr, "fail to open_input_file: %d\n", ret);
        return -1;
    }
    // ffmpeg.exe -i abc.mp4 -i 1.jpg -filter_complex "overlay=x=10:y=20" out.mp4
    const char* filter_descr = "movie=1.jpg[logo];[in][logo]overlay=10:20[out]";
    AVFilterGraph* filter_graph = nullptr;
    AVFilterContext* buffersink_ctx = nullptr;
    AVFilterContext* buffersrc_ctx = nullptr;
    AVRational time_base = fmt_ctx->streams[video_stream_index]->time_base;
    ret = init_filters(filter_descr, dec_ctx, time_base, &filter_graph, &buffersink_ctx, &buffersrc_ctx);
    if (ret < 0) {
        fprintf(stderr, "fail to init_filters: %d\n", ret);
        return -1;
    }
    AVFrame* frame = av_frame_alloc();
    AVFrame* filt_frame = av_frame_alloc();
    if (!frame || !filt_frame) {
        fprintf(stderr, "fail to av_frame_alloc\n");
        return -1;
    }
    const int width_src = dec_ctx->width, height_src = dec_ctx->height;
    const int width_dst = dec_ctx->width / 2, height_dst = dec_ctx->height / 2;
    SwsContext* sws_ctx = sws_getContext(width_src, height_src, AV_PIX_FMT_YUV420P,
        width_dst, height_dst, AV_PIX_FMT_BGR24, 0, nullptr, nullptr, nullptr);
    if (!sws_ctx) {
        fprintf(stderr, "fail to sws_getContext\n");
        return -1;
    }
    const int stride_src[4] = { width_src, width_src / 2, width_src / 2, 0 };
    const int stride_dst[4] = { width_dst * 3, 0, 0, 0 };
    AVPacket packet;
    bool exit = false;
    cv::Mat mat(height_dst, width_dst, CV_8UC3);
    const char* winname = "show video";
    cv::namedWindow(winname);
    // read all packets
    while (1) {
        if (exit) break;
        if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
            break;
        if (packet.stream_index == video_stream_index) {
            ret = avcodec_send_packet(dec_ctx, &packet);
            if (ret < 0) {
                av_log(nullptr, 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(nullptr, AV_LOG_ERROR, "Error while receiving a frame from the decoder\n");
                    print_error_string(ret);
                    return -1;
                }
                frame->pts = frame->best_effort_timestamp;
                // push the decoded frame into the filtergraph
                if ((ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF)) < 0) {
                    av_log(nullptr, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
                    print_error_string(ret);
                    break;
                }
                // pull filtered frames from the filtergraph
                while (1) {
                    ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
                    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                        break;
                    if (ret < 0) {
                        fprintf(stderr, "fail to av_buffersink_get_frame: %d\n", ret);
                        return -1;
                    }
                    sws_scale(sws_ctx, filt_frame->data, stride_src, 0, height_src, &mat.data, stride_dst);
                    cv::imshow(winname, mat);
                    av_frame_unref(filt_frame);
                    int key = cv::waitKey(30);
                    if (key == 27) {
                        exit = true;
                        break;
                    }
                    av_frame_unref(filt_frame);
                }
                av_frame_unref(frame);
            }
        }
        av_packet_unref(&packet);
    }
    avfilter_graph_free(&filter_graph);
    avcodec_free_context(&dec_ctx);
    avformat_close_input(&fmt_ctx);
    av_frame_free(&frame);
    av_frame_free(&filt_frame);
    sws_freeContext(sws_ctx);
    //if (ret < 0 && ret != AVERROR_EOF) {
    //    print_error_string(ret);
    //    return ret;
    //}
    return 0;
}

执行结果如下图所示:

GitHub:https://github.com/fengbingchun/OpenCV_Test

到此这篇关于FFmpeg中avfilter模块的介绍与使用的文章就介绍到这了,更多相关FFmpeg avfilter内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • C++11之后的decltype类型指示符详解

    C++11之后的decltype类型指示符详解

    为了满足这一要求,C++11 新标准引入了另一种类型说明符 decltype ,它的作用是选择并返回操作数的数据类型,这篇文章主要介绍了C++11之后的decltype类型指示符,需要的朋友可以参考下
    2023-01-01
  • Cocos2d-x人物动作类实例

    Cocos2d-x人物动作类实例

    这篇文章主要介绍了Cocos2d-x人物动作类实例,本文用大量代码和图片讲解Cocos2d-x中的动作,代码中同时包含大量注释说明,需要的朋友可以参考下
    2014-09-09
  • C语言三子棋的实现思路到过程详解

    C语言三子棋的实现思路到过程详解

    所谓三子棋,就是三行三列的棋盘,玩家可以和电脑下棋,率先连成三个的获胜。这篇文章主要为大家详细介绍了如何通过C语言实现三子棋小游戏,感兴趣的小伙伴可以尝试一下
    2023-02-02
  • C 语言条件运算符详细讲解

    C 语言条件运算符详细讲解

    本文主要介绍C语言中的条件运算符,并提供示例代码以便大家学习参考,希望能帮助学习 C语言的同学
    2016-07-07
  • C++中的friend友元函数详细解析

    C++中的friend友元函数详细解析

    友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类。友元函数的特点是能够访问类中的私有成员的非成员函数。友元函数从语法上看,它与普通函数一样,即在定义上和调用上与普通函数一样
    2013-09-09
  • 深入了解C++异常处理

    深入了解C++异常处理

    任何东西都可以认为是异常,错误只是异常的一种。本文将带大家了解C++中异常是什么,是如何捕获和处理的等相关知识。文中示例代码简洁易懂,感兴趣的小伙伴可以了解一下
    2021-12-12
  • C语言文件操作详解以及详细步骤

    C语言文件操作详解以及详细步骤

    文件(file)一般指存储在外部介质上数据的集合,比如我们经常使用的.txt, .bmp, jpg. .exe,.rmvb等等,下面这篇文章主要给大家介绍了关于C语言文件操作的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-06-06
  • C++ Boost MetaStateMachine定义状态机超详细讲解

    C++ Boost MetaStateMachine定义状态机超详细讲解

    Boost是为C++语言标准库提供扩展的一些C++程序库的总称。Boost库是一个可移植、提供源代码的C++库,作为标准库的后备,是C++标准化进程的开发引擎之一,是为C++语言标准库提供扩展的一些C++程序库的总称
    2022-12-12
  • C++设计模式之策略模式

    C++设计模式之策略模式

    这篇文章主要介绍了C++设计模式之策略模式,本文讲解了什么是策略模式、策略模式的使用场合、策略模式的代码实例等内容,需要的朋友可以参考下
    2014-10-10
  • C++布隆过滤器的使用示例

    C++布隆过滤器的使用示例

    宁可错杀一千,也不放过一个,这是布隆过滤器的特点,本文主要介绍了C++布隆过滤器的使用示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-09-09

最新评论