如何在C / C ++中使用FFmpeg API叠加滤镜

4

我有一个C++项目,可以创建类似于WebTV的RTMP流,并允许在运行时进行操作,例如更改当前内容、搜索内容、通过由json数组构建的播放列表循环播放,还支持在运行时更改整个播放列表。

目前,我正在从mp4文件中读取H264和AAC编码的数据包,然后在不进行任何编码或解码的情况下调整它们的PTS和DTS值,然后将它们发送到目标RTMP服务器。

但是我想在解码H264数据包后使用FFmpeg的“overlay”滤镜向原始帧应用叠加图像。我查看了随FFmpeg示例附带的示例;

#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;
AVFilterGraph *filter_graph;
static int video_stream_index = -1;
static int64_t last_pts = AV_NOPTS_VALUE;

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;
    }

    /* 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;

    /* 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);

    /* init the video decoder */
    if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");
        return ret;
    }

    return 0;
}

static int init_filters(const char *filters_descr)
{
    char args[512];
    int ret = 0;
    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 };

    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);

    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;
    }

    /* 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;
    }

    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;
}

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 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) {
        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(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 */
                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) {
                    ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
                    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                        break;
                    if (ret < 0)
                        goto end;
                    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);
}

这个示例使用以下过滤器:

"scale = 78:24,transpose = cclock"

我使用一个样本视频文件编译并运行它,但它只会输出花哨的字符到控制台,下面给出的代码块就是造成这种情况的原因:

   /* 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);

我对编码和解码没有问题,只是不知道如何应用“叠加”滤镜。是否有任何教程演示如何使用“叠加”滤镜?


这个教程似乎很好地演示了过滤器的使用。 - user7860670
我应该如何将我的叠加图像添加到过滤器链中? - yildizmehmet
@VTT 我可以通过将videoFrame和overlayFrame发送到缓冲源上下文来实现我的目的吗,如下所示:av_buffersrc_add_frame_flags(buffersrc_ctx,videoFrame,AV_BUFFERSRC_FLAG_KEEP_REF); av_buffersrc_add_frame_flags(buffersrc_ctx,overlayFrame,AV_BUFFERSRC_FLAG_KEEP_REF);在使用以下代码从filtergraph中提取过滤帧之后;av_buffersink_get_frame(buffersink_ctx,filt_frame);filt_frame是否包含我的覆盖帧? - yildizmehmet
2个回答

4
就像示例中一样,只是您使用了“overlay”。
 snprintf(args, sizeof(args), args here...);
 avfilter_graph_create_filter(sink, avfilter_get_by_name("overlay"), nullptr, nullptr, arg, graph);

那么您需要创建两个源垫片。即:
avfilter_graph_create_filter(sourceX, avfilter_get_by_name("buffer"), nullptr, args, nullptr, m_graph);

有一个下沉垫和一个源。然后将一个源与视频帧连接,另一个源与图像连接以进行叠加。


感谢您的指导。我创建了两个缓冲区源并用AVFrame进行了填充,同时使用了char *filter_descr = "[in]scale=300:100[scl];[in1][scl]overlay=25:25"来利用我的过滤器链。 - yildizmehmet

2

以下代码片段将非常有用...

    char args[512];
    int ret = 0;
    const AVFilter *bufferSrc  = avfilter_get_by_name("buffer");
    const AVFilter *bufferOvr  = avfilter_get_by_name("buffer");
    const AVFilter *bufferSink = avfilter_get_by_name("buffersink");
    const AVFilter *ovrFilter  = avfilter_get_by_name("overlay");
    const AVFilter *colorFilter  = avfilter_get_by_name("colorchannelmixer");
    enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE };

    fFilterGraph = avfilter_graph_alloc();
    if (!fFilterGraph) {
        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",
         decCtx->width, decCtx->height, decCtx->pix_fmt,
         fTimeBase.num, fTimeBase.den,
         decCtx->sample_aspect_ratio.num, decCtx->sample_aspect_ratio.den);
    ret = avfilter_graph_create_filter(&fBufSrc0Ctx, bufferSrc, "in0",
                       args, NULL, fFilterGraph);
    if (ret < 0)
        goto end;

    /* buffer video overlay source: the overlayed frame from the file will be inserted here. */
    snprintf(args, sizeof(args),
         "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
         ovrCtx->width, ovrCtx->height, ovrCtx->pix_fmt,
         fTimeBase.num, fTimeBase.den,
         ovrCtx->sample_aspect_ratio.num, ovrCtx->sample_aspect_ratio.den);
    ret = avfilter_graph_create_filter(&fBufSrc1Ctx, bufferOvr, "in1",
                       args, NULL, fFilterGraph);
    if (ret < 0)
        goto end;

    /* color filter */
    snprintf(args, sizeof(args), "aa=%f", (float)fWatermarkOpacity / 10.0);
    ret = avfilter_graph_create_filter(&fColorFilterCtx, colorFilter, "colorFilter",
                       args, NULL, fFilterGraph);
    if (ret < 0)
        goto end;

    /* overlay filter */
    switch (fWatermarkPos) {
    case 0:
        /* Top left */
        snprintf(args, sizeof(args), "x=%d:y=%d:repeatlast=1",
             fWatermarkOffset, fWatermarkOffset);
        break;
    case 1:
        /* Top right */
        snprintf(args, sizeof(args), "x=W-w-%d:y=%d:repeatlast=1",
             fWatermarkOffset, fWatermarkOffset);
        break;
    case 3:
        /* Bottom left */
        snprintf(args, sizeof(args), "x=%d:y=H-h-%d:repeatlast=1",
             fWatermarkOffset, fWatermarkOffset);
        break;
    case 4:
        /* Bottom right */
        snprintf(args, sizeof(args), "x=W-w-%d:y=H-h-%d:repeatlast=1",
             fWatermarkOffset, fWatermarkOffset);
        break;

    case 2:
    default:
        /* Center */
        snprintf(args, sizeof(args), "x=(W-w)/2:y=(H-h)/2:repeatlast=1");
        break;
    }
    ret = avfilter_graph_create_filter(&fOvrFilterCtx, ovrFilter, "overlay",
                       args, NULL, fFilterGraph);
    if (ret < 0)
        goto end;

    /* buffer sink - destination of the final video */
    ret = avfilter_graph_create_filter(&fBufSinkCtx, bufferSink, "out",
                       NULL, NULL, fFilterGraph);
    if (ret < 0)
        goto end;

    ret = av_opt_set_int_list(fBufSinkCtx, "pix_fmts", pix_fmts,
                  AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);
    if (ret < 0)
        goto end;

    /*
     * Link all filters..
     */
    avfilter_link(fBufSrc0Ctx, 0, fOvrFilterCtx, 0);
    avfilter_link(fBufSrc1Ctx, 0, fColorFilterCtx, 0);
    avfilter_link(fColorFilterCtx, 0, fOvrFilterCtx, 1);
    avfilter_link(fOvrFilterCtx, 0, fBufSinkCtx, 0);
    if ((ret = avfilter_graph_config(fFilterGraph, NULL)) < 0)
        goto end;

end:

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接