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

Rel*_*lla 61 c image h.264 x264

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

Kil*_*nDS 93

首先:检查x264.h文件,它包含或多或少的每个函数和结构的引用.您可以在下载中找到的x264.c文件包含一个示例实现.大多数人都说基于那个,但我觉得它对于初学者来说相当复杂,但是它可以作为一个例子来回归.

首先设置一些x264_param_t类型的参数,一个描述参数的好站点是http://mewiki.project357.com/wiki/X264_Settings.另外,请看一下这个x264_param_default_preset函数,它允许您定位某些功能,而无需了解所有(有时非常复杂的)参数.x264_param_apply_profile之后也可以使用(你可能想要"基线"配置文件)

这是我的代码中的一些示例设置:

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");
Run Code Online (Sandbox Code Playgroud)

在此之后,您可以按如下方式初始化编码器

x264_t* encoder = x264_encoder_open(&param);
x264_picture_t pic_in, pic_out;
x264_picture_alloc(&pic_in, X264_CSP_I420, w, h)
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

编码就像这样简单,对于每一帧做:

//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
}
Run Code Online (Sandbox Code Playgroud)

我希望这会让你前进;),我自己花了很长时间才开始.X264是一款非常强大但有时很复杂的软件.

编辑:使用其他参数时会出现延迟帧,但我的参数不是这种情况(主要是由于nolatency选项).如果是这种情况,frame_size有时会为零,x264_encoder_encode只要该函数x264_encoder_delayed_frames不返回0 ,您就必须调用.但是对于此功能,您应该更深入地了解x264.c和x264.h.

  • 这非常有帮助(+1).Python社区真的需要一个包装器来抽象出一些C风格的代码. (7认同)

小智 5

我上传了一个生成原始yuv帧的示例,然后使用x264对它们进行编码.完整代码可以在这里找到:https://gist.github.com/roxlu/6453908

  • 您可以在此处添加解决方案的摘要,以使其超过链接的生命周期 (4认同)

Cir*_*四事件 5

FFmpeg 2.8.6 C 可运行示例

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

该示例合成并编码了由 生成的一些彩色帧generate_rgb

这里讨论控制帧类型(I, P, B)以拥有尽可能少的关键帧(最好只是第一个): https: //stackoverflow.com/a/36412909/895245正如那里提到的,我不推荐它用于大多数应用程序。

这里进行帧类型控制的关键行是:

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

和:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后我们可以通过以下方式验证帧类型:

ffprobe -select_streams v \
    -show_frames \
    -show_entries frame=pict_type \
    -of csv \
    tmp.h264
Run Code Online (Sandbox Code Playgroud)

如所述: https: //superuser.com/questions/885452/extracting-the-index-of-key-frames-from-a-video-using-ffmpeg

生成输出的预览

主程序

#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;
}
Run Code Online (Sandbox Code Playgroud)

编译并运行:

gcc -o main.out -std=c99 -Wextra main.c -lavcodec -lswscale -lavutil
./main.out
ffplay tmp.mpg
ffplay tmp.h264
Run Code Online (Sandbox Code Playgroud)

在 Ubuntu 16.04 上测试。GitHub 上游.

  • @CiroSantilli新疆再教育营六四事件法轮功郝海东这个例子是正确的。正在编码 x264 格式的一系列帧。但是,如果我们想将其转换为可供电影播放器​​读取的 mp4 文件,我们需要执行一个额外的步骤,即混合。它有点复杂,因为它涉及使用更多的库。参考文献绝对在这里 - &gt; https://github.com/FFmpeg/FFmpeg/blob/master/doc/examples/muxing.c (2认同)