Igor
Igor

Reputation: 375

How to use av_frame_unref in ffmpeg?

  1. Can I create one AVFrame and use it for decoding of all frames? So I call av_frame_alloc() once, decode all frames, and then call av_frame_unref() once. Or I should call av_frame_alloc / av_frame_unref for each frame?
  2. When exactly I should call av_frame_unref, before decoding or after decoding?

A.

av_frame_alloc()

av_frame_unref()

(decoding...)

B. Or this variant:

av_frame_alloc()

(decoding...)

av_frame_unref()

Upvotes: 4

Views: 4451

Answers (2)

the kamilz
the kamilz

Reputation: 1988

Reference counting is a generic process where a dynamically allocated source is shared (e.g. among multiple threads). To prevent freeing the source by a thread and put others offside position, this mechanism is used, often implemented with a simple atomic counter associated with the object.

The threads which accesses the source calls addref, that typically will increase the counter by 1 and when the thread is done using it calls unref and that decreases the counter (in case of ffmpeg these are av_frame_ref and av_frame_unref if I'm not mistaken).

This ensures that the source remains valid until the thread using it is done with it.

Eventually, when the counter reaches zero (no user left), the source is freed safely.

Upvotes: 3

halfelf
halfelf

Reputation: 10107

  1. You could only use one AVFrame struct for the entire decoding/encoding process, by calling av_frame_alloc() once.
  2. av_frame_unref() is only needed when you decide to enable reference counting for your encoding/decoding context, called for each frame.
  3. Use av_frame_free() to free the frame struct and all its buffers at the end of your encoding/decoding process.

See ffmpeg's official examples for how to use them: demuxing_decoding

Upvotes: 3

Related Questions