使用FFmpeg libav和libx264从图像创建视频?

7
我正在尝试使用ffmpeg库从图像创建视频。这些图像的大小为1920x1080,应该使用.mkv容器编码为H.264。我遇到了各种问题,认为我已经接近解决方案,但这个问题我真的卡住了。使用我所使用的设置,我的视频的前X帧(大约40帧,取决于我用于视频的图像数量和内容)未被编码。avcodec_encode_video2没有返回任何错误(got_picture_ptr = 0),结果是一个看起来正常的视频,但前几秒钟跳动得很奇怪。
因此,这就是我创建视频文件的方式:
// m_codecContext is an instance variable of type AVCodecContext *
// m_formatCtx is an instance variable of type AVFormatContext *

// outputFileName is a valid filename ending with .mkv
AVOutputFormat *oformat = av_guess_format(NULL, outputFileName, NULL);
if (oformat == NULL)
{
    oformat = av_guess_format("mpeg", NULL, NULL);
}

// oformat->video_codec is AV_CODEC_ID_H264
AVCodec *codec = avcodec_find_encoder(oformat->video_codec);

m_codecContext = avcodec_alloc_context3(codec);
m_codecContext->codec_id = oformat->video_codec;
m_codecContext->codec_type = AVMEDIA_TYPE_VIDEO;
m_codecContext->gop_size = 30;
m_codecContext->bit_rate = width * height * 4
m_codecContext->width = width;
m_codecContext->height = height;
m_codecContext->time_base = (AVRational){1,frameRate};
m_codecContext->max_b_frames = 1;
m_codecContext->pix_fmt = AV_PIX_FMT_YUV420P;

m_formatCtx = avformat_alloc_context();
m_formatCtx->oformat = oformat;
m_formatCtx->video_codec_id = oformat->video_codec;

snprintf(m_formatCtx->filename, sizeof(m_formatCtx->filename), "%s", outputFileName);

AVStream *videoStream = avformat_new_stream(m_formatCtx, codec);
if(!videoStream)
{
   printf("Could not allocate stream\n");
}
videoStream->codec = m_codecContext;

if(m_formatCtx->oformat->flags & AVFMT_GLOBALHEADER)
{
   m_codecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;
}

avcodec_open2(m_codecContext, codec, NULL) < 0);
avio_open(&m_formatCtx->pb, outputFileName.toStdString().c_str(), AVIO_FLAG_WRITE);
avformat_write_header(m_formatCtx, NULL);

这是添加框架的方法:

void VideoCreator::writeImageToVideo(const QSharedPointer<QImage> &img, int frameIndex)
{
    AVFrame *frame = avcodec_alloc_frame();

    /* alloc image and output buffer */

    int size = m_codecContext->width * m_codecContext->height;
    int numBytes = avpicture_get_size(m_codecContext->pix_fmt, m_codecContext->width, m_codecContext->height);

    uint8_t *outbuf = (uint8_t *)malloc(numBytes);
    uint8_t *picture_buf = (uint8_t *)av_malloc(numBytes);

    int ret = av_image_fill_arrays(frame->data, frame->linesize, picture_buf, m_codecContext->pix_fmt, m_codecContext->width, m_codecContext->height, 1);

    frame->data[0] = picture_buf;
    frame->data[1] = frame->data[0] + size;
    frame->data[2] = frame->data[1] + size/4;
    frame->linesize[0] = m_codecContext->width;
    frame->linesize[1] = m_codecContext->width/2;
    frame->linesize[2] = m_codecContext->width/2;

    fflush(stdout);


    for (int y = 0; y < m_codecContext->height; y++)
    {
        for (int x = 0; x < m_codecContext->width; x++)
        {
            unsigned char b = img->bits()[(y * m_codecContext->width + x) * 4 + 0];
            unsigned char g = img->bits()[(y * m_codecContext->width + x) * 4 + 1];
            unsigned char r = img->bits()[(y * m_codecContext->width + x) * 4 + 2];

            unsigned char Y = (0.257 * r) + (0.504 * g) + (0.098 * b) + 16;

            frame->data[0][y * frame->linesize[0] + x] = Y;

            if (y % 2 == 0 && x % 2 == 0)
            {
                unsigned char V = (0.439 * r) - (0.368 * g) - (0.071 * b) + 128;
                unsigned char U = -(0.148 * r) - (0.291 * g) + (0.439 * b) + 128;

                frame->data[1][y/2 * frame->linesize[1] + x/2] = U;
                frame->data[2][y/2 * frame->linesize[2] + x/2] = V;
            }
        }
    }

    int pts = frameIndex;//(1.0 / 30.0) * 90.0 * frameIndex;

    frame->pts = pts;//av_rescale_q(m_codecContext->coded_frame->pts, m_codecContext->time_base, formatCtx->streams[0]->time_base); //(1.0 / 30.0) * 90.0 * frameIndex;

    int got_packet_ptr;
    AVPacket packet;
    av_init_packet(&packet);
    packet.data = outbuf;
    packet.size = numBytes;
    packet.stream_index = formatCtx->streams[0]->index;
    packet.flags |= AV_PKT_FLAG_KEY;
    packet.pts = packet.dts = pts;
    m_codecContext->coded_frame->pts = pts;

    ret = avcodec_encode_video2(m_codecContext, &packet, frame, &got_packet_ptr);
    if (got_packet_ptr != 0)
    {
        m_codecContext->coded_frame->pts = pts;  // Set the time stamp

        if (m_codecContext->coded_frame->pts != (0x8000000000000000LL))
        {
            pts = av_rescale_q(m_codecContext->coded_frame->pts, m_codecContext->time_base, formatCtx->streams[0]->time_base);
        }
        packet.pts = pts;
        if(m_codecContext->coded_frame->key_frame)
        {
           packet.flags |= AV_PKT_FLAG_KEY;
        }

        std::cout << "pts: " << packet.pts << ", dts: "  << packet.dts << std::endl;

        av_interleaved_write_frame(formatCtx, &packet);
        av_free_packet(&packet);
    }

    free(picture_buf);
    free(outbuf);
    av_free(frame);
    printf("\n");
}

这是清理操作:

int numBytes = avpicture_get_size(m_codecContext->pix_fmt, m_codecContext->width, m_codecContext->height);
int got_packet_ptr = 1;

int ret;
//        for(; got_packet_ptr != 0; i++)
while (got_packet_ptr)
{
    uint8_t *outbuf = (uint8_t *)malloc(numBytes);

    AVPacket packet;
    av_init_packet(&packet);
    packet.data = outbuf;
    packet.size = numBytes;

    ret = avcodec_encode_video2(m_codecContext, &packet, NULL, &got_packet_ptr);
    if (got_packet_ptr)
    {
        av_interleaved_write_frame(m_formatCtx, &packet);
    }

    av_free_packet(&packet);
    free(outbuf);
}

av_write_trailer(formatCtx);

avcodec_close(m_codecContext);
av_free(m_codecContext);
printf("\n");

我认为这可能与PTS和DTS值有关,但我尝试了一切。帧索引似乎是最有意义的。图像是正确的,我可以将它们保存到文件中没有任何问题。我已经没有更多的想法了。

如果有人比我更懂,请告诉我,我将不胜感激...

更新:

如果有帮助的话,这是视频编码结束时的输出:

[libx264 @ 0x7fffc00028a0] frame I:19    Avg QP:14.24  size:312420
[libx264 @ 0x7fffc00028a0] frame P:280   Avg QP:19.16  size:148867
[libx264 @ 0x7fffc00028a0] frame B:181   Avg QP:21.31  size: 40540
[libx264 @ 0x7fffc00028a0] consecutive B-frames: 24.6% 75.4%
[libx264 @ 0x7fffc00028a0] mb I  I16..4: 30.9% 45.5% 23.7%
[libx264 @ 0x7fffc00028a0] mb P  I16..4:  4.7%  9.1%  4.5%  P16..4: 23.5% 16.6% 12.6%  0.0%  0.0%    skip:28.9%
[libx264 @ 0x7fffc00028a0] mb B  I16..4:  0.6%  0.5%  0.3%  B16..8: 26.7% 11.0%  5.5%  direct: 3.9%  skip:51.5%  L0:39.4% L1:45.0% BI:15.6%
[libx264 @ 0x7fffc00028a0] final ratefactor: 19.21
[libx264 @ 0x7fffc00028a0] 8x8 transform intra:48.2% inter:47.3%
[libx264 @ 0x7fffc00028a0] coded y,uvDC,uvAC intra: 54.9% 53.1% 30.4% inter: 25.4% 13.5% 4.2%
[libx264 @ 0x7fffc00028a0] i16 v,h,dc,p: 41% 29% 11% 19%
[libx264 @ 0x7fffc00028a0] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 16% 26% 31%  3%  4%  3%  7%  3%  6%
[libx264 @ 0x7fffc00028a0] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 30% 26% 14%  4%  5%  4%  7%  4%  7%
[libx264 @ 0x7fffc00028a0] i8c dc,h,v,p: 58% 26% 13%  3%
[libx264 @ 0x7fffc00028a0] Weighted P-Frames: Y:17.1% UV:3.6%
[libx264 @ 0x7fffc00028a0] ref P L0: 63.1% 21.4% 11.4%  4.1%  0.1%    
[libx264 @ 0x7fffc00028a0] ref B L0: 85.7% 14.3%
[libx264 @ 0x7fffc00028a0] kb/s:27478.30
2个回答

2

Libav可能会延迟处理初始帧。一个好的做法是在处理完所有帧后检查是否有延迟帧。具体操作如下:

int i=NUMBER_OF_FRAMES_PREVIOUSLY_ENCODED
for(; got_packet_ptr; i++)
   ret = avcodec_encode_video2(m_codecContext, &packet, NULL, &got_packet_ptr);
//Write the packets to a container after this.

重点是将一个NULL指针传递到要编码的帧的位置,并继续执行此操作,直到获得的数据包为非空为止。请参阅此链接中的代码示例-“获取延迟帧”下面的部分。
另一种更简单的方法是将B帧的数量设置为0。
m_codecContext->max_b_frames = 0;

请告诉我这是否可以正常工作。

此外,您还没有使用libx264 API。您可以利用libx264 API对视频进行编码,该API具有更简单和更清晰的语法。而且它为您提供了更多的控制设置和更好的性能。

对于将视频流写入mkv容器,您仍然需要使用libav库。


非常感谢您抽出时间。不幸的是,无论设置B帧数量还是写入延迟帧似乎都行不通。虽然显然存在延迟帧,因为程序进入循环。视频实际上似乎更少跳动,但仍然不正确。似乎在2秒后有一个空洞,在这个空洞中只显示了2张静止图像,持续了2秒钟,就好像中间的帧丢失了一样。 - marikaner
你能指定生成视频的帧数和你打算编码的总图像数量吗?你可以检查调用av_interleaved_write()的次数(根据你的更新应该是480次)。 另外,frameIndex的计算是什么? - Hrishikesh_Pardeshi
是的,我打算编码的图像数量是480张。frameIndex只是一个整数,每帧从0增加到479。在使用实际帧进行avcodec_encode_video2后,av_interleaved_write()被调用442次,在使用NULL后,它被调用38次。 - marikaner
看起来没问题。如果编码了所有480帧,那么输出的视频应该没有任何问题?可以使用诸如virtualDub之类的工具检查生成的视频,逐帧进行检查是否有任何输入图像丢失。如果您能提供输出,则我更容易想象问题所在。 - Hrishikesh_Pardeshi
只有在允许b帧编码时,才会延迟处理帧。您在更新中放置的输出显示181个b帧已编码,这是在max_bframes设置为0还是正值下完成的? - Hrishikesh_Pardeshi

0

至少对我来说,添加

frame->width = m_codecContext->width;
frame->height = m_codecContext->height;
frame->format = m_codecContext->pix_fmt;

让这个示例代码按预期工作。


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