如何使用x264 C API将一系列图像编码为H264格式?

68

如何使用x264 C API将RGB图像编码为H264帧?我已经创建了一系列RGB图像,现在该如何将其转换成一系列H264帧呢?特别是,我如何将这个RGB图像序列编码成由单个初始H264关键帧后跟依赖H264帧组成的H264帧序列?

3个回答

96
首先要检查x264.h文件,里面基本包含了每个函数和结构的参考。你可以在下载中找到x264.c文件,它包含了一个示例实现。大多数人建议初学者以此为基础,但我认为对于初学者而言相对复杂,不过它仍然是一个良好的备用示例。
首先设置一些参数,类型为x264_param_t,有一个很好的描述参数的网站:http://mewiki.project357.com/wiki/X264_Settings。同时看一下x264_param_default_preset函数,它可以让你在不需要理解所有(有时相当复杂)参数的情况下定位某些功能。之后使用x264_param_apply_profile(你可能想要“baseline”配置文件)。
以下是我的代码示例设置:
x264_param_t param;
x264_param_default_preset(&param, "veryfast", "zerolatency");
param.i_threads = 1;
param.i_width = width;
param.i_height = height;
param.i_fps_num = fps;
param.i_fps_den = 1;
// Intra refres:
param.i_keyint_max = fps;
param.b_intra_refresh = 1;
//Rate control:
param.rc.i_rc_method = X264_RC_CRF;
param.rc.f_rf_constant = 25;
param.rc.f_rf_constant_max = 35;
//For streaming:
param.b_repeat_headers = 1;
param.b_annexb = 1;
x264_param_apply_profile(&param, "baseline");

接下来,您可以按以下方式初始化编码器:

x264_t* encoder = x264_encoder_open(&param);
x264_picture_t pic_in, pic_out;
x264_picture_alloc(&pic_in, X264_CSP_I420, w, h)

X264希望得到YUV420P数据(我猜其他一些格式也可以,但这是最常见的)。您可以使用libswscale(来自ffmpeg)将图像转换为正确的格式。初始化步骤如下(我假设RGB数据每像素24bpp)。

struct SwsContext* convertCtx = sws_getContext(in_w, in_h, PIX_FMT_RGB24, out_w, out_h, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL);

编码很简单,只需对每个帧执行以下操作:

//data is a pointer to you RGB structure
int srcstride = w*3; //RGB stride is just 3*width
sws_scale(convertCtx, &data, &srcstride, 0, h, pic_in.img.plane, pic_in.img.stride);
x264_nal_t* nals;
int i_nals;
int frame_size = x264_encoder_encode(encoder, &nals, &i_nals, &pic_in, &pic_out);
if (frame_size >= 0)
{
    // OK
}

我希望这能帮助到你,我自己花了很长时间才开始入门。X264是一个非常强大但有时也很复杂的软件。

编辑:当你使用其他参数时,会出现延迟帧的情况,但我使用的参数并不会(主要是由于nolatency选项)。如果出现延迟帧的情况,帧大小有时会为零,你需要不断调用x264_encoder_encode函数,直到x264_encoder_delayed_frames函数返回0。但要了解这个功能,你需要深入研究x264.c和x264.h文件。


7
非常有帮助 (+1)。Python社区确实需要一个能够抽象掉一些C风格代码的封装。 - Carl F.
1
有没有一种简单的方法将其流式传输到常规媒体客户端,比如XBMC,或将其包装为AVI流? - dascandy
你可以编写一个 DirectShow 源过滤器。AVI 不是 H.264 的最佳容器选择,请参见 http://en.wikipedia.org/wiki/Comparison_of_container_formats。 - fishfood
x264_encoder_encodedata,也就是 RGB 结构体并没有做任何处理,它实际上要编码的是什么? - user4016367
pic_in.img.stride seems to be renamed to pic_in.img.i_stride. In addition, the resulting frame-data can be found in nals->p_payload - Morris Franken
所以,假设我们不需要执行 sws_getContextsws_scale,因为我们的输入像素/字节/数据已经处于示例颜色格式中,那么我们应该怎样将 data 转换到 pic_in 中呢? - Meme Machine

5

FFmpeg 2.8.6 C可运行示例

使用FFmpeg作为x264的封装器是一个好主意,因为它为多个编码器公开了统一的API。因此,如果您需要更改格式,您只需更改一个参数而不是学习新的API。

该示例通过generate_rgb生成一些彩色帧并对其进行编码。

控制帧类型(I、P、B)以尽可能少地使用关键帧(理想情况下仅第一个关键帧)在这里讨论: https://dev59.com/EHE95IYBdhLWcg3wf98F#36412909 如上所述,我不建议大多数应用程序使用此方法。

控制帧类型的关键代码如下:

/* Minimal distance of I-frames. This is the maximum value allowed,
or else we get a warning at runtime. */
c->keyint_min = 600;

并且:

if (frame->pts == 1) {
    frame->key_frame = 1;
    frame->pict_type = AV_PICTURE_TYPE_I;
} else {
    frame->key_frame = 0;
    frame->pict_type = AV_PICTURE_TYPE_P;
}

我们可以通过以下方式验证帧类型:
ffprobe -select_streams v \
    -show_frames \
    -show_entries frame=pict_type \
    -of csv \
    tmp.h264

作为提到的内容:https://superuser.com/questions/885452/extracting-the-index-of-key-frames-from-a-video-using-ffmpeg 生成输出预览
主要.c文件。
#include <libavcodec/avcodec.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libswscale/swscale.h>

static AVCodecContext *c = NULL;
static AVFrame *frame;
static AVPacket pkt;
static FILE *file;
struct SwsContext *sws_context = NULL;

static void ffmpeg_encoder_set_frame_yuv_from_rgb(uint8_t *rgb) {
    const int in_linesize[1] = { 3 * c->width };
    sws_context = sws_getCachedContext(sws_context,
            c->width, c->height, AV_PIX_FMT_RGB24,
            c->width, c->height, AV_PIX_FMT_YUV420P,
            0, 0, 0, 0);
    sws_scale(sws_context, (const uint8_t * const *)&rgb, in_linesize, 0,
            c->height, frame->data, frame->linesize);
}

uint8_t* generate_rgb(int width, int height, int pts, uint8_t *rgb) {
    int x, y, cur;
    rgb = realloc(rgb, 3 * sizeof(uint8_t) * height * width);
    for (y = 0; y < height; y++) {
        for (x = 0; x < width; x++) {
            cur = 3 * (y * width + x);
            rgb[cur + 0] = 0;
            rgb[cur + 1] = 0;
            rgb[cur + 2] = 0;
            if ((frame->pts / 25) % 2 == 0) {
                if (y < height / 2) {
                    if (x < width / 2) {
                        /* Black. */
                    } else {
                        rgb[cur + 0] = 255;
                    }
                } else {
                    if (x < width / 2) {
                        rgb[cur + 1] = 255;
                    } else {
                        rgb[cur + 2] = 255;
                    }
                }
            } else {
                if (y < height / 2) {
                    rgb[cur + 0] = 255;
                    if (x < width / 2) {
                        rgb[cur + 1] = 255;
                    } else {
                        rgb[cur + 2] = 255;
                    }
                } else {
                    if (x < width / 2) {
                        rgb[cur + 1] = 255;
                        rgb[cur + 2] = 255;
                    } else {
                        rgb[cur + 0] = 255;
                        rgb[cur + 1] = 255;
                        rgb[cur + 2] = 255;
                    }
                }
            }
        }
    }
    return rgb;
}

/* Allocate resources and write header data to the output file. */
void ffmpeg_encoder_start(const char *filename, int codec_id, int fps, int width, int height) {
    AVCodec *codec;
    int ret;

    codec = avcodec_find_encoder(codec_id);
    if (!codec) {
        fprintf(stderr, "Codec not found\n");
        exit(1);
    }
    c = avcodec_alloc_context3(codec);
    if (!c) {
        fprintf(stderr, "Could not allocate video codec context\n");
        exit(1);
    }
    c->bit_rate = 400000;
    c->width = width;
    c->height = height;
    c->time_base.num = 1;
    c->time_base.den = fps;
    c->keyint_min = 600;
    c->pix_fmt = AV_PIX_FMT_YUV420P;
    if (codec_id == AV_CODEC_ID_H264)
        av_opt_set(c->priv_data, "preset", "slow", 0);
    if (avcodec_open2(c, codec, NULL) < 0) {
        fprintf(stderr, "Could not open codec\n");
        exit(1);
    }
    file = fopen(filename, "wb");
    if (!file) {
        fprintf(stderr, "Could not open %s\n", filename);
        exit(1);
    }
    frame = av_frame_alloc();
    if (!frame) {
        fprintf(stderr, "Could not allocate video frame\n");
        exit(1);
    }
    frame->format = c->pix_fmt;
    frame->width  = c->width;
    frame->height = c->height;
    ret = av_image_alloc(frame->data, frame->linesize, c->width, c->height, c->pix_fmt, 32);
    if (ret < 0) {
        fprintf(stderr, "Could not allocate raw picture buffer\n");
        exit(1);
    }
}

/*
Write trailing data to the output file
and free resources allocated by ffmpeg_encoder_start.
*/
void ffmpeg_encoder_finish(void) {
    uint8_t endcode[] = { 0, 0, 1, 0xb7 };
    int got_output, ret;
    do {
        fflush(stdout);
        ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);
        if (ret < 0) {
            fprintf(stderr, "Error encoding frame\n");
            exit(1);
        }
        if (got_output) {
            fwrite(pkt.data, 1, pkt.size, file);
            av_packet_unref(&pkt);
        }
    } while (got_output);
    fwrite(endcode, 1, sizeof(endcode), file);
    fclose(file);
    avcodec_close(c);
    av_free(c);
    av_freep(&frame->data[0]);
    av_frame_free(&frame);
}

/*
Encode one frame from an RGB24 input and save it to the output file.
Must be called after ffmpeg_encoder_start, and ffmpeg_encoder_finish
must be called after the last call to this function.
*/
void ffmpeg_encoder_encode_frame(uint8_t *rgb) {
    int ret, got_output;
    ffmpeg_encoder_set_frame_yuv_from_rgb(rgb);
    av_init_packet(&pkt);
    pkt.data = NULL;
    pkt.size = 0;
    if (frame->pts == 1) {
        frame->key_frame = 1;
        frame->pict_type = AV_PICTURE_TYPE_I;
    } else {
        frame->key_frame = 0;
        frame->pict_type = AV_PICTURE_TYPE_P;
    }
    ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
    if (ret < 0) {
        fprintf(stderr, "Error encoding frame\n");
        exit(1);
    }
    if (got_output) {
        fwrite(pkt.data, 1, pkt.size, file);
        av_packet_unref(&pkt);
    }
}

/* Represents the main loop of an application which generates one frame per loop. */
static void encode_example(const char *filename, int codec_id) {
    int pts;
    int width = 320;
    int height = 240;
    uint8_t *rgb = NULL;
    ffmpeg_encoder_start(filename, codec_id, 25, width, height);
    for (pts = 0; pts < 100; pts++) {
        frame->pts = pts;
        rgb = generate_rgb(width, height, pts, rgb);
        ffmpeg_encoder_encode_frame(rgb);
    }
    ffmpeg_encoder_finish();
}

int main(void) {
    avcodec_register_all();
    encode_example("tmp.h264", AV_CODEC_ID_H264);
    encode_example("tmp.mpg", AV_CODEC_ID_MPEG1VIDEO);
    return 0;
}

使用以下步骤编译和运行:

gcc -o main.out -std=c99 -Wextra main.c -lavcodec -lswscale -lavutil
./main.out
ffplay tmp.mpg
ffplay tmp.h264

在Ubuntu 16.04上进行测试。 GitHub源代码.


这需要nvcuda.dll及其依赖项。无法使其运行。 - rosewater
@rosewater 感谢您的报告。如果您找到安装方法,请告诉我。我只能在Ubuntu上测试。 - Ciro Santilli OurBigBook.com
1
@CiroSantilli,输出文件无法被 Quick Time 识别。你知道可能出了什么问题吗? - Nuno Santos
我正在使用通过brew安装的最新版本ffmpeg。你的代码已经过时了,因为我不得不使用avcodec_send_frame / avcodec_receive_packet代替avcodec_encode_video2。也许这有一些我不知道的影响。这是我现在拥有的-> https://pastebin.com/BbVJpPcS - Nuno Santos
@NunoSantos 感谢您的跟进。如果您成功修复我的示例,请告诉我,我们可以更新此答案,或者如果您愿意,您也可以添加一个新的答案。 - Ciro Santilli OurBigBook.com
显示剩余3条评论

5

5
你可以在这里添加你的解决方案摘要,以便它能够超越链接的生命周期。 - krsteeve

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