【问题标题】:FFmpeg decode raw buffer with avcodec_decode_video2FFmpeg 使用 avcodec_decode_video2 解码原始缓冲区
【发布时间】:2014-01-14 05:23:11
【问题描述】:

我收到一个 h264 流,我至少知道一帧的大小。流进来了,因为我可以将它存储在一个文件中并使用 vlc 播放。播放文件对我来说没问题,因为我包含了 libavformat。但是 libavformat 给了我一个 AVPacket,我可以直接给 avcodec_decode_video2。在这种情况下,我得到了一个字节流。如何将原始 h264 流提供给 avcodec_decode_video2?如何将我的数据包装到 AVPacket 中。 VLC 不需要猜测任何数据。

【问题讨论】:

    标签: c++ ffmpeg libavcodec


    【解决方案1】:

    解码流或多或少容易。这段代码非常适合我:

    class ffmpegstreamdestination
    {
    public:
        ffmpegstreamdestination(AVCodecID decoder): 
        {       
            m_pCodec= avcodec_find_decoder(decoder);
            m_pCodecCtx = avcodec_alloc_context3(m_pCodec);
            avcodec_open2(m_pCodecCtx,m_pCodec,0);
            m_pFrame=avcodec_alloc_frame();
        }
    
        ~ffmpegstreamdestination()
        {
            av_free(m_pFrame);
            avcodec_close(m_pCodecCtx);
        }
    
        void decodeStreamData(unsigned char * pData, size_t sz)
        {
            AVPacket        packet;
            av_init_packet(&packet);
    
            packet.data=pData;
            packet.size=(int)sz;
            int framefinished=0;
            int nres=avcodec_decode_video2(m_pCodecCtx,m_pFrame,&framefinished,&packet);
    
            if(framefinished)
            {
                       // do the yuv magic and call a consumer
            }
    
            return;
        }
    
    protected:
        AVCodecContext  *m_pCodecCtx;
        AVCodec         *m_pCodec;
        AVFrame         *m_pFrame;
    };
    

    调用 decodeStreamData 期望数据为帧。您必须在流中搜索 NAL(或多或少是一个标头幻数),它在 h264 案例 0x00000001 中。它是一帧的开始。填充 AVPacket 并没有我想象的那么成问题。如果您没有这些信息,您可以将属性保留在其中,因为它们是由 av_init_packet 初始化的。例如,只有当您有不同的帧速率时才会出现问题。

    与往常一样,如果您发现错误或认为某些方法会更好地工作,我们欢迎您发送短消息。

    【讨论】:

    • 嗨,我如何解析0x00000001,因为这个起始码在SPSPPS 之前重复?
    • @nmxprime 最好就此提出一个新问题。据我所知,您可以简单地遍历 pData,例如: for(size_t i=0;i
    • 我试过这样,但我可能迭代错误,所以没有成功!让我试试!!实际上,通常该文件包含 100 帧的数据,这意味着 100 的(sps,pps and data)。相同的起始码用于 sps、pps 和数据。顺便说一句,你说的是什么边界检查?
    • @nmxprime 我们的问题将在评论部分做出回应。使用您的代码打开一个新问题。在此处为您的问题添加评论,我 + 100 万编码员将调查您的问题 :-)
    • 我有来自 RTSP 流的原始数据。收到此错误“[h264 @ 001436e0] no frame!”,“nres”值始终小于 0。我的代码有什么问题吗?
    猜你喜欢
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 2018-03-27
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    相关资源
    最近更新 更多