27 #include <stdatomic.h>
99 #if FF_API_THREAD_SAFE_CALLBACKS
156 #if FF_API_THREAD_SAFE_CALLBACKS
157 #define THREAD_SAFE_CALLBACKS(avctx) \
158 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
230 "free the frame on failure. This is a bug, please report it.\n");
281 if (dst !=
src && (for_user ||
src->codec->update_thread_context)) {
319 if (
src->hw_frames_ctx) {
334 #if FF_API_CODED_FRAME
374 #if FF_API_THREAD_SAFE_CALLBACKS
380 if (
src->slice_count &&
src->slice_offset) {
394 #if FF_API_THREAD_SAFE_CALLBACKS
409 f->extended_data =
f->data;
437 memory_order_relaxed);
439 #if FF_API_THREAD_SAFE_CALLBACKS
477 #if FF_API_THREAD_SAFE_CALLBACKS
522 AVFrame *picture,
int *got_picture_ptr,
566 p = &fctx->
threads[finished++];
590 }
while (!avpkt->
size && !*got_picture_ptr && err >= 0 && finished != fctx->
next_finished);
615 p =
f->owner[field]->internal->thread_ctx;
619 "%p finished %d field %d\n", progress, n, field);
638 p =
f->owner[field]->internal->thread_ctx;
642 "thread awaiting %d field %d from %p\n", n, field, progress);
694 for (
i = 0;
i < thread_count;
i++) {
710 #define OFFSET_ARRAY(...) __VA_ARGS__, SENTINEL
711 #define DEFINE_OFFSET_ARRAY(type, name, mutexes, conds) \
712 static const unsigned name ## _offsets[] = { offsetof(type, pthread_init_cnt),\
713 OFFSET_ARRAY mutexes, \
716 #define OFF(member) offsetof(FrameThreadContext, member)
718 (
OFF(buffer_mutex),
OFF(hwaccel_mutex),
OFF(async_mutex)),
722 #define OFF(member) offsetof(PerThreadContext, member)
725 (
OFF(input_cond),
OFF(progress_cond),
OFF(output_cond)));
730 unsigned cnt = *(
unsigned*)((
char*)obj +
offsets[0]);
731 const unsigned *cur_offset =
offsets;
733 for (; *(++cur_offset) !=
SENTINEL && cnt; cnt--)
735 for (; *(++cur_offset) !=
SENTINEL && cnt; cnt--)
741 const unsigned *cur_offset =
offsets;
745 #define PTHREAD_INIT_LOOP(type) \
746 for (; *(++cur_offset) != SENTINEL; cnt++) { \
747 pthread_ ## type ## _t *dst = (void*)((char*)obj + *cur_offset); \
748 err = pthread_ ## type ## _init(dst, NULL); \
750 err = AVERROR(err); \
758 *(
unsigned*)((
char*)obj +
offsets[0]) = cnt;
777 for (
i = 0;
i < thread_count;
i++) {
793 #if FF_API_THREAD_SAFE_CALLBACKS
853 (*threads_to_free)++;
861 copy->internal->thread_ctx = p;
867 if (!
copy->priv_data)
885 copy->internal->last_pkt_props = p->
avpkt;
888 copy->internal->is_copy = 1;
930 if (thread_count <= 1) {
950 avctx->
delay =
src->thread_count - 1;
958 for (;
i < thread_count; ) {
997 #if FF_API_THREAD_SAFE_CALLBACKS
1027 f->owner[0] =
f->owner[1] = avctx;
1040 av_log(avctx,
AV_LOG_ERROR,
"get_buffer() cannot be called after ff_thread_finish_setup()\n");
1057 #if !FF_API_THREAD_SAFE_CALLBACKS
1090 #if FF_API_THREAD_SAFE_CALLBACKS
1100 av_log(avctx,
AV_LOG_ERROR,
"get_format() cannot be called after ff_thread_finish_setup()\n");
1130 #if FF_API_THREAD_SAFE_CALLBACKS
1148 f->owner[0] =
f->owner[1] =
NULL;
1150 #if !FF_API_THREAD_SAFE_CALLBACKS
1154 if (can_direct_free || !
f->f->buf[0]) {
1162 if (p->num_released_buffers == p->released_buffers_allocated) {
1164 sizeof(*p->released_buffers));
1167 p->released_buffers =
tmp;
1170 if (!
tmp || !
tmp[p->released_buffers_allocated]) {
1174 p->released_buffers_allocated++;
1177 dst = p->released_buffers[p->num_released_buffers];
1180 p->num_released_buffers++;
1188 av_log(avctx,
AV_LOG_ERROR,
"Could not queue a frame for freeing, this will leak\n");
1189 memset(
f->f->buf, 0,
sizeof(
f->f->buf));
1190 if (
f->f->extended_buf)
1191 memset(
f->f->extended_buf, 0,
f->f->nb_extended_buf *
sizeof(*
f->f->extended_buf));
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Libavcodec external API header.
#define FF_THREAD_FRAME
Decode more than one frame at once.
refcounted data buffer API
#define flags(name, subs,...)
common internal and external API header
#define FFSWAP(type, a, b)
int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
Get a buffer for a frame.
int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
Select the (possibly hardware accelerated) pixel format.
#define atomic_store(object, desired)
#define atomic_load_explicit(object, order)
#define atomic_load(object)
#define atomic_store_explicit(object, desired, order)
#define atomic_init(obj, value)
#define pthread_mutex_lock(a)
#define pthread_mutex_unlock(a)
reference-counted frame API
int av_opt_copy(void *dst, const void *src)
Copy options from src object into dest object.
void av_opt_free(void *obj)
Free all allocated objects in obj.
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
int avcodec_default_get_buffer2(AVCodecContext *s, AVFrame *frame, int flags)
The default callback for AVCodecContext.get_buffer2().
enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
int av_packet_ref(AVPacket *dst, const AVPacket *src)
Setup a new reference to the data described by a given packet.
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
AVBufferRef * av_buffer_alloc(buffer_size_t size)
Allocate an AVBuffer of the given size using av_malloc().
int av_buffer_replace(AVBufferRef **pdst, AVBufferRef *src)
Ensure dst refers to the same data as src.
AVBufferRef * av_buffer_ref(AVBufferRef *buf)
Create a new reference to an AVBuffer.
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
void av_frame_move_ref(AVFrame *dst, AVFrame *src)
Move everything contained in src to dst and reset src.
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
#define AV_LOG_WARNING
Something somehow does not look correct.
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
void * av_memdup(const void *p, size_t size)
Duplicate a buffer with av_malloc().
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Allocate, reallocate, or free an array.
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Allocate, reallocate, or free an array through a pointer to a pointer.
void * av_mallocz_array(size_t nmemb, size_t size)
Allocate a memory block for an array with av_mallocz().
static const int offsets[]
#define HWACCEL_CAP_ASYNC_SAFE
#define FF_CODEC_CAP_ALLOCATE_PROGRESS
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
#define FF_API_THREAD_SAFE_CALLBACKS
common internal API header
#define FF_DISABLE_DEPRECATION_WARNINGS
#define FF_ENABLE_DEPRECATION_WARNINGS
#define attribute_align_arg
Memory handling functions.
static av_always_inline int pthread_cond_broadcast(pthread_cond_t *cond)
static av_always_inline int pthread_cond_signal(pthread_cond_t *cond)
static av_always_inline int pthread_cond_destroy(pthread_cond_t *cond)
static av_always_inline int pthread_join(pthread_t thread, void **value_ptr)
static av_always_inline int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
int(* cond)(enum AVPixelFormat pix_fmt)
AVPixelFormat
Pixel format.
static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
static av_cold int init_pthread(void *obj, const unsigned offsets[])
void ff_thread_report_progress(ThreadFrame *f, int n, int field)
Notify later decoding threads when part of their reference picture is ready.
static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
Update the next thread's AVCodecContext with values set by the user.
@ NEEDS_CLOSE
AVCodec->close needs to be called.
@ INITIALIZED
Thread has been properly set up.
@ UNINITIALIZED
Thread has not been created, AVCodec->close mustn't be called.
FF_ENABLE_DEPRECATION_WARNINGS int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
Wrapper around get_buffer() for frame-multithreaded codecs.
static void async_unlock(FrameThreadContext *fctx)
static attribute_align_arg void * frame_worker_thread(void *arg)
Codec worker thread.
void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
int ff_frame_thread_init(AVCodecContext *avctx)
static av_cold int init_thread(PerThreadContext *p, int *threads_to_free, FrameThreadContext *fctx, AVCodecContext *avctx, AVCodecContext *src, const AVCodec *codec, int first)
static void release_delayed_buffers(PerThreadContext *p)
Releases the buffers that this decoding thread was the last user of.
void ff_thread_await_progress(ThreadFrame *f, int n, int field)
Wait for earlier decoding threads to finish reference pictures.
@ STATE_GET_FORMAT
Set when the codec calls get_format().
@ STATE_INPUT_READY
Set when the thread is awaiting a packet.
@ STATE_GET_BUFFER
Set when the codec calls get_buffer().
#define DEFINE_OFFSET_ARRAY(type, name, mutexes, conds)
void ff_thread_finish_setup(AVCodecContext *avctx)
If the codec defines update_thread_context(), call this when they are ready for the next thread to st...
void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
Wrapper around release_buffer() frame-for multithreaded codecs.
static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx, AVPacket *avpkt)
static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
Update the next thread's AVCodecContext with values from the reference thread's context.
#define THREAD_SAFE_CALLBACKS(avctx)
#define PTHREAD_INIT_LOOP(type)
int ff_thread_decode_frame(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, AVPacket *avpkt)
Submit a new frame to a decoding thread.
static void async_lock(FrameThreadContext *fctx)
static av_cold void free_pthread(void *obj, const unsigned offsets[])
int ff_thread_can_start_frame(AVCodecContext *avctx)
static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
Waits for all threads to finish.
void ff_thread_flush(AVCodecContext *avctx)
Wait for decoding threads to finish and reset internal state.
FF_DISABLE_DEPRECATION_WARNINGS enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
Wrapper around get_format() for frame-multithreaded codecs.
uint8_t * data
The data buffer.
Describe the class of an AVClass context structure.
main external API structure.
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
int hwaccel_flags
Bit set of AV_HWACCEL_FLAG_* flags, which affect hardware accelerated decoding (if active).
int width
picture width / height.
int flags2
AV_CODEC_FLAG2_*.
enum AVSampleFormat sample_fmt
audio sample format
enum AVPixelFormat sw_pix_fmt
Nominal unaccelerated pixel format, see AV_PIX_FMT_xxx.
enum AVColorRange color_range
MPEG vs JPEG YUV range.
int slice_flags
slice flags
enum AVPixelFormat(* get_format)(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
callback to negotiate the pixelFormat
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
AVBufferRef * hw_frames_ctx
A reference to the AVHWFramesContext describing the input (for encoding) or output (decoding) frames.
enum AVMediaType codec_type
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
attribute_deprecated AVFrame * coded_frame
the picture in the bitstream
int slice_count
slice count
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
const struct AVHWAccel * hwaccel
Hardware accelerator in use.
int active_thread_type
Which multithreading methods are in use by the codec.
int64_t reordered_opaque
opaque 64-bit number (generally a PTS) that will be reordered and output in AVFrame....
int has_b_frames
Size of the frame reordering buffer in the decoder.
void(* draw_horiz_band)(struct AVCodecContext *s, const AVFrame *src, int offset[AV_NUM_DATA_POINTERS], int y, int type, int height)
If non NULL, 'draw_horiz_band' is called by the libavcodec decoder to draw a horizontal band.
enum AVDiscard skip_loop_filter
Skip loop filtering for selected frames.
const struct AVCodec * codec
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
int idct_algo
IDCT algorithm, see FF_IDCT_* below.
int export_side_data
Bit set of AV_CODEC_EXPORT_DATA_* flags, which affects the kind of metadata exported in frame,...
enum AVColorSpace colorspace
YUV colorspace type.
int sample_rate
samples per second
int frame_number
Frame counter, set by libavcodec.
attribute_deprecated int thread_safe_callbacks
Set by the client if its custom get_buffer() callback can be called synchronously from another thread...
int thread_count
thread count is used to decide how many independent tasks should be passed to execute()
void * opaque
Private data of the user, can be used to carry app specific stuff.
void * hwaccel_context
Hardware accelerator context.
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
int flags
AV_CODEC_FLAG_*.
int channels
number of audio channels
enum AVDiscard skip_idct
Skip IDCT/dequantization for selected frames.
enum AVChromaLocation chroma_sample_location
This defines the location of chroma samples.
int coded_width
Bitstream width / height, may be different from width/height e.g.
uint64_t channel_layout
Audio channel layout.
int * slice_offset
slice offsets in the frame in bytes
int(* get_buffer2)(struct AVCodecContext *s, AVFrame *frame, int flags)
This callback is called at the beginning of each frame to get data buffer(s) for it.
struct AVCodecInternal * internal
Private context used for internal data.
enum AVDiscard skip_frame
Skip decoding for selected frames.
int is_copy
Whether the parent AVCodecContext is a copy of the context which had init() called on it.
void * hwaccel_priv_data
hwaccel-specific private data
int caps_internal
Internal codec capabilities.
const AVClass * priv_class
AVClass for the private context.
int(* init)(struct AVCodecContext *)
int(* update_thread_context)(struct AVCodecContext *dst, const struct AVCodecContext *src)
Copy necessary context variables from a previous thread context to the current one.
int(* decode)(struct AVCodecContext *avctx, void *outdata, int *got_frame_ptr, struct AVPacket *avpkt)
Decode picture or subtitle data.
void(* flush)(struct AVCodecContext *)
Flush buffers.
int(* close)(struct AVCodecContext *)
int capabilities
Codec capabilities.
AVFormatInternal * internal
An opaque field for libavformat internal usage.
void * priv_data
Format private data.
This structure describes decoded (raw) audio or video data.
AVBufferRef * buf[AV_NUM_DATA_POINTERS]
AVBuffer references backing the data for this frame.
int64_t pkt_dts
DTS copied from the AVPacket that triggered returning this frame.
int caps_internal
Internal hwaccel capabilities.
This structure stores compressed data.
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Context stored in the client AVCodecInternal thread_ctx.
pthread_mutex_t async_mutex
int next_decoding
The next context to submit a packet to.
PerThreadContext * threads
The contexts for each thread.
int delaying
Set for the first N packets, where N is the number of threads.
const AVHWAccel * stash_hwaccel
pthread_cond_t async_cond
PerThreadContext * prev_thread
The last thread submit_packet() was called on.
int next_finished
The next context to return output from.
pthread_mutex_t buffer_mutex
Mutex used to protect get/release_buffer().
void * stash_hwaccel_context
void * stash_hwaccel_priv
unsigned pthread_init_cnt
Number of successfully initialized mutexes/conditions.
pthread_mutex_t hwaccel_mutex
This lock is used for ensuring threads run in serial when hwaccel is used.
Context used by codec threads and stored in their AVCodecInternal thread_ctx.
struct FrameThreadContext * parent
AVCodecContext * avctx
Context used to decode packets passed to this thread.
enum AVPixelFormat * available_formats
Format array for get_format()
int die
Set when the thread should exit.
pthread_mutex_t mutex
Mutex used to protect the contents of the PerThreadContext.
int released_buffers_allocated
AVFrame ** released_buffers
Array of frames passed to ff_thread_release_buffer().
int requested_flags
flags passed to get_buffer() for requested_frame
atomic_int debug_threads
Set if the FF_DEBUG_THREADS option is set.
enum AVPixelFormat result_format
get_format() result
pthread_mutex_t progress_mutex
Mutex used to protect frame progress values and progress_cond.
unsigned pthread_init_cnt
Number of successfully initialized mutexes/conditions.
AVPacket * avpkt
Input packet (for decoding) or output (for encoding).
int got_frame
The output of got_picture_ptr from the last avcodec_decode_video() call.
int result
The result of the last codec decode/encode() call.
pthread_cond_t input_cond
Used to wait for a new packet from the main thread.
AVFrame * frame
Output frame (for decoding) or input (for encoding).
AVFrame * requested_frame
AVFrame the codec passed to get_buffer()
pthread_cond_t output_cond
Used by the main thread to wait for frames to finish.
pthread_cond_t progress_cond
Used by child threads to wait for progress to change.
static void error(const char *err)
static void copy(const float *p1, float *p2, const int length)