本文介绍了如何使用ffmpeg从H264 SPS获取宽度和高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试初始化FFMPEG H264编解码器上下文,像这样用SPS帧填充extradata字段:

I am trying to initialize an FFMPEG H264 codec context filling the extradata field with the SPS frame like this :

#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>

int main()
{
    const char sps[] = {0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x0a, 0xf8, 0x41, 0xa2};
    av_register_all();
    av_log_set_level(AV_LOG_DEBUG);

    AVCodec *const codec = avcodec_find_decoder(CODEC_ID_H264);
    if (codec != NULL)
    {
        AVCodecContext* ctx = avcodec_alloc_context3(codec);
        ctx->debug = ~0;
        ctx->extradata = (uint8_t *)av_malloc(sizeof(sps) + FF_INPUT_BUFFER_PADDING_SIZE);
        ctx->extradata_size = sizeof(sps);
        memcpy(ctx->extradata,sps,sizeof(sps));
        memset(&ctx->extradata[ctx->extradata_size], 0, FF_INPUT_BUFFER_PADDING_SIZE);

        if (avcodec_open2(ctx, codec, NULL) < 0)
        {
            fprintf(stderr, "Failed to open codec\n");
        }
        else
        {
            char buf[1024];
            avcodec_string(buf,sizeof(buf),ctx,1);
            fprintf(stderr, "%s\n", buf);
        }
        avcodec_close(ctx);
        av_free(ctx);
    }
}

程序的输出为:

输出显示 h264_ps.c (mb_width = 8,mb_height = 6,crop_left = crop_right = crop_top = crop_bottom = 0).

The output show that sps was decoded with the needed information to compute width and height by h264_ps.c (mb_width=8, mb_height=6, crop_left=crop_right=crop_top=crop_bottom=0).

然后我期望调用avcodec_string获得宽度和高度.
有没有一种方法可以不解码帧?

Then I was expecting to get the width and the height calling avcodec_string.
Is there a way to do this without decoding frames ?

推荐答案

为解码器提供虚拟缓冲区可以获取SPS中编码的大小.
使用空的PPS和空的非IDR SLICE:

Feeding the decoder with a dummy buffer make possible to get the size encoded in the SPS.
Using a null PPS and an empty non-IDR SLICE :

int got_frame = 0;
AVPacket pkt;
av_init_packet(&pkt);
char buffer[] = {0x00, 0x00, 0x00, 0x01, 0x68, 0xff, 0x00, 0x00, 0x00, 0x01, 0x21};
pkt.data = buffer;
pkt.size = sizeof(buffer);
AVFrame* frame = av_frame_alloc();
avcodec_decode_video2(ctx, frame, &got_frame, &pkt);
av_frame_free(&frame);
fprintf(stderr, "size: %dx%d\n", ctx->width, ctx->height);

运行此代码会显示错误,但可以从SPS中提取宽度和高度:

Running this code print errors but it allow to extract width and height from the SPS :

[h264 @ 0xd0d040] Missing reference picture, default is 0
[h264 @ 0xd0d040] decode_slice_header error
size: 128x96

这篇关于如何使用ffmpeg从H264 SPS获取宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 02:38
查看更多