[Libav-user] AVPacket av_malloc av_packet_unref question

Charles linux2 at orion15.org
Mon Aug 22 03:36:27 EEST 2016

On 08/21/2016 07:23 PM, Brian Brice wrote:
> You should probably use av_packet_alloc instead of av_malloc on the
> AVPacket.  This will ensure that each field is initialized properly.
> The demuxer could set the data pointer to its own internal storage
> (when buf is NULL) which can be reused when you call av_read_frame
> another time.  The call to av_packet_unref is mostly to decrement the
> reference count on the buf pointer.  It does other things, like
> releasing the side data and resetting the fields to some default.
> On Fri, Aug 19, 2016 at 3:31 PM, Charles <linux2 at orion15.org> wrote:
>> I have a piece of code that appears to work, that is to say it does stream
>> packets..
>> It goes like this:
>> av_packet = (AVPacket *) av_malloc( sizeof( AVPacket ) );
>> while ( 1 ) /// reading in from file out to mpegts
>> {
>>    av_read_frame( av_in_fmt_ctx, m_avpacket );
>> [...]
>>    ret = av_interleaved_write_frame( av_out_fmt_ctx, av_packet );
>>    av_packet_unref( av_packet );
>> }
>> In the include headers I find this type of verbage ::
>>  * The side data is always allocated with av_malloc(), copied by
>>  * av_packet_ref() and freed by av_packet_unref().
>> From reading the av_read_frame I know the packed is a reference to another
>> packet (at least the buf).
>> Question :
>> What is av_malloc doing if the packet is getting unref and passed back into
>> av_read_frame without another malloc?
>> Follow Up :
>> Is this thread safe?

This may be poor form but I just declared an AVPacket

    /// \note setup stuff used in ReadFrame
    av_init_packet( &av_pkt );
    av_pkt.data = NULL;  /// demux will allocate
    av_pkt.size = 0;

    Comments from av_read_frame

          * If pkt->buf is NULL, then the packet is valid until the next
          * av_read_frame() or until avformat_close_input(). Otherwise the packet
          * is valid indefinitely. In both cases the packet must be freed with
          * av_packet_unref when it is no longer needed.

I am using the new ABI avcodec_send_packet / avcodec_receive_frame
Since it is a spinning thread, the packet stays in scope and I just never delete it...
Seems to work ok


More information about the Libav-user mailing list