FFmpeg 学习系列之官方 Demo encode video

1,527 阅读4分钟

FFmpeg 官方 Demo encode_video.c 学习,是一个用 libavcodec API 编码视频的例子。其中涉及了 AVCodecContext、AVFrame、AVPacket、AVCodec 和 AVRational 结构体,以及 avcodec_send_frame(...)、avcodec_receive_packet(...)、av_packet_unref(...)、avcodec_find_encoder_by_name(...)、avcodec_alloc_context3(...)、av_packet_alloc()、avcodec_open2(...)、av_frame_alloc()、av_frame_get_buffer(...)、av_frame_make_writable(...)、avcodec_free_context(...)、av_frame_free(...) 和 av_packet_free(...) 这些函数。

学习这些 FFmpeg 常用的结构体以及常用的 API 函数,莫过于直接阅读官网英文 API 描述,再去结合使用加深理解。先来过一遍 Demo 源码熟悉整个流程,并运行以后观察它的效果。

一、encode_video.c 源码

下面是整个 encode_video.c 的源码,原先对应的英文注释,我都加了自己理解的翻译。

首先这个程序运行后需要输入 ,分别对应输出的文件路径和编码器名称。接着会调用 avcodec_find_encoder_by_name(...) 根据名称查找相应的编码器,如果不存在这个编码器名称就会打印错误消息 Codec 'xxx' not found。找到了编码器(AVCodec)之后,就会调用 avcodec_alloc_context3(...) 分配编码器上下文(AVCodecContext)。接下来调用 av_packet_alloc() 分配 AVPacket,编码器编码时会将每一帧 AVFrame 编码为 AVPacket。现在开始给编码器上下文配置一些参数(码率、视频宽、视频高、时间基、帧率、GOP(图像组,指两个I帧之间的距离)、最大B帧数、帧格式),可以打开编码器了,通过调用 avcodec_open2(...) 实现的。调用 av_frame_alloc() 分配 AVFrame 内存,指定一下帧的格式和宽高,接着调用 av_frame_get_buffer(...) 分配帧数据使用的空间。接下来是个 for 循环,内部首先调用 av_frame_make_writable(...) 确保帧(AVFrame)数据可写,然后准备一帧假数据(一帧YUV420P),最后给每帧的 pts(显示时间戳,用来告诉播放器该在什么时候显示这一帧的数据) 赋值,现在可以把帧(AVFrame)发送给编码器,这是通过调用 avcodec_send_frame(...) 实现的。现在可以把编码后的帧(AVPacket)从编码器取出,这是通过调用 avcodec_receive_packet(...) 实现的。把编码后的每帧写入文件,调用 av_packet_unref(...) 解除对 AVPacket 的引用。如果编码器 ID 是 AV_CODEC_ID_MPEG1VIDEO 或者 AV_CODEC_ID_MPEG2VIDEO,需要在结尾添加序列从而得到一个 MPEG 文件。最后关闭文件,并释放 AVCodecContext 占用的内存(调用 avcodec_free_context(...) 实现), 最后释放 AVFrame 和 AVPacket 占用的内存,调用 av_frame_free(...) 和 av_packet_free(...) 实现。

/**
 * @file
 * video encoding with libavcodec API example
 * 用 libavcodec API 编码视频的例子
 * @example encode_video.c
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libavcodec/avcodec.h>
#include <libavutil/opt.h>
#include <libavutil/imgutils.h>
static void encode(AVCodecContext *enc_ctx, AVFrame *frame, AVPacket *pkt,
                   FILE *outfile)
{
    int ret;
    /* send the frame to the encoder 发送帧到编码器 */
    if (frame)
        printf("Send frame %3"PRId64"\n", frame->pts);// PRId64 跨平台的书写方式,主要是为了同时支持32位和64位操作系统
    ret = avcodec_send_frame(enc_ctx, frame);
    if (ret < 0) {
        fprintf(stderr, "Error sending a frame for encoding\n");
        exit(1);
    }
    while (ret >= 0) {
        ret = avcodec_receive_packet(enc_ctx, pkt);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return;
        else if (ret < 0) {
            fprintf(stderr, "Error during encoding\n");
            exit(1);
        }
        printf("Write packet %3"PRId64" (size=%5d)\n", pkt->pts, pkt->size);
        fwrite(pkt->data, 1, pkt->size, outfile);
        av_packet_unref(pkt);
    }
}
int main(int argc, char **argv)
{
    const char *filename, *codec_name;
    const AVCodec *codec;
    AVCodecContext *c= NULL;
    int i, ret, x, y;
    FILE *f;
    AVFrame *frame;
    AVPacket *pkt;
    uint8_t endcode[] = { 0, 0, 1, 0xb7 };
    if (argc <= 2) {
        fprintf(stderr, "Usage: %s <output file> <codec name>\n", argv[0]);
        exit(0);
    }
    filename = argv[1];
    codec_name = argv[2];
    /* find the mpeg1video encoder 通过名称查找编码器*/
    codec = avcodec_find_encoder_by_name(codec_name);
    if (!codec) {
        fprintf(stderr, "Codec '%s' not found\n", codec_name);
        exit(1);
    }
    c = avcodec_alloc_context3(codec);
    if (!c) {
        fprintf(stderr, "Could not allocate video codec context\n");
        exit(1);
    }
    pkt = av_packet_alloc();
    if (!pkt)
        exit(1);
    /* put sample parameters 填充参数*/
    c->bit_rate = 400000;
    /* resolution must be a multiple of two 分辨率必须是2的倍数*/
    c->width = 352;
    c->height = 288;
    /* frames per second 每秒帧数*/
    c->time_base = (AVRational){1, 25};
    c->framerate = (AVRational){25, 1};
    /* emit one intra frame every ten frames
     * check frame pict_type before passing frame
     * to encoder, if frame->pict_type is AV_PICTURE_TYPE_I
     * then gop_size is ignored and the output of encoder
     * will always be I frame irrespective to gop_size
     * 每 10 帧发出一帧 I 帧
     * 在将帧传递给编码器之前检查帧的 pict_type,
     * 如果 frame->pict_type 是 AV_PICTURE_TYPE_I,那么 gop_size 将被忽略,
     * 编码器的输出将始终是 I 帧,而不考虑 gop_size
     */
    c->gop_size = 10;
    c->max_b_frames = 1;
    c->pix_fmt = AV_PIX_FMT_YUV420P;
    if (codec->id == AV_CODEC_ID_H264)
        av_opt_set(c->priv_data, "preset", "slow", 0);
    /* open it 打开*/
    ret = avcodec_open2(c, codec, NULL);
    if (ret < 0) {
        fprintf(stderr, "Could not open codec: %s\n", av_err2str(ret));
        exit(1);
    }
    f = fopen(filename, "wb");
    if (!f) {
        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_frame_get_buffer(frame, 0);
    if (ret < 0) {
        fprintf(stderr, "Could not allocate the video frame data\n");
        exit(1);
    }
    /* encode 1 second of video 编码一秒视频*/
    for (i = 0; i < 25; i++) {
        fflush(stdout);
        /* make sure the frame data is writable 确保帧数据可写*/
        ret = av_frame_make_writable(frame);
        if (ret < 0)
            exit(1);
        /* prepare a dummy image 准备一帧假图像*/
        /* Y */
        for (y = 0; y < c->height; y++) {
            for (x = 0; x < c->width; x++) {
                frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
            }
        }
        /* Cb and Cr Cb 和 Cr*/
        for (y = 0; y < c->height/2; y++) {
            for (x = 0; x < c->width/2; x++) {
                frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
                frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
            }
        }
        frame->pts = i;
        /* encode the image 编码图像*/
        encode(c, frame, pkt, f);
    }
    /* flush the encoder 刷新编码器*/
    encode(c, NULL, pkt, f);
    /* add sequence end code to have a real MPEG file 添加结尾序列得到一个 MPEG 文件*/
    if (codec->id == AV_CODEC_ID_MPEG1VIDEO || codec->id == AV_CODEC_ID_MPEG2VIDEO)
        fwrite(endcode, 1, sizeof(endcode), f);
    fclose(f);
    avcodec_free_context(&c);
    av_frame_free(&frame);
    av_packet_free(&pkt);
    return 0;
}

二、encode_video.c 编译运行

按照《FFmpeg Ubuntu 20.04 编译》一节安装好 FFmpeg 后,encode_video.c 位于 ~/ffmpeg_build/share/ffmpeg/examples/ 路径下。

  1. 配置 PKG_CONFIG_PATH 环境变量
export PKG_CONFIG_PATH=~/ffmpeg_build/lib/pkgconfig/
  1. make 命令编译这些 examples,其中就包括 encode_video.c
cd ~/ffmpeg_build/share/ffmpeg/examples/
make

运行程序 encode_video,会在当前目录下生成一个 test.mp4 文件。

cd ~/ffmpeg_build/share/ffmpeg/examples/
./encode_video ./test.mp4 mpeg4

运行期间输出的打印

encode_video.png

最后就可以调用 ffplay 播放这个 test.mp4 视频文件了!

cd ~/ffmpeg_build/share/ffmpeg/examples/
ffplay ./test.mp4

encode_video_result.png

参考资料:

1.ffmpeg.org/doxygen/tru…