1 /*
2 * This file is part of FFmpeg.
3 *
4 * FFmpeg is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * FFmpeg is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with FFmpeg; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18
19 /**
20 * @file
21 * Frame multithreading support functions
22 * @see doc/multithreading.txt
23 */
24
26
27 #include <stdatomic.h>
28 #include <stdint.h>
29
36
47
48 enum {
49 ///< Set when the thread is awaiting a packet.
51 ///< Set before the codec has called ff_thread_finish_setup().
53 /**
54 * Set when the codec calls get_buffer().
55 * State is returned to STATE_SETTING_UP afterwards.
56 */
58 /**
59 * Set when the codec calls get_format().
60 * State is returned to STATE_SETTING_UP afterwards.
61 */
63 ///< Set after the codec has called ff_thread_finish_setup().
65 };
66
67 /**
68 * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
69 */
72
78
81
83
84 AVPacket avpkt;
///< Input packet (for decoding) or output (for encoding).
85
86 AVFrame *
frame;
///< Output frame (for decoding) or input (for encoding).
87 int got_frame;
///< The output of got_picture_ptr from the last avcodec_decode_video() call.
88 int result;
///< The result of the last codec decode/encode() call.
89
91
92 /**
93 * Array of frames passed to ff_thread_release_buffer().
94 * Frames are released after all threads referencing them are finished.
95 */
99
102
105
106 int die;
///< Set when the thread should exit.
107
110
113
114 /**
115 * Context stored in the client AVCodecInternal thread_ctx.
116 */
120
122 /**
123 * This lock is used for ensuring threads run in serial when hwaccel
124 * is used.
125 */
130
133
135 * Set for the first N packets, where N is the number of threads.
136 * While it is set, ff_thread_en/decode_frame won't return any results.
137 */
139
140 #define THREAD_SAFE_CALLBACKS(avctx) \
141 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
142
144 {
150 }
151
153 {
159 }
160
161 /**
162 * Codec worker thread.
163 *
164 * Automatically calls ff_thread_finish_setup() if the codec does
165 * not provide an update_thread_context method, or if the codec returns
166 * before calling it.
167 */
169 {
173
175 while (1) {
178
180
183
184 /* If a decoder supports hwaccel, then it must call ff_get_format().
185 * Since that call must happen before ff_thread_finish_setup(), the
186 * decoder is required to implement update_thread_context() and call
187 * ff_thread_finish_setup() manually. Therefore the above
188 * ff_thread_finish_setup() call did not happen and hwaccel_serializing
189 * cannot be true here. */
191
192 /* if the previous thread uses hwaccel then we take the lock to ensure
193 * the threads don't run concurrently */
197 }
198
202
206 "free the frame on failure. This is a bug, please report it.\n");
208 }
209
212
216 }
217
220
222 }
223
225
227
231 }
233
235 }
236
237 /**
238 * Update the next thread's AVCodecContext with values from the reference thread's context.
239 *
240 * @param dst The destination context.
241 * @param src The source context.
242 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
243 * @return 0 on success, negative error code on failure
244 */
246 {
247 int err = 0;
248
256
259
262
265
268
272
277
280
286
290
295 }
296 }
297
299 }
300
301 if (for_user) {
303 #if FF_API_CODED_FRAME
307 #endif
308 } else {
311 }
312
313 return err;
314 }
315
316 /**
317 * Update the next thread's AVCodecContext with values set by the user.
318 *
319 * @param dst The destination context.
320 * @param src The source context.
321 * @return 0 on success, negative error code on failure
322 */
324 {
325 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
327
330
334
337
339
343
348 if (err < 0)
349 return err;
350 }
353 }
355 return 0;
356 #undef copy_fields
357 }
358
359 /// Releases the buffers that this decoding thread was the last user of.
361 {
363
366
368
369 // fix extended data in case the caller screwed it up
375
377 }
378 }
379
382 {
386 int ret;
387
389 return 0;
390
392
394 if (ret) {
396 return ret;
397 }
400 memory_order_relaxed);
401
403
404 if (prev_thread) {
405 int err;
411 }
412
414 if (err) {
416 return err;
417 }
418 }
419
422 if (ret < 0) {
425 return ret;
426 }
427
431
432 /*
433 * If the client doesn't have a thread-safe get_buffer(),
434 * then decoding threads call back to the main thread,
435 * and it calls back to the client here.
436 */
437
442 int call_done = 1;
446
450 break;
453 break;
454 default:
455 call_done = 0;
456 break;
457 }
458 if (call_done) {
461 }
463 }
464 }
465
468
469 return 0;
470 }
471
473 AVFrame *picture,
int *got_picture_ptr,
475 {
479 int err;
480
481 /* release the async lock, permitting blocked hwaccel threads to
482 * go forward while we are in this function */
484
485 /*
486 * Submit a packet to the next decoding thread.
487 */
488
491 if (err)
493
494 /*
495 * If we're still receiving the initial packets, don't return a frame.
496 */
497
500
502 *got_picture_ptr=0;
506 }
507 }
508
509 /*
510 * Return the next available frame from the oldest thread.
511 * If we're at the end of the stream, then we have to skip threads that
512 * didn't output a frame/error, because we don't want to accidentally signal
513 * EOF (avpkt->size == 0 && *got_picture_ptr == 0 && err >= 0).
514 */
515
516 do {
517 p = &fctx->
threads[finished++];
518
524 }
525
530
531 /*
532 * A later call with avkpt->size == 0 may loop over all threads,
533 * including this one, searching for a frame/error to return before being
534 * stopped by the "finished != fctx->next_finished" condition.
535 * Make sure we don't mistakenly return the same frame/error again.
536 */
539
541 }
while (!avpkt->
size && !*got_picture_ptr && err >= 0 && finished != fctx->
next_finished);
542
544
546
548
549 /* return the size of the consumed packet if no error occurred */
550 if (err >= 0)
554 return err;
555 }
556
558 {
561
564 return;
565
567
570 "%p finished %d field %d\n", progress, n, field);
571
573
575
578 }
579
581 {
584
587 return;
588
590
593 "thread awaiting %d field %d from %p\n", n, field, progress);
594
599 }
600
603
605
609 }
610
611 /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
615
617 }
618
622 }
623
625
628 }
629
630 /// Waits for all threads to finish.
632 {
633 int i;
634
636
637 for (i = 0; i < thread_count; i++) {
639
645 }
647 }
648
650 }
651
653 {
656 int i;
657
659
665 }
666
667 for (i = 0; i < thread_count; i++) {
669
674
678
681
684 }
685
686 for (i = 0; i < thread_count; i++) {
688
696
700 }
701
705 }
706
708 }
709
715
717
721 }
722
724 {
729 int i, err = 0;
730
731 if (!thread_count) {
733 #if FF_API_DEBUG_MV
734 if ((avctx->
debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->
debug_mv)
735 nb_cpus = 1;
736 #endif
737 // use number of cores + 1 as thread count if there is more than one
738 if (nb_cpus > 1)
740 else
742 }
743
744 if (thread_count <= 1) {
746 return 0;
747 }
748
750 if (!fctx)
752
757 }
758
763
766
767 for (i = 0; i < thread_count; i++) {
770
776
782 }
783
786
787 if (!copy) {
790 }
791
793
799 }
803
804 if (!i) {
806
808 err = codec->
init(copy);
809
811 } else {
816 }
819
822 }
823
825
827
832 }
833
834 return 0;
835
838
839 return err;
840 }
841
843 {
844 int i;
846
847 if (!fctx) return;
848
853 }
854
860 // Make sure decode flush calls with size=0 won't return old frames
864
866
869 }
870 }
871
873 {
877 return 0;
878 }
879 return 1;
880 }
881
883 {
885 int err;
886
888
891
894 av_log(avctx,
AV_LOG_ERROR,
"get_buffer() cannot be called after ff_thread_finish_setup()\n");
895 return -1;
896 }
897
903 }
905
908 }
909
914 } else {
920
923
925
927
928 }
931 if (err)
933
935
936 return err;
937 }
938
940 {
947 av_log(avctx,
AV_LOG_ERROR,
"get_format() cannot be called after ff_thread_finish_setup()\n");
948 return -1;
949 }
954
957
959
961
962 return res;
963 }
964
966 {
968 if (ret < 0)
970 return ret;
971 }
972
974 {
981
983 return;
984
987
990
991 if (can_direct_free) {
993 return;
994 }
995
998
1004 if (!tmp)
1007
1010
1012
1015 }
static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
int caps_internal
Internal hwaccel capabilities.
pthread_cond_t progress_cond
Used by child threads to wait for progress to change.
int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
Select the (possibly hardware accelerated) pixel format.
const struct AVCodec * codec
#define AV_CODEC_PROP_INTRA_ONLY
Codec uses only intra compression.
const AVCodecDescriptor * codec_descriptor
AVCodecDescriptor.
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
static void copy(const float *p1, float *p2, const int length)
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it...
#define copy_fields(s, e)
This structure describes decoded (raw) audio or video data.
#define pthread_mutex_lock(a)
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
#define atomic_store(object, desired)
Context used by codec threads and stored in their AVCodecInternal thread_ctx.
AVFrame * requested_frame
AVFrame the codec passed to get_buffer()
int coded_width
Bitstream width / height, may be different from width/height e.g.
void(* flush)(AVCodecContext *)
Flush buffers.
AVPacket * last_pkt_props
Properties (timestamps+side data) extracted from the last packet passed for decoding.
static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx, AVPacket *avpkt)
#define AV_LOG_WARNING
Something somehow does not look correct.
Memory handling functions.
AVBufferRef * buf[AV_NUM_DATA_POINTERS]
AVBuffer references backing the data for this frame.
enum AVColorRange color_range
MPEG vs JPEG YUV range.
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel...
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
void av_frame_move_ref(AVFrame *dst, AVFrame *src)
Move everything contained in src to dst and reset src.
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
int(* decode)(AVCodecContext *, void *outdata, int *outdata_size, AVPacket *avpkt)
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
pthread_cond_t input_cond
Used to wait for a new packet from the main thread.
void ff_thread_await_progress(ThreadFrame *f, int n, int field)
Wait for earlier decoding threads to finish reference pictures.
const struct AVHWAccel * hwaccel
Hardware accelerator in use.
enum AVPixelFormat * available_formats
Format array for get_format()
static av_always_inline int pthread_cond_destroy(pthread_cond_t *cond)
AVPacket avpkt
Input packet (for decoding) or output (for encoding).
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
#define av_assert0(cond)
assert() equivalent, that is always enabled.
int(* init_thread_copy)(AVCodecContext *)
If defined, called on thread contexts when they are created.
enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
enum AVSampleFormat sample_fmt
audio sample format
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
void * hwaccel_context
Hardware accelerator context.
static attribute_align_arg void * frame_worker_thread(void *arg)
Codec worker thread.
Multithreading support functions.
#define THREAD_SAFE_CALLBACKS(avctx)
pthread_mutex_t hwaccel_mutex
This lock is used for ensuring threads run in serial when hwaccel is used.
Set when the codec calls get_buffer().
int requested_flags
flags passed to get_buffer() for requested_frame
int next_decoding
The next context to submit a packet to.
static av_always_inline int pthread_cond_signal(pthread_cond_t *cond)
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
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...
enum AVChromaLocation chroma_sample_location
This defines the location of chroma samples.
Context stored in the client AVCodecInternal thread_ctx.
AVCodecContext * avctx
Context used to decode packets passed to this thread.
int av_packet_ref(AVPacket *dst, const AVPacket *src)
Setup a new reference to the data described by a given packet.
int die
Set when the thread should exit.
int ff_thread_decode_frame(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, AVPacket *avpkt)
Submit a new frame to a decoding thread.
int slice_count
slice count
Libavcodec version macros.
int(* close)(AVCodecContext *)
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
int has_b_frames
Size of the frame reordering buffer in the decoder.
PerThreadContext * prev_thread
The last thread submit_packet() was called on.
void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
Wrapper around release_buffer() frame-for multithreaded codecs.
#define atomic_load(object)
int is_copy
Whether the parent AVCodecContext is a copy of the context which had init() called on it...
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
int active_thread_type
Which multithreading methods are in use by the codec.
int capabilities
Codec capabilities.
int result
The result of the last codec decode/encode() call.
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
int flags
AV_CODEC_FLAG_*.
simple assert() macros that are a bit more flexible than ISO C assert().
reference-counted frame API
uint64_t channel_layout
Audio channel layout.
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
int props
Codec properties, a combination of AV_CODEC_PROP_* flags.
common internal API header
pthread_cond_t output_cond
Used by the main thread to wait for frames to finish.
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...
#define FF_THREAD_FRAME
Decode more than one frame at once.
int width
picture width / height.
int idct_algo
IDCT algorithm, see FF_IDCT_* below.
AVBufferRef * hw_frames_ctx
A reference to the AVHWFramesContext describing the input (for encoding) or output (decoding) frames...
void ff_thread_report_progress(ThreadFrame *f, int n, int field)
Notify later decoding threads when part of their reference picture is ready.
#define atomic_load_explicit(object, order)
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
static av_always_inline int pthread_join(pthread_t thread, void **value_ptr)
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given buffer if it is not large enough, otherwise do nothing.
int64_t reordered_opaque
opaque 64-bit number (generally a PTS) that will be reordered and output in AVFrame.reordered_opaque
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
#define pthread_mutex_unlock(a)
static void error(const char *err)
int thread_count
thread count is used to decide how many independent tasks should be passed to execute() ...
int got_frame
The output of got_picture_ptr from the last avcodec_decode_video() call.
static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
Update the next thread's AVCodecContext with values set by the user.
pthread_mutex_t buffer_mutex
Mutex used to protect get/release_buffer().
pthread_mutex_t progress_mutex
Mutex used to protect frame progress values and progress_cond.
static av_always_inline int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
pthread_cond_t async_cond
int avcodec_default_get_buffer2(AVCodecContext *s, AVFrame *frame, int flags)
The default callback for AVCodecContext.get_buffer2().
Libavcodec external API header.
enum AVMediaType codec_type
AVBufferRef * av_buffer_alloc(int size)
Allocate an AVBuffer of the given size using av_malloc().
int sample_rate
samples per second
int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
Wrapper around get_buffer() for frame-multithreaded codecs.
main external API structure.
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
uint8_t * data
The data buffer.
int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
Get a buffer for a frame.
int slice_flags
slice flags
AVCodecContext * owner[2]
enum AVPixelFormat(* get_format)(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
callback to negotiate the pixelFormat
enum AVColorSpace colorspace
YUV colorspace type.
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
enum AVPixelFormat result_format
get_format() result
int delaying
Set for the first N packets, where N is the number of threads.
refcounted data buffer API
enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
Wrapper around get_format() for frame-multithreaded codecs.
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.
#define atomic_store_explicit(object, desired, order)
static void async_unlock(FrameThreadContext *fctx)
PerThreadContext * threads
The contexts for each thread.
int allocate_progress
Whether to allocate progress for frame threading.
static void async_lock(FrameThreadContext *fctx)
AVFrame * released_buffers
Array of frames passed to ff_thread_release_buffer().
struct FrameThreadContext * parent
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Set when the thread is awaiting a packet.
const AVClass * priv_class
AVClass for the private context.
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
int64_t pkt_dts
DTS copied from the AVPacket that triggered returning this frame.
void av_opt_free(void *obj)
Free all allocated objects in obj.
#define FF_DISABLE_DEPRECATION_WARNINGS
common internal api header.
common internal and external API header
int released_buffers_allocated
void * hwaccel_priv_data
hwaccel-specific private data
AVBufferRef * av_buffer_ref(AVBufferRef *buf)
Create a new reference to an AVBuffer.
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.
static av_always_inline int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
attribute_deprecated AVFrame * coded_frame
the picture in the bitstream
int thread_safe_callbacks
Set by the client if its custom get_buffer() callback can be called synchronously from another thread...
#define HWACCEL_CAP_ASYNC_SAFE
int(* update_thread_context)(AVCodecContext *dst, const AVCodecContext *src)
Copy necessary context variables from a previous thread context to the current one.
void ff_thread_flush(AVCodecContext *avctx)
Wait for decoding threads to finish and reset internal state.
Set when the codec calls get_format().
AVFrame * frame
Output frame (for decoding) or input (for encoding).
int ff_thread_can_start_frame(AVCodecContext *avctx)
#define FF_ENABLE_DEPRECATION_WARNINGS
static av_always_inline int pthread_cond_broadcast(pthread_cond_t *cond)
int channels
number of audio channels
struct AVCodecInternal * internal
Private context used for internal data.
pthread_mutex_t mutex
Mutex used to protect the contents of the PerThreadContext.
int flags2
AV_CODEC_FLAG2_*.
static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
Waits for all threads to finish.
pthread_mutex_t async_mutex
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
int * slice_offset
slice offsets in the frame in bytes
int frame_number
Frame counter, set by libavcodec.
atomic_int debug_threads
Set if the FF_DEBUG_THREADS option is set.
static void release_delayed_buffers(PerThreadContext *p)
Releases the buffers that this decoding thread was the last user of.
#define atomic_init(obj, value)
int hwaccel_flags
Bit set of AV_HWACCEL_FLAG_* flags, which affect hardware accelerated decoding (if active)...
int debug_mv
debug motion vectors
int next_finished
The next context to return output from.
int(* init)(AVCodecContext *)
uint8_t ** extended_data
pointers to the data planes/channels.
AVPixelFormat
Pixel format.
This structure stores compressed data.
int ff_frame_thread_init(AVCodecContext *avctx)
enum AVPixelFormat sw_pix_fmt
Nominal unaccelerated pixel format, see AV_PIX_FMT_xxx.
void * opaque
Private data of the user, can be used to carry app specific stuff.
void * av_mallocz_array(size_t nmemb, size_t size)