Search code examples
ffmpegaacmux

FFmpeg remux without decode/encode


I want to use ffmpeg lib to save rtsp stream to local mp4 file without decode. both the inpout stream and output file use H264+AAC codec. For now I use the following code to read the packet from the input stream and write to the output file.

...
av_write_header(oFmtCtx);
av_init_packet(&packet);
int j = 0;

while (av_read_frame(pIFmtCtx, &packet) >= 0 && j < 140/*temp use to get a period of the stream*/)
{
    //now I only output the audio stream
    if (packet.stream_index == audioStream)
    {
        AVPacket pkt;
        av_init_packet(&pkt);
        pkt.size = packet.size;
        pkt.data = packet.data;
        pkt.dts = AV_NOPTS_VALUE;
        pkt.pts = AV_NOPTS_VALUE;
        pkt.flags |= PKT_FLAG_KEY;
        pkt.stream_index = oStream->index;
        if (av_interleaved_write_frame(oFmtCtx, &pkt) != 0)
        {
            LOGI("Error while writing audio frame\n");
            break;
        }
    }
    j++;

}
av_write_trailer(oFmtCtx);

The file is generated. and when I open it using VLC, the playback lasts for the right time but no audio is outputed. Any help will be greatly appreciated, Thanks in advance.

Bolton


Solution

  • Finally I made it. Below is my code:

    while (j < 140)
    {
        av_read_frame(pIFmtCtx, &packet);
        pkt_stream_index = packet.stream_index;
        pkt_pts = packet.pts;
        pkt_dts = packet.dts;
    
        if (packet.stream_index == audioStream)
        {
            packet.stream_index = oStream->index;
            av_write_frame(oFmtCtx, &packet);
    
            packet.stream_index = pkt_stream_index;
            packet.pts = pkt_pts;
            packet.dts = pkt_dts;
        }
        av_free_packet(&packet);
        j++;
    }
    

    I don't know the reason but it works!