簡體   English   中英

我如何通過 libavformat 將 H264 流混合到 MP4 文件中

[英]How can i mux H264 stream into MP4 file via libavformat

我想實現一個應用程序,首先解碼一個多媒體文件(例如test.mp4文件,視頻編解碼器id是H264),得到一個視頻流和一個音頻流,然后在音頻流中做一些不同,最后編碼視頻流(使用 libx264)和音頻流到結果文件(result.mp4)。 為了提高效率,我省略了視頻流的解碼和編碼,我通過函數“av_read_frame”得到視頻包,然后通過函數“av_write_frame”直接輸出到結果文件中。 但是輸出文件中沒有圖片,輸出文件的大小相當小。

我跟蹤了ffmpeg的代碼,發現在函數“av_write_frame->mov_write_packet->ff_mov_write_packet”中,會調用函數“ff_avc_parse_nal_units”來獲取nal單元的大小,但是返回值很小(比如208字節)。

我發現MP4文件中的H264碼流沒有以Annex-B格式存儲,所以找不到起始碼(0x000001),現在我的問題是如何將H264碼流改成Annex-B格式,並制作行得通嗎?我在每一幀的開頭手動添加了啟動代碼,但它仍然無法正常工作。

任何人都可以給我任何提示嗎?非常感謝。 以下是與我類似的代碼:

    // write the stream header, if any
    av_write_header(pFormatCtxEnc);

    .........
    /**
    * Init of Encoder and Decoder
    */

    bool KeyFlag = false;
    bool KeyFlagEx = false;
    // Read frames and save frames to disk
    int iPts = 1;
    av_init_packet(&packet);
    while(av_read_frame(pFormatCtxDec, &packet)>=0)
    {
            if (packet.flags == 1)
                    KeyFlag = true;

            if (!KeyFlag)
                    continue;

            if (m_bStop)
            {
                    break;
            }

            // Is this a packet from the video stream?
            if(packet.stream_index == videoStream)
            {
                    currentframeNum ++;
                    if (progressCB != NULL && currentframeNum%20 == 0)
                    {
                            float fpercent = (float)currentframeNum/frameNum;
                            progressCB(fpercent,m_pUser);
                    }

                    if (currentframeNum >= beginFrame && currentframeNum <= endFrane)
                    {
                            if (packet.flags == 1)
                                    KeyFlagEx = true;

                            if (!KeyFlagEx)
                                    continue;
                            packet.dts = iPts ++;
                            av_write_frame(pFormatCtxEnc, &packet);

                    }
            }
            // Free the packet that was allocated by av_read_frame
    }

    // write the trailer, if any
    av_write_trailer(pFormatCtxEnc);

    /**
    * Release of encoder and decoder
    */

    return true;

你可以試試這個: libavcodec/h264_mp4toannexb_bsf.c 它將不帶起始碼的比特流轉換為帶起始碼的比特流。

使用您的源文件,是否ffmpeg -i src.mp4 -vcodec copy -an dst.mp4工作? 如果添加-bsf h264_mp4toannexb是否有效? (當然,都使用與您嘗試以編程方式使用的相同版本/構建的ffmpeg)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM