AVPacket 해제에 대한 글


출처 :  http://stackoverflow.com/questions/26090992/ffmpeg-can-not-free-avpacket-when-decode-h264-stream





av_free_packet will clear your packet data, the same pointer that was allocated inside av_read_frame. But you changed it in packet.data += bytesDecoded; => crash.

Several advices:

  • No need to call av_init_packet if the first use of your packet is av_read_frame (it is done inside this function). But if you keep your code, you need it in order to initialize packet.size to 0 (tested, but not initialized the first time)

  • Call av_free_packet each time you are done with the packet data, only when the decode is successful. In your code, it means you must call it after avcodec_decode_video2, even if the frame is not finished.

  • Once your packed is decoded (i.e. avcodec_decode_video2 is ok, no matter if frameFinished is true or false), you can free it. No need to keep it and change data pointer. The process is "read packet, decode it, free it. read next packet, decode it, free it.". (Note that this does not apply to audio packets).

I suggest simplify your main loop by something like (read first, decode after):

while(true)
{
    // Step 1: Read packet
    while(true)
    {
        av_read_frame(pFormatCtx, &packet);

        // todo: Error handling

        if(packet.stream_index != videoStreamIndex)
        {
            av_free_packet(&packet);
        }
        else
        {
            break;
        }
    } while (packet.stream_index != videoStreamIndex);

    // Step 2/3: Decode and free
    avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
    av_free_packet(&packet);

    // todo: Error handling and checking frameFinished if needed
    // Of course, if you need to use the packet now, move the av_free_packet() after this
}


Posted by 세모아
,