2 * This file is part of FFmpeg.
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.
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.
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
21 * Frame multithreading support functions
22 * @see doc/multithreading.txt
27 #include <stdatomic.h>
33 #include "pthread_internal.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/buffer.h"
39 #include "libavutil/common.h"
40 #include "libavutil/cpu.h"
41 #include "libavutil/frame.h"
42 #include "libavutil/internal.h"
43 #include "libavutil/log.h"
44 #include "libavutil/mem.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/thread.h"
49 ///< Set when the thread is awaiting a packet.
51 ///< Set before the codec has called ff_thread_finish_setup().
54 * Set when the codec calls get_buffer().
55 * State is returned to STATE_SETTING_UP afterwards.
59 * Set when the codec calls get_format().
60 * State is returned to STATE_SETTING_UP afterwards.
63 ///< Set after the codec has called ff_thread_finish_setup().
68 UNINITIALIZED, ///< Thread has not been created, AVCodec->close mustn't be called
69 NEEDS_CLOSE, ///< AVCodec->close needs to be called
70 INITIALIZED, ///< Thread has been properly set up
74 * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
76 typedef struct PerThreadContext {
77 struct FrameThreadContext *parent;
81 unsigned pthread_init_cnt;///< Number of successfully initialized mutexes/conditions
82 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
83 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
84 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
86 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
87 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
89 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
91 AVPacket *avpkt; ///< Input packet (for decoding) or output (for encoding).
93 AVFrame *frame; ///< Output frame (for decoding) or input (for encoding).
94 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
95 int result; ///< The result of the last codec decode/encode() call.
99 #if FF_API_THREAD_SAFE_CALLBACKS
101 * Array of frames passed to ff_thread_release_buffer().
102 * Frames are released after all threads referencing them are finished.
104 AVFrame **released_buffers;
105 int num_released_buffers;
106 int released_buffers_allocated;
108 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
109 int requested_flags; ///< flags passed to get_buffer() for requested_frame
111 const enum AVPixelFormat *available_formats; ///< Format array for get_format()
112 enum AVPixelFormat result_format; ///< get_format() result
115 int die; ///< Set when the thread should exit.
117 int hwaccel_serializing;
118 int async_serializing;
120 atomic_int debug_threads; ///< Set if the FF_DEBUG_THREADS option is set.
124 * Context stored in the client AVCodecInternal thread_ctx.
126 typedef struct FrameThreadContext {
127 PerThreadContext *threads; ///< The contexts for each thread.
128 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
130 unsigned pthread_init_cnt; ///< Number of successfully initialized mutexes/conditions
131 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
133 * This lock is used for ensuring threads run in serial when hwaccel
136 pthread_mutex_t hwaccel_mutex;
137 pthread_mutex_t async_mutex;
138 pthread_cond_t async_cond;
141 int next_decoding; ///< The next context to submit a packet to.
142 int next_finished; ///< The next context to return output from.
145 * Set for the first N packets, where N is the number of threads.
146 * While it is set, ff_thread_en/decode_frame won't return any results.
148 } FrameThreadContext;
150 #if FF_API_THREAD_SAFE_CALLBACKS
151 #define THREAD_SAFE_CALLBACKS(avctx) \
152 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
155 static void async_lock(FrameThreadContext *fctx)
157 pthread_mutex_lock(&fctx->async_mutex);
158 while (fctx->async_lock)
159 pthread_cond_wait(&fctx->async_cond, &fctx->async_mutex);
160 fctx->async_lock = 1;
161 pthread_mutex_unlock(&fctx->async_mutex);
164 static void async_unlock(FrameThreadContext *fctx)
166 pthread_mutex_lock(&fctx->async_mutex);
167 av_assert0(fctx->async_lock);
168 fctx->async_lock = 0;
169 pthread_cond_broadcast(&fctx->async_cond);
170 pthread_mutex_unlock(&fctx->async_mutex);
174 * Codec worker thread.
176 * Automatically calls ff_thread_finish_setup() if the codec does
177 * not provide an update_thread_context method, or if the codec returns
180 static attribute_align_arg void *frame_worker_thread(void *arg)
182 PerThreadContext *p = arg;
183 AVCodecContext *avctx = p->avctx;
184 const AVCodec *codec = avctx->codec;
186 pthread_mutex_lock(&p->mutex);
188 while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
189 pthread_cond_wait(&p->input_cond, &p->mutex);
193 FF_DISABLE_DEPRECATION_WARNINGS
194 if (!codec->update_thread_context
195 #if FF_API_THREAD_SAFE_CALLBACKS
196 && THREAD_SAFE_CALLBACKS(avctx)
199 ff_thread_finish_setup(avctx);
200 FF_ENABLE_DEPRECATION_WARNINGS
202 /* If a decoder supports hwaccel, then it must call ff_get_format().
203 * Since that call must happen before ff_thread_finish_setup(), the
204 * decoder is required to implement update_thread_context() and call
205 * ff_thread_finish_setup() manually. Therefore the above
206 * ff_thread_finish_setup() call did not happen and hwaccel_serializing
207 * cannot be true here. */
208 av_assert0(!p->hwaccel_serializing);
210 /* if the previous thread uses hwaccel then we take the lock to ensure
211 * the threads don't run concurrently */
212 if (avctx->hwaccel) {
213 pthread_mutex_lock(&p->parent->hwaccel_mutex);
214 p->hwaccel_serializing = 1;
217 av_frame_unref(p->frame);
219 p->result = codec->decode(avctx, p->frame, &p->got_frame, p->avpkt);
221 if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
222 if (avctx->codec->caps_internal & FF_CODEC_CAP_ALLOCATE_PROGRESS)
223 av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
224 "free the frame on failure. This is a bug, please report it.\n");
225 av_frame_unref(p->frame);
228 if (atomic_load(&p->state) == STATE_SETTING_UP)
229 ff_thread_finish_setup(avctx);
231 if (p->hwaccel_serializing) {
232 p->hwaccel_serializing = 0;
233 pthread_mutex_unlock(&p->parent->hwaccel_mutex);
236 if (p->async_serializing) {
237 p->async_serializing = 0;
239 async_unlock(p->parent);
242 pthread_mutex_lock(&p->progress_mutex);
244 atomic_store(&p->state, STATE_INPUT_READY);
246 pthread_cond_broadcast(&p->progress_cond);
247 pthread_cond_signal(&p->output_cond);
248 pthread_mutex_unlock(&p->progress_mutex);
250 pthread_mutex_unlock(&p->mutex);
256 * Update the next thread's AVCodecContext with values from the reference thread's context.
258 * @param dst The destination context.
259 * @param src The source context.
260 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
261 * @return 0 on success, negative error code on failure
263 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
267 if (dst != src && (for_user || src->codec->update_thread_context)) {
268 dst->time_base = src->time_base;
269 dst->framerate = src->framerate;
270 dst->width = src->width;
271 dst->height = src->height;
272 dst->pix_fmt = src->pix_fmt;
273 dst->sw_pix_fmt = src->sw_pix_fmt;
275 dst->coded_width = src->coded_width;
276 dst->coded_height = src->coded_height;
278 dst->has_b_frames = src->has_b_frames;
279 dst->idct_algo = src->idct_algo;
281 dst->bits_per_coded_sample = src->bits_per_coded_sample;
282 dst->sample_aspect_ratio = src->sample_aspect_ratio;
284 dst->profile = src->profile;
285 dst->level = src->level;
287 dst->bits_per_raw_sample = src->bits_per_raw_sample;
288 dst->ticks_per_frame = src->ticks_per_frame;
289 dst->color_primaries = src->color_primaries;
291 dst->color_trc = src->color_trc;
292 dst->colorspace = src->colorspace;
293 dst->color_range = src->color_range;
294 dst->chroma_sample_location = src->chroma_sample_location;
296 dst->hwaccel = src->hwaccel;
297 dst->hwaccel_context = src->hwaccel_context;
299 dst->channels = src->channels;
300 dst->sample_rate = src->sample_rate;
301 dst->sample_fmt = src->sample_fmt;
302 dst->channel_layout = src->channel_layout;
303 dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
305 if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
306 (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
307 av_buffer_unref(&dst->hw_frames_ctx);
309 if (src->hw_frames_ctx) {
310 dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
311 if (!dst->hw_frames_ctx)
312 return AVERROR(ENOMEM);
316 dst->hwaccel_flags = src->hwaccel_flags;
318 err = av_buffer_replace(&dst->internal->pool, src->internal->pool);
324 #if FF_API_CODED_FRAME
325 FF_DISABLE_DEPRECATION_WARNINGS
326 dst->coded_frame = src->coded_frame;
327 FF_ENABLE_DEPRECATION_WARNINGS
330 if (dst->codec->update_thread_context)
331 err = dst->codec->update_thread_context(dst, src);
338 * Update the next thread's AVCodecContext with values set by the user.
340 * @param dst The destination context.
341 * @param src The source context.
342 * @return 0 on success, negative error code on failure
344 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
346 dst->flags = src->flags;
348 dst->draw_horiz_band= src->draw_horiz_band;
349 dst->get_buffer2 = src->get_buffer2;
351 dst->opaque = src->opaque;
352 dst->debug = src->debug;
354 dst->slice_flags = src->slice_flags;
355 dst->flags2 = src->flags2;
356 dst->export_side_data = src->export_side_data;
358 dst->skip_loop_filter = src->skip_loop_filter;
359 dst->skip_idct = src->skip_idct;
360 dst->skip_frame = src->skip_frame;
362 dst->frame_number = src->frame_number;
363 dst->reordered_opaque = src->reordered_opaque;
364 #if FF_API_THREAD_SAFE_CALLBACKS
365 FF_DISABLE_DEPRECATION_WARNINGS
366 dst->thread_safe_callbacks = src->thread_safe_callbacks;
367 FF_ENABLE_DEPRECATION_WARNINGS
370 if (src->slice_count && src->slice_offset) {
371 if (dst->slice_count < src->slice_count) {
372 int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
373 sizeof(*dst->slice_offset));
377 memcpy(dst->slice_offset, src->slice_offset,
378 src->slice_count * sizeof(*dst->slice_offset));
380 dst->slice_count = src->slice_count;
384 #if FF_API_THREAD_SAFE_CALLBACKS
385 /// Releases the buffers that this decoding thread was the last user of.
386 static void release_delayed_buffers(PerThreadContext *p)
388 FrameThreadContext *fctx = p->parent;
390 while (p->num_released_buffers > 0) {
393 pthread_mutex_lock(&fctx->buffer_mutex);
395 // fix extended data in case the caller screwed it up
396 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
397 p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
398 f = p->released_buffers[--p->num_released_buffers];
399 f->extended_data = f->data;
402 pthread_mutex_unlock(&fctx->buffer_mutex);
407 static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx,
410 FrameThreadContext *fctx = p->parent;
411 PerThreadContext *prev_thread = fctx->prev_thread;
412 const AVCodec *codec = p->avctx->codec;
415 if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
418 pthread_mutex_lock(&p->mutex);
420 ret = update_context_from_user(p->avctx, user_avctx);
422 pthread_mutex_unlock(&p->mutex);
425 atomic_store_explicit(&p->debug_threads,
426 (p->avctx->debug & FF_DEBUG_THREADS) != 0,
427 memory_order_relaxed);
429 #if FF_API_THREAD_SAFE_CALLBACKS
430 release_delayed_buffers(p);
435 if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
436 pthread_mutex_lock(&prev_thread->progress_mutex);
437 while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
438 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
439 pthread_mutex_unlock(&prev_thread->progress_mutex);
442 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
444 pthread_mutex_unlock(&p->mutex);
449 av_packet_unref(p->avpkt);
450 ret = av_packet_ref(p->avpkt, avpkt);
452 pthread_mutex_unlock(&p->mutex);
453 av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
457 atomic_store(&p->state, STATE_SETTING_UP);
458 pthread_cond_signal(&p->input_cond);
459 pthread_mutex_unlock(&p->mutex);
461 #if FF_API_THREAD_SAFE_CALLBACKS
462 FF_DISABLE_DEPRECATION_WARNINGS
464 * If the client doesn't have a thread-safe get_buffer(),
465 * then decoding threads call back to the main thread,
466 * and it calls back to the client here.
469 if (!p->avctx->thread_safe_callbacks && (
470 p->avctx->get_format != avcodec_default_get_format ||
471 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
472 while (atomic_load(&p->state) != STATE_SETUP_FINISHED && atomic_load(&p->state) != STATE_INPUT_READY) {
474 pthread_mutex_lock(&p->progress_mutex);
475 while (atomic_load(&p->state) == STATE_SETTING_UP)
476 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
478 switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
479 case STATE_GET_BUFFER:
480 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
482 case STATE_GET_FORMAT:
483 p->result_format = ff_get_format(p->avctx, p->available_formats);
490 atomic_store(&p->state, STATE_SETTING_UP);
491 pthread_cond_signal(&p->progress_cond);
493 pthread_mutex_unlock(&p->progress_mutex);
496 FF_ENABLE_DEPRECATION_WARNINGS
499 fctx->prev_thread = p;
500 fctx->next_decoding++;
505 int ff_thread_decode_frame(AVCodecContext *avctx,
506 AVFrame *picture, int *got_picture_ptr,
509 FrameThreadContext *fctx = avctx->internal->thread_ctx;
510 int finished = fctx->next_finished;
514 /* release the async lock, permitting blocked hwaccel threads to
515 * go forward while we are in this function */
519 * Submit a packet to the next decoding thread.
522 p = &fctx->threads[fctx->next_decoding];
523 err = submit_packet(p, avctx, avpkt);
528 * If we're still receiving the initial packets, don't return a frame.
531 if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
534 if (fctx->delaying) {
543 * Return the next available frame from the oldest thread.
544 * If we're at the end of the stream, then we have to skip threads that
545 * didn't output a frame/error, because we don't want to accidentally signal
546 * EOF (avpkt->size == 0 && *got_picture_ptr == 0 && err >= 0).
550 p = &fctx->threads[finished++];
552 if (atomic_load(&p->state) != STATE_INPUT_READY) {
553 pthread_mutex_lock(&p->progress_mutex);
554 while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
555 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
556 pthread_mutex_unlock(&p->progress_mutex);
559 av_frame_move_ref(picture, p->frame);
560 *got_picture_ptr = p->got_frame;
561 picture->pkt_dts = p->avpkt->dts;
565 * A later call with avkpt->size == 0 may loop over all threads,
566 * including this one, searching for a frame/error to return before being
567 * stopped by the "finished != fctx->next_finished" condition.
568 * Make sure we don't mistakenly return the same frame/error again.
573 if (finished >= avctx->thread_count) finished = 0;
574 } while (!avpkt->size && !*got_picture_ptr && err >= 0 && finished != fctx->next_finished);
576 update_context_from_thread(avctx, p->avctx, 1);
578 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
580 fctx->next_finished = finished;
582 /* return the size of the consumed packet if no error occurred */
590 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
593 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
596 atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
599 p = f->owner[field]->internal->thread_ctx;
601 if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
602 av_log(f->owner[field], AV_LOG_DEBUG,
603 "%p finished %d field %d\n", progress, n, field);
605 pthread_mutex_lock(&p->progress_mutex);
607 atomic_store_explicit(&progress[field], n, memory_order_release);
609 pthread_cond_broadcast(&p->progress_cond);
610 pthread_mutex_unlock(&p->progress_mutex);
613 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
616 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
619 atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
622 p = f->owner[field]->internal->thread_ctx;
624 if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
625 av_log(f->owner[field], AV_LOG_DEBUG,
626 "thread awaiting %d field %d from %p\n", n, field, progress);
628 pthread_mutex_lock(&p->progress_mutex);
629 while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
630 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
631 pthread_mutex_unlock(&p->progress_mutex);
634 void ff_thread_finish_setup(AVCodecContext *avctx) {
635 PerThreadContext *p = avctx->internal->thread_ctx;
637 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
639 if (avctx->hwaccel && !p->hwaccel_serializing) {
640 pthread_mutex_lock(&p->parent->hwaccel_mutex);
641 p->hwaccel_serializing = 1;
644 /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
645 if (avctx->hwaccel &&
646 !(avctx->hwaccel->caps_internal & HWACCEL_CAP_ASYNC_SAFE)) {
647 p->async_serializing = 1;
649 async_lock(p->parent);
652 pthread_mutex_lock(&p->progress_mutex);
653 if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
654 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
657 atomic_store(&p->state, STATE_SETUP_FINISHED);
659 pthread_cond_broadcast(&p->progress_cond);
660 pthread_mutex_unlock(&p->progress_mutex);
663 /// Waits for all threads to finish.
664 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
670 for (i = 0; i < thread_count; i++) {
671 PerThreadContext *p = &fctx->threads[i];
673 if (atomic_load(&p->state) != STATE_INPUT_READY) {
674 pthread_mutex_lock(&p->progress_mutex);
675 while (atomic_load(&p->state) != STATE_INPUT_READY)
676 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
677 pthread_mutex_unlock(&p->progress_mutex);
685 #define SENTINEL 0 // This forbids putting a mutex/condition variable at the front.
686 #define OFFSET_ARRAY(...) __VA_ARGS__, SENTINEL
687 #define DEFINE_OFFSET_ARRAY(type, name, mutexes, conds) \
688 static const unsigned name ## _offsets[] = { offsetof(type, pthread_init_cnt),\
689 OFFSET_ARRAY mutexes, \
692 #define OFF(member) offsetof(FrameThreadContext, member)
693 DEFINE_OFFSET_ARRAY(FrameThreadContext, thread_ctx,
694 (OFF(buffer_mutex), OFF(hwaccel_mutex), OFF(async_mutex)),
698 #define OFF(member) offsetof(PerThreadContext, member)
699 DEFINE_OFFSET_ARRAY(PerThreadContext, per_thread,
700 (OFF(progress_mutex), OFF(mutex)),
701 (OFF(input_cond), OFF(progress_cond), OFF(output_cond)));
704 static av_cold void free_pthread(void *obj, const unsigned offsets[])
706 unsigned cnt = *(unsigned*)((char*)obj + offsets[0]);
707 const unsigned *cur_offset = offsets;
709 for (; *(++cur_offset) != SENTINEL && cnt; cnt--)
710 pthread_mutex_destroy((pthread_mutex_t*)((char*)obj + *cur_offset));
711 for (; *(++cur_offset) != SENTINEL && cnt; cnt--)
712 pthread_cond_destroy ((pthread_cond_t *)((char*)obj + *cur_offset));
715 static av_cold int init_pthread(void *obj, const unsigned offsets[])
717 const unsigned *cur_offset = offsets;
721 #define PTHREAD_INIT_LOOP(type) \
722 for (; *(++cur_offset) != SENTINEL; cnt++) { \
723 pthread_ ## type ## _t *dst = (void*)((char*)obj + *cur_offset); \
724 err = pthread_ ## type ## _init(dst, NULL); \
726 err = AVERROR(err); \
730 PTHREAD_INIT_LOOP(mutex)
731 PTHREAD_INIT_LOOP(cond)
734 *(unsigned*)((char*)obj + offsets[0]) = cnt;
738 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
740 FrameThreadContext *fctx = avctx->internal->thread_ctx;
741 const AVCodec *codec = avctx->codec;
744 park_frame_worker_threads(fctx, thread_count);
746 if (fctx->prev_thread && avctx->internal->hwaccel_priv_data !=
747 fctx->prev_thread->avctx->internal->hwaccel_priv_data) {
748 if (update_context_from_thread(avctx, fctx->prev_thread->avctx, 1) < 0) {
749 av_log(avctx, AV_LOG_ERROR, "Failed to update user thread.\n");
753 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
754 if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
755 av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
756 fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
757 fctx->threads->avctx->internal->is_copy = 1;
760 for (i = 0; i < thread_count; i++) {
761 PerThreadContext *p = &fctx->threads[i];
762 AVCodecContext *ctx = p->avctx;
765 if (p->thread_init == INITIALIZED) {
766 pthread_mutex_lock(&p->mutex);
768 pthread_cond_signal(&p->input_cond);
769 pthread_mutex_unlock(&p->mutex);
771 pthread_join(p->thread, NULL);
773 if (codec->close && p->thread_init != UNINITIALIZED)
776 #if FF_API_THREAD_SAFE_CALLBACKS
777 release_delayed_buffers(p);
778 for (int j = 0; j < p->released_buffers_allocated; j++)
779 av_frame_free(&p->released_buffers[j]);
780 av_freep(&p->released_buffers);
782 if (ctx->priv_data) {
783 if (codec->priv_class)
784 av_opt_free(ctx->priv_data);
785 av_freep(&ctx->priv_data);
788 av_freep(&ctx->slice_offset);
790 av_buffer_unref(&ctx->internal->pool);
791 av_freep(&ctx->internal);
792 av_buffer_unref(&ctx->hw_frames_ctx);
795 av_frame_free(&p->frame);
797 free_pthread(p, per_thread_offsets);
798 av_packet_free(&p->avpkt);
803 av_freep(&fctx->threads);
804 free_pthread(fctx, thread_ctx_offsets);
806 av_freep(&avctx->internal->thread_ctx);
808 if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
809 av_opt_free(avctx->priv_data);
813 static av_cold int init_thread(PerThreadContext *p, int *threads_to_free,
814 FrameThreadContext *fctx, AVCodecContext *avctx,
815 AVCodecContext *src, const AVCodec *codec, int first)
817 AVCodecContext *copy;
820 atomic_init(&p->state, STATE_INPUT_READY);
822 copy = av_memdup(src, sizeof(*src));
824 return AVERROR(ENOMEM);
825 copy->priv_data = NULL;
827 /* From now on, this PerThreadContext will be cleaned up by
828 * ff_frame_thread_free in case of errors. */
829 (*threads_to_free)++;
834 copy->internal = av_memdup(src->internal, sizeof(*src->internal));
836 return AVERROR(ENOMEM);
837 copy->internal->thread_ctx = p;
839 copy->delay = avctx->delay;
841 if (codec->priv_data_size) {
842 copy->priv_data = av_mallocz(codec->priv_data_size);
843 if (!copy->priv_data)
844 return AVERROR(ENOMEM);
846 if (codec->priv_class) {
847 *(const AVClass **)copy->priv_data = codec->priv_class;
848 err = av_opt_copy(copy->priv_data, src->priv_data);
854 err = init_pthread(p, per_thread_offsets);
858 if (!(p->frame = av_frame_alloc()) ||
859 !(p->avpkt = av_packet_alloc()))
860 return AVERROR(ENOMEM);
861 copy->internal->last_pkt_props = p->avpkt;
864 copy->internal->is_copy = 1;
867 err = codec->init(copy);
869 if (codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP)
870 p->thread_init = NEEDS_CLOSE;
874 p->thread_init = NEEDS_CLOSE;
877 update_context_from_thread(avctx, copy, 1);
879 atomic_init(&p->debug_threads, (copy->debug & FF_DEBUG_THREADS) != 0);
881 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
884 p->thread_init = INITIALIZED;
889 int ff_frame_thread_init(AVCodecContext *avctx)
891 int thread_count = avctx->thread_count;
892 const AVCodec *codec = avctx->codec;
893 AVCodecContext *src = avctx;
894 FrameThreadContext *fctx;
898 int nb_cpus = av_cpu_count();
899 // use number of cores + 1 as thread count if there is more than one
901 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
903 thread_count = avctx->thread_count = 1;
906 if (thread_count <= 1) {
907 avctx->active_thread_type = 0;
911 avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
913 return AVERROR(ENOMEM);
915 err = init_pthread(fctx, thread_ctx_offsets);
917 free_pthread(fctx, thread_ctx_offsets);
918 av_freep(&avctx->internal->thread_ctx);
922 fctx->async_lock = 1;
925 if (codec->type == AVMEDIA_TYPE_VIDEO)
926 avctx->delay = src->thread_count - 1;
928 fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
929 if (!fctx->threads) {
930 err = AVERROR(ENOMEM);
934 for (; i < thread_count; ) {
935 PerThreadContext *p = &fctx->threads[i];
938 err = init_thread(p, &i, fctx, avctx, src, codec, first);
946 ff_frame_thread_free(avctx, i);
950 void ff_thread_flush(AVCodecContext *avctx)
953 FrameThreadContext *fctx = avctx->internal->thread_ctx;
957 park_frame_worker_threads(fctx, avctx->thread_count);
958 if (fctx->prev_thread) {
959 if (fctx->prev_thread != &fctx->threads[0])
960 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
963 fctx->next_decoding = fctx->next_finished = 0;
965 fctx->prev_thread = NULL;
966 for (i = 0; i < avctx->thread_count; i++) {
967 PerThreadContext *p = &fctx->threads[i];
968 // Make sure decode flush calls with size=0 won't return old frames
970 av_frame_unref(p->frame);
973 #if FF_API_THREAD_SAFE_CALLBACKS
974 release_delayed_buffers(p);
977 if (avctx->codec->flush)
978 avctx->codec->flush(p->avctx);
982 int ff_thread_can_start_frame(AVCodecContext *avctx)
984 PerThreadContext *p = avctx->internal->thread_ctx;
985 FF_DISABLE_DEPRECATION_WARNINGS
986 if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
987 (avctx->codec->update_thread_context
988 #if FF_API_THREAD_SAFE_CALLBACKS
989 || !THREAD_SAFE_CALLBACKS(avctx)
994 FF_ENABLE_DEPRECATION_WARNINGS
998 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
1000 PerThreadContext *p = avctx->internal->thread_ctx;
1003 f->owner[0] = f->owner[1] = avctx;
1005 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
1006 return ff_get_buffer(avctx, f->f, flags);
1008 FF_DISABLE_DEPRECATION_WARNINGS
1009 if (atomic_load(&p->state) != STATE_SETTING_UP &&
1010 (avctx->codec->update_thread_context
1011 #if FF_API_THREAD_SAFE_CALLBACKS
1012 || !THREAD_SAFE_CALLBACKS(avctx)
1015 FF_ENABLE_DEPRECATION_WARNINGS
1016 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
1020 if (avctx->codec->caps_internal & FF_CODEC_CAP_ALLOCATE_PROGRESS) {
1021 atomic_int *progress;
1022 f->progress = av_buffer_alloc(2 * sizeof(*progress));
1024 return AVERROR(ENOMEM);
1026 progress = (atomic_int*)f->progress->data;
1028 atomic_init(&progress[0], -1);
1029 atomic_init(&progress[1], -1);
1032 pthread_mutex_lock(&p->parent->buffer_mutex);
1033 #if !FF_API_THREAD_SAFE_CALLBACKS
1034 err = ff_get_buffer(avctx, f->f, flags);
1036 FF_DISABLE_DEPRECATION_WARNINGS
1037 if (THREAD_SAFE_CALLBACKS(avctx)) {
1038 err = ff_get_buffer(avctx, f->f, flags);
1040 pthread_mutex_lock(&p->progress_mutex);
1041 p->requested_frame = f->f;
1042 p->requested_flags = flags;
1043 atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
1044 pthread_cond_broadcast(&p->progress_cond);
1046 while (atomic_load(&p->state) != STATE_SETTING_UP)
1047 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
1051 pthread_mutex_unlock(&p->progress_mutex);
1054 if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
1055 ff_thread_finish_setup(avctx);
1056 FF_ENABLE_DEPRECATION_WARNINGS
1059 av_buffer_unref(&f->progress);
1061 pthread_mutex_unlock(&p->parent->buffer_mutex);
1066 #if FF_API_THREAD_SAFE_CALLBACKS
1067 FF_DISABLE_DEPRECATION_WARNINGS
1068 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1070 enum AVPixelFormat res;
1071 PerThreadContext *p = avctx->internal->thread_ctx;
1072 if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
1073 avctx->get_format == avcodec_default_get_format)
1074 return ff_get_format(avctx, fmt);
1075 if (atomic_load(&p->state) != STATE_SETTING_UP) {
1076 av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
1079 pthread_mutex_lock(&p->progress_mutex);
1080 p->available_formats = fmt;
1081 atomic_store(&p->state, STATE_GET_FORMAT);
1082 pthread_cond_broadcast(&p->progress_cond);
1084 while (atomic_load(&p->state) != STATE_SETTING_UP)
1085 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
1087 res = p->result_format;
1089 pthread_mutex_unlock(&p->progress_mutex);
1093 FF_ENABLE_DEPRECATION_WARNINGS
1096 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1098 int ret = thread_get_buffer_internal(avctx, f, flags);
1100 av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1104 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1106 #if FF_API_THREAD_SAFE_CALLBACKS
1107 FF_DISABLE_DEPRECATION_WARNINGS
1108 PerThreadContext *p = avctx->internal->thread_ctx;
1109 FrameThreadContext *fctx;
1112 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1113 THREAD_SAFE_CALLBACKS(avctx);
1114 FF_ENABLE_DEPRECATION_WARNINGS
1120 if (avctx->debug & FF_DEBUG_BUFFERS)
1121 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1123 av_buffer_unref(&f->progress);
1124 f->owner[0] = f->owner[1] = NULL;
1126 #if !FF_API_THREAD_SAFE_CALLBACKS
1127 av_frame_unref(f->f);
1129 // when the frame buffers are not allocated, just reset it to clean state
1130 if (can_direct_free || !f->f->buf[0]) {
1131 av_frame_unref(f->f);
1136 pthread_mutex_lock(&fctx->buffer_mutex);
1138 if (p->num_released_buffers == p->released_buffers_allocated) {
1139 AVFrame **tmp = av_realloc_array(p->released_buffers, p->released_buffers_allocated + 1,
1140 sizeof(*p->released_buffers));
1142 tmp[p->released_buffers_allocated] = av_frame_alloc();
1143 p->released_buffers = tmp;
1146 if (!tmp || !tmp[p->released_buffers_allocated]) {
1147 ret = AVERROR(ENOMEM);
1150 p->released_buffers_allocated++;
1153 dst = p->released_buffers[p->num_released_buffers];
1154 av_frame_move_ref(dst, f->f);
1156 p->num_released_buffers++;
1159 pthread_mutex_unlock(&fctx->buffer_mutex);
1161 // make sure the frame is clean even if we fail to free it
1162 // this leaks, but it is better than crashing
1164 av_log(avctx, AV_LOG_ERROR, "Could not queue a frame for freeing, this will leak\n");
1165 memset(f->f->buf, 0, sizeof(f->f->buf));
1166 if (f->f->extended_buf)
1167 memset(f->f->extended_buf, 0, f->f->nb_extended_buf * sizeof(*f->f->extended_buf));
1168 av_frame_unref(f->f);