繁体   English   中英

如何使用ffmpeg从H264 SPS获得宽度和高度

[英]How to get width and height from the H264 SPS using ffmpeg

我正在尝试初始化一个FFMPEG H264编解码器上下文,用SPS帧填充extradata字段,如下所示:

#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 @ 0xc74010] NAL 7/3,4/11长度6
[h264 @ 0xc74010] sps:0 profile:66/10 poc:0 ref:0 8x6 FRM crop:0/0/0/0 420 0/0 b8 reo:-1
视频:h264,1个参考帧,无(左),q = 2-31,200 kb / s

输出显示用所需信息解码sps以计算宽度和高度h264_ps.cmb_width = 8,mb_height = 6,crop_left = crop_right = crop_top = crop_bottom = 0)。

然后我期望获得调用avcodec_string的宽度和高度。
有没有办法在不解码帧的情况下做到这一点?

如果你正确格式化你的extradata,它在avcodec_open2()之后可以在AVCodecContext.width和AVCodecContext.height中使用。

这篇文章将告诉你如何格式化H.264 Stream的序列/图片参数集的可能位置

用虚拟缓冲器馈送解码器使得可以获得在SPS中编码的大小。
使用空PPS和空的非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中提取宽度和高度:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM