c - H264解码使用ffmpeg

标签 c ffmpeg

我正在尝试使用 ffmpeg 库解码视频流,我基本上就是这样做的:

void video_decode(const char *filename)
{
    AVCodec *codec;
    AVCodecContext *c= NULL;
    int frame_count=0;
    FILE *f;
    AVFrame *frame;
    uint8_t inbuf[INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
    AVPacket avpkt;
    av_init_packet(&avpkt);
    memset(inbuf + INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
    printf("Decoding video file...\n");
    /* find the h264 video decoder */
    codec = avcodec_find_decoder(AV_CODEC_ID_H264);
    c = avcodec_alloc_context3(codec);
    c->bit_rate = 400000;
    c->width = 1920;
    c->height = 1080;

    if (avcodec_open2(c, codec, NULL) < 0) {
        fprintf(stderr, "Could not open codec\n");
        exit(1);
    }
    frame = av_frame_alloc();
    for (;;) {
        avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);         
    if (avpkt.size == 0)
            break;
        avpkt.data = inbuf;
        while(avpkt.size > 0){

        int len, got_frame;
            len = avcodec_decode_video2(c, frame, &got_frame, &avpkt);          
        if (len < 0) {
                fprintf(stderr, "Errr while decding frame %d\n", frame_count);
                exit (1);
            }
            if (got_frame) {
                //Print out frame information..
        }
            if (avpkt.data) {
                avpkt.size -= len;
                avpkt.data += len;
            }
    }               
    }  
}

但我得到了以下输出:

Decoding video file...
[h264 @ 0x303c040] decode_slice_header error
[h264 @ 0x303c040] decode_slice_header error
[h264 @ 0x303c040] decode_slice_header error
[h264 @ 0x303c040] no frame!
Errr while decding frame 0

显然编解码器的启动是不完整的。你有h264 api的经验吗?任何帮助将不胜感激。

最佳答案

您不能只将随机数 (INBUF_SIZE) 字节放入 AV 数据包中。应该是full AU或者NALU,如果不是annex B,必须先设置extra data字段。对于您的情况,我建议使用 libavformat 打开文件并读取 AVPackets。

关于c - H264解码使用ffmpeg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35910824/

相关文章:

c - JSON - 对象的嵌套

video - 使用 FFMPEG 将大型 HLS 流传输到 MP4 剪辑

在深度嵌套的源/makefile 中正确包含 (POSIX) 库

c - 旋转矩阵,使 Up vector 等于另一个 vector

java - 关闭应用程序JAVA后ffmpeg工作

ffmpeg - 在 MP4 中嵌入定时文本元数据

ffmpeg 无法识别的选项 '--enable-libopus'

Android h264 解码不存在的 PPS 0 引用

c - 哪个是最标准的 : strnlen or strnlen_s?

c# - 将 C 代码移植到 C#