使用GTK显示已过滤的ffmpeg帧

时间:2015-01-07 01:39:03

标签: c video ffmpeg gtk libav

我想使用ffmpeg api显示裁剪和缩放的帧,我使用GTK + 3作为GUI组件。从this tutorialffmpeg examples开始,我可以显示未过滤的帧,但有些不稳定。过滤后的帧根本无法正确显示。它主要产生完全黑色的输出。我怀疑这是由于sws_scale(),但我还没有发现为什么会发生这种情况。

使用"琐事"从ffmpeg示例中显示我可以确认正在裁剪和缩放帧。

运行下面的代码我得到了一堆错误:

[swscaler @ 0x7fb58b025400] bad src image pointers
[swscaler @ 0x7fb58b025400] bad dst image pointers

我也遇到了这个错误:

[swscaler @ 0x7fd05c025600] Warning: data is not aligned! This can lead to a speedloss

我尝试制作一个16位对齐的缓冲区,但它似乎没有对结果产生任何影响。

这就是我解码帧并应用滤镜的方法:

void decode(gpointer args) {
    int ret;
    AVPacket packet;
    AVFrame *frame = av_frame_alloc();
    AVFrame *filt_frame = av_frame_alloc();
    int got_frame;

    if(!frame || !filt_frame) {
        perror("Could not allocate frame");
        exit(1);
    }

    /* read all packets */
    while (1) {
        if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
            break;
        if (packet.stream_index == video_stream_index) {
            got_frame = 0;
            ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, &packet);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error decoding video\n");
                break;
            }
            if (got_frame) {
                frame->pts = av_frame_get_best_effort_timestamp(frame);
                /* 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_frame2(filt_frame, buffersink_ctx->inputs[0]->time_base);
                    av_frame_unref(filt_frame);
                }
                av_frame_unref(frame);
            }
        }
        av_free_packet(&packet);
    }
end:
    avfilter_graph_free(&filter_graph);
    avcodec_close(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);
    }

}

这就是我显示帧的方式。

void display_frame2(const AVFrame *frame, AVRational time_base) {
    GdkPixbuf *pixbuf;
    int64_t delay;
    AVFrame *filt;
    uint8_t *buffer;
    int num_bytes, i;
    buffer = NULL;


    filt = av_frame_alloc();
    num_bytes = avpicture_get_size(PIX_FMT_RGB24, dec_ctx->width, dec_ctx->height);
    buffer = (uint8_t *)av_malloc(num_bytes * sizeof(uint8_t));
    avpicture_fill((AVPicture *)filt, buffer, PIX_FMT_RGB24, dec_ctx->width, dec_ctx->height);

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

    sws_scale(  sws_ctx,
                (uint8_t const * const *)frame->data,
                frame->linesize,
                0,
                frame->height,
                filt->data,
                filt->linesize);
    pixbuf = gdk_pixbuf_new_from_data(  filt->data[0], GDK_COLORSPACE_RGB,
                                        0, 8, dec_ctx->width, dec_ctx->height,
                                        filt->linesize[0], NULL, NULL);
    gtk_image_set_from_pixbuf((GtkImage *)image, pixbuf);
    free( filt );
    free( buffer );

}

编辑: 经过一些思考和实验后,我得到了过滤后的帧,尽管是SDL,而不是GTK +。我使用ffmpeg中的转码示例来查看是否可以使用过滤器重新编码视频,这确实有效。在这个例子中,我基本上改变了过滤器的过滤器,大部分工作已经完成。此时我所做的就是使用SDL显示视频,如危险教程中所示。裁剪过滤器会产生很多伪影,但它至少会显示一些东西。

我还需要做更多的工作,看看它是否适用于GTK +。我没有详细研究上面的程序和转码示例中的程序之间的差异,所以我还没弄清楚为什么我的旧代码不显示过滤帧。这两组代码都使用sws_scale(),但是新代码没有错误,所以这必然意味着某些东西是不同的。一旦我取得更多进展,我会更新这篇文章。

编辑2: 根据@ drahnr的要求,添加了一个应该可用的小型可编辑示例。我没有机会尝试更换GtkPixbuf。

#define _XOPEN_SOURCE 600 
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <libavfilter/avfiltergraph.h>
#include <libavfilter/avcodec.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
#include <libavutil/avstring.h>
#include <libavutil/time.h>
#include <libavutil/opt.h>
#include <unistd.h>

#include <gtk/gtk.h>
#include <gdk/gdkx.h>


GtkWidget *image;
GtkWidget *window;

struct SwsContext *sws_ctx;
char *filter_descr = "crop=100:100,scale=640:360";
static AVFormatContext *fmt_ctx;
static AVCodecContext *dec_ctx;
AVFilterContext *buffersink_ctx;
AVFilterContext *buffersrc_ctx;
AVFilterGraph *filter_graph;
static int video_stream_index = -1;

static void open_input_file(const char *filename)
{
    AVCodec *dec;
    avformat_open_input(&fmt_ctx, filename, NULL, NULL);
    avformat_find_stream_info(fmt_ctx, NULL);
    video_stream_index = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
    dec_ctx = fmt_ctx->streams[video_stream_index]->codec;
    av_opt_set_int(dec_ctx, "refcounted_frames", 1, 0);
    avcodec_open2(dec_ctx, dec, NULL);
}


static void init_filters(const char *filters_descr)
{
    char args[512];
    AVFilter *buffersrc  = avfilter_get_by_name("buffer");
    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[] = { PIX_FMT_RGB24, AV_PIX_FMT_NONE };
    filter_graph = avfilter_graph_alloc();
    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);
    avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in", args, NULL, filter_graph);
    avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out", NULL, NULL, filter_graph);
    av_opt_set_int_list(buffersink_ctx, "pix_fmts", pix_fmts, AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);
    outputs->name       = av_strdup("in");
    outputs->filter_ctx = buffersrc_ctx;
    outputs->pad_idx    = 0;
    outputs->next       = NULL;
    inputs->name       = av_strdup("out");
    inputs->filter_ctx = buffersink_ctx;
    inputs->pad_idx    = 0;
    inputs->next       = NULL;
    avfilter_graph_parse_ptr(filter_graph, filters_descr, &inputs, &outputs, NULL);
    avfilter_graph_config(filter_graph, NULL);
}

static void display_frame2(const AVFrame *frame, AVRational time_base) {
    GdkPixbuf *pixbuf;

    AVFrame *filt;
    uint8_t *buffer;
    int num_bytes;
    buffer = NULL;

    filt = av_frame_alloc();
    num_bytes = avpicture_get_size(PIX_FMT_RGB24, dec_ctx->width, dec_ctx->height);
    buffer = (uint8_t *)av_malloc(num_bytes * sizeof(uint8_t));
    avpicture_fill((AVPicture *)filt, buffer, PIX_FMT_RGB24, dec_ctx->width, dec_ctx->height);
    usleep(33670 / 4);
    sws_scale(  sws_ctx,
                (uint8_t const * const *)frame->data,
                frame->linesize,
                0,
                frame->height,
                filt->data,
                filt->linesize);
    pixbuf = gdk_pixbuf_new_from_data(  filt->data[0], GDK_COLORSPACE_RGB,
                                        0, 8, dec_ctx->width, dec_ctx->height,
                                        filt->linesize[0], NULL, NULL);
    gtk_image_set_from_pixbuf((GtkImage *)image, pixbuf);
    free( filt );
    free( buffer );

}


void decode(gpointer args) {
    int ret;
    AVPacket packet;
    AVFrame *frame      = av_frame_alloc();
    AVFrame *filt_frame = av_frame_alloc();
    int got_frame;

    while (1) {
        av_read_frame(fmt_ctx, &packet);
        if (packet.stream_index == video_stream_index) {
            got_frame = 0;
            avcodec_decode_video2(dec_ctx, frame, &got_frame, &packet);
            if (got_frame) {
                frame->pts = av_frame_get_best_effort_timestamp(frame);
                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;
                }
                while (1) {
                    ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
                    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                        break;
                    // Display original frame
                    display_frame2(frame, buffersink_ctx->inputs[0]->time_base);
                    // Display filtered frame
                    // display_frame2(filt_frame, buffersink_ctx->inputs[0]->time_base);
                    av_frame_unref(filt_frame);
                }
                av_frame_unref(frame);
            }
        }
        av_free_packet(&packet);
    }

}

static void realize_cb(GtkWidget *widget, gpointer data) {
    GThread *tid;
    tid = g_thread_new("video", decode, NULL);
}

static void destroy(GtkWidget *widget, gpointer data) {
        gtk_main_quit();
}

int main(int argc, char **argv)
{
    av_register_all();
    avfilter_register_all();
    open_input_file(argv[1]);
    init_filters(filter_descr);
    sws_ctx = NULL;
    sws_ctx = sws_getContext(   dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt, dec_ctx->width, dec_ctx->height,
                                    PIX_FMT_RGB24, SWS_BILINEAR, NULL, NULL, NULL );
    av_dump_format( fmt_ctx, 0, argv[1], 0);

    gtk_init(&argc, &argv);
    window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
    g_signal_connect(window, "realize", G_CALLBACK(realize_cb), NULL);
    g_signal_connect(window, "destroy", G_CALLBACK(destroy), NULL);
    gtk_container_set_border_width(GTK_CONTAINER(window), 10);
    image = gtk_image_new();
    gtk_widget_show(image);
    gtk_container_add(GTK_CONTAINER(window), image);
    gtk_widget_show(window);
    gtk_main();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

执行此操作的正确方法是使用cairo_surface_t和裸机GtkDrawingArea。获取其大小分配,相应地缩放内容(此处:您的视频帧)。

那你什么时候想画画?当然不像你现在那样。

将它同步到帧时钟,并阅读相应的文档页面(是的,这是有效的,但它会对你有所帮助)https://developer.gnome.org/gdk3/stable/GdkFrameClock.html#gdk-frame-clock-begin-updating

并在准备好显示新帧时安排重绘。


我在上面的程序中看到的主要错误是你从一个不是运行GtkImage *image的线程的线程访问一个UI元素gtk_main/g_event_loop,这是不允许的,因为只有一个非常小的子集g/gtk_调用是线程安全的。其中一个要绕过的是g_idle_add,它将数据回调到主循环中(在gtk文档中搜索GSource)。


对于对齐方式,我不知道这里的问题是什么,即使将其与posix_memalign对齐512 字节 <,我也会收到警告/ p>

编辑:看起来,步幅也必须是16字节的倍数,这是所需的对齐方式。


开始clean draft widget implementation at github,虽然这还没有编译 - 但它仍然非常清楚地概述了这个方法。