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>
32 #include "pthread_internal.h"
36 #include "libavutil/avassert.h"
37 #include "libavutil/buffer.h"
38 #include "libavutil/common.h"
39 #include "libavutil/cpu.h"
40 #include "libavutil/frame.h"
41 #include "libavutil/internal.h"
42 #include "libavutil/log.h"
43 #include "libavutil/mem.h"
44 #include "libavutil/opt.h"
45 #include "libavutil/thread.h"
48 ///< Set when the thread is awaiting a packet.
50 ///< Set before the codec has called ff_thread_finish_setup().
53 * Set when the codec calls get_buffer().
54 * State is returned to STATE_SETTING_UP afterwards.
58 * Set when the codec calls get_format().
59 * State is returned to STATE_SETTING_UP afterwards.
62 ///< Set after the codec has called ff_thread_finish_setup().
67 * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
69 typedef struct PerThreadContext {
70 struct FrameThreadContext *parent;
74 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
75 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
76 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
78 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
79 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
81 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
83 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
85 AVFrame *frame; ///< Output frame (for decoding) or input (for encoding).
86 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
87 int result; ///< The result of the last codec decode/encode() call.
92 * Array of frames passed to ff_thread_release_buffer().
93 * Frames are released after all threads referencing them are finished.
95 AVFrame *released_buffers;
96 int num_released_buffers;
97 int released_buffers_allocated;
99 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
100 int requested_flags; ///< flags passed to get_buffer() for requested_frame
102 const enum AVPixelFormat *available_formats; ///< Format array for get_format()
103 enum AVPixelFormat result_format; ///< get_format() result
105 int die; ///< Set when the thread should exit.
107 int hwaccel_serializing;
111 * Context stored in the client AVCodecInternal thread_ctx.
113 typedef struct FrameThreadContext {
114 PerThreadContext *threads; ///< The contexts for each thread.
115 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
117 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
119 * This lock is used for ensuring threads run in serial when hwaccel
122 pthread_mutex_t hwaccel_mutex;
124 int next_decoding; ///< The next context to submit a packet to.
125 int next_finished; ///< The next context to return output from.
128 * Set for the first N packets, where N is the number of threads.
129 * While it is set, ff_thread_en/decode_frame won't return any results.
131 } FrameThreadContext;
133 #define THREAD_SAFE_CALLBACKS(avctx) \
134 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
137 * Codec worker thread.
139 * Automatically calls ff_thread_finish_setup() if the codec does
140 * not provide an update_thread_context method, or if the codec returns
143 static attribute_align_arg void *frame_worker_thread(void *arg)
145 PerThreadContext *p = arg;
146 AVCodecContext *avctx = p->avctx;
147 const AVCodec *codec = avctx->codec;
149 pthread_mutex_lock(&p->mutex);
151 while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
152 pthread_cond_wait(&p->input_cond, &p->mutex);
156 if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
157 ff_thread_finish_setup(avctx);
159 /* If a decoder supports hwaccel, then it must call ff_get_format().
160 * Since that call must happen before ff_thread_finish_setup(), the
161 * decoder is required to implement update_thread_context() and call
162 * ff_thread_finish_setup() manually. Therefore the above
163 * ff_thread_finish_setup() call did not happen and hwaccel_serializing
164 * cannot be true here. */
165 av_assert0(!p->hwaccel_serializing);
167 /* if the previous thread uses hwaccel then we take the lock to ensure
168 * the threads don't run concurrently */
169 if (avctx->hwaccel) {
170 pthread_mutex_lock(&p->parent->hwaccel_mutex);
171 p->hwaccel_serializing = 1;
174 av_frame_unref(p->frame);
176 p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
178 if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
179 if (avctx->internal->allocate_progress)
180 av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
181 "free the frame on failure. This is a bug, please report it.\n");
182 av_frame_unref(p->frame);
185 if (atomic_load(&p->state) == STATE_SETTING_UP)
186 ff_thread_finish_setup(avctx);
188 if (p->hwaccel_serializing) {
189 p->hwaccel_serializing = 0;
190 pthread_mutex_unlock(&p->parent->hwaccel_mutex);
193 pthread_mutex_lock(&p->progress_mutex);
195 for (i = 0; i < MAX_BUFFERS; i++)
196 if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
197 p->progress[i][0] = INT_MAX;
198 p->progress[i][1] = INT_MAX;
201 atomic_store(&p->state, STATE_INPUT_READY);
203 pthread_cond_broadcast(&p->progress_cond);
204 pthread_cond_signal(&p->output_cond);
205 pthread_mutex_unlock(&p->progress_mutex);
207 pthread_mutex_unlock(&p->mutex);
213 * Update the next thread's AVCodecContext with values from the reference thread's context.
215 * @param dst The destination context.
216 * @param src The source context.
217 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
218 * @return 0 on success, negative error code on failure
220 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
225 dst->time_base = src->time_base;
226 dst->framerate = src->framerate;
227 dst->width = src->width;
228 dst->height = src->height;
229 dst->pix_fmt = src->pix_fmt;
231 dst->coded_width = src->coded_width;
232 dst->coded_height = src->coded_height;
234 dst->has_b_frames = src->has_b_frames;
235 dst->idct_algo = src->idct_algo;
237 dst->bits_per_coded_sample = src->bits_per_coded_sample;
238 dst->sample_aspect_ratio = src->sample_aspect_ratio;
240 FF_DISABLE_DEPRECATION_WARNINGS
241 dst->dtg_active_format = src->dtg_active_format;
242 FF_ENABLE_DEPRECATION_WARNINGS
243 #endif /* FF_API_AFD */
245 dst->profile = src->profile;
246 dst->level = src->level;
248 dst->bits_per_raw_sample = src->bits_per_raw_sample;
249 dst->ticks_per_frame = src->ticks_per_frame;
250 dst->color_primaries = src->color_primaries;
252 dst->color_trc = src->color_trc;
253 dst->colorspace = src->colorspace;
254 dst->color_range = src->color_range;
255 dst->chroma_sample_location = src->chroma_sample_location;
257 dst->hwaccel = src->hwaccel;
258 dst->hwaccel_context = src->hwaccel_context;
260 dst->channels = src->channels;
261 dst->sample_rate = src->sample_rate;
262 dst->sample_fmt = src->sample_fmt;
263 dst->channel_layout = src->channel_layout;
264 dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
266 if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
267 (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
268 av_buffer_unref(&dst->hw_frames_ctx);
270 if (src->hw_frames_ctx) {
271 dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
272 if (!dst->hw_frames_ctx)
273 return AVERROR(ENOMEM);
279 dst->delay = src->thread_count - 1;
280 #if FF_API_CODED_FRAME
281 FF_DISABLE_DEPRECATION_WARNINGS
282 dst->coded_frame = src->coded_frame;
283 FF_ENABLE_DEPRECATION_WARNINGS
286 if (dst->codec->update_thread_context)
287 err = dst->codec->update_thread_context(dst, src);
294 * Update the next thread's AVCodecContext with values set by the user.
296 * @param dst The destination context.
297 * @param src The source context.
298 * @return 0 on success, negative error code on failure
300 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
302 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
303 dst->flags = src->flags;
305 dst->draw_horiz_band= src->draw_horiz_band;
306 dst->get_buffer2 = src->get_buffer2;
308 dst->opaque = src->opaque;
309 dst->debug = src->debug;
310 dst->debug_mv = src->debug_mv;
312 dst->slice_flags = src->slice_flags;
313 dst->flags2 = src->flags2;
315 copy_fields(skip_loop_filter, subtitle_header);
317 dst->frame_number = src->frame_number;
318 dst->reordered_opaque = src->reordered_opaque;
319 dst->thread_safe_callbacks = src->thread_safe_callbacks;
321 if (src->slice_count && src->slice_offset) {
322 if (dst->slice_count < src->slice_count) {
323 int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
324 sizeof(*dst->slice_offset));
328 memcpy(dst->slice_offset, src->slice_offset,
329 src->slice_count * sizeof(*dst->slice_offset));
331 dst->slice_count = src->slice_count;
336 /// Releases the buffers that this decoding thread was the last user of.
337 static void release_delayed_buffers(PerThreadContext *p)
339 FrameThreadContext *fctx = p->parent;
341 while (p->num_released_buffers > 0) {
344 pthread_mutex_lock(&fctx->buffer_mutex);
346 // fix extended data in case the caller screwed it up
347 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
348 p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
349 f = &p->released_buffers[--p->num_released_buffers];
350 f->extended_data = f->data;
353 pthread_mutex_unlock(&fctx->buffer_mutex);
357 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
359 FrameThreadContext *fctx = p->parent;
360 PerThreadContext *prev_thread = fctx->prev_thread;
361 const AVCodec *codec = p->avctx->codec;
364 if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
367 pthread_mutex_lock(&p->mutex);
369 release_delayed_buffers(p);
373 if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
374 pthread_mutex_lock(&prev_thread->progress_mutex);
375 while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
376 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
377 pthread_mutex_unlock(&prev_thread->progress_mutex);
380 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
382 pthread_mutex_unlock(&p->mutex);
387 av_packet_unref(&p->avpkt);
388 ret = av_packet_ref(&p->avpkt, avpkt);
390 pthread_mutex_unlock(&p->mutex);
391 av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
395 atomic_store(&p->state, STATE_SETTING_UP);
396 pthread_cond_signal(&p->input_cond);
397 pthread_mutex_unlock(&p->mutex);
400 * If the client doesn't have a thread-safe get_buffer(),
401 * then decoding threads call back to the main thread,
402 * and it calls back to the client here.
405 if (!p->avctx->thread_safe_callbacks && (
406 p->avctx->get_format != avcodec_default_get_format ||
407 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
408 while (atomic_load(&p->state) != STATE_SETUP_FINISHED && atomic_load(&p->state) != STATE_INPUT_READY) {
410 pthread_mutex_lock(&p->progress_mutex);
411 while (atomic_load(&p->state) == STATE_SETTING_UP)
412 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
414 switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
415 case STATE_GET_BUFFER:
416 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
418 case STATE_GET_FORMAT:
419 p->result_format = ff_get_format(p->avctx, p->available_formats);
426 atomic_store(&p->state, STATE_SETTING_UP);
427 pthread_cond_signal(&p->progress_cond);
429 pthread_mutex_unlock(&p->progress_mutex);
433 fctx->prev_thread = p;
434 fctx->next_decoding++;
439 int ff_thread_decode_frame(AVCodecContext *avctx,
440 AVFrame *picture, int *got_picture_ptr,
443 FrameThreadContext *fctx = avctx->internal->thread_ctx;
444 int finished = fctx->next_finished;
449 * Submit a packet to the next decoding thread.
452 p = &fctx->threads[fctx->next_decoding];
453 err = update_context_from_user(p->avctx, avctx);
455 err = submit_packet(p, avpkt);
459 * If we're still receiving the initial packets, don't return a frame.
462 if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
465 if (fctx->delaying) {
472 * Return the next available frame from the oldest thread.
473 * If we're at the end of the stream, then we have to skip threads that
474 * didn't output a frame, because we don't want to accidentally signal
475 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
479 p = &fctx->threads[finished++];
481 if (atomic_load(&p->state) != STATE_INPUT_READY) {
482 pthread_mutex_lock(&p->progress_mutex);
483 while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
484 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
485 pthread_mutex_unlock(&p->progress_mutex);
488 av_frame_move_ref(picture, p->frame);
489 *got_picture_ptr = p->got_frame;
490 picture->pkt_dts = p->avpkt.dts;
496 * A later call with avkpt->size == 0 may loop over all threads,
497 * including this one, searching for a frame to return before being
498 * stopped by the "finished != fctx->next_finished" condition.
499 * Make sure we don't mistakenly return the same frame again.
503 if (finished >= avctx->thread_count) finished = 0;
504 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
506 update_context_from_thread(avctx, p->avctx, 1);
508 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
510 fctx->next_finished = finished;
513 * When no frame was found while flushing, but an error occurred in
514 * any thread, return it instead of 0.
515 * Otherwise the error can get lost.
517 if (!avpkt->size && !*got_picture_ptr)
520 /* return the size of the consumed packet if no error occurred */
521 return (p->result >= 0) ? avpkt->size : p->result;
524 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
527 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
530 atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
533 p = f->owner->internal->thread_ctx;
535 if (f->owner->debug&FF_DEBUG_THREADS)
536 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
538 pthread_mutex_lock(&p->progress_mutex);
540 atomic_store_explicit(&progress[field], n, memory_order_release);
542 pthread_cond_broadcast(&p->progress_cond);
543 pthread_mutex_unlock(&p->progress_mutex);
546 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
549 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
552 atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
555 p = f->owner->internal->thread_ctx;
557 if (f->owner->debug&FF_DEBUG_THREADS)
558 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
560 pthread_mutex_lock(&p->progress_mutex);
561 while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
562 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
563 pthread_mutex_unlock(&p->progress_mutex);
566 void ff_thread_finish_setup(AVCodecContext *avctx) {
567 PerThreadContext *p = avctx->internal->thread_ctx;
569 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
571 if (avctx->hwaccel && !p->hwaccel_serializing) {
572 pthread_mutex_lock(&p->parent->hwaccel_mutex);
573 p->hwaccel_serializing = 1;
576 pthread_mutex_lock(&p->progress_mutex);
577 if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
578 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
581 atomic_store(&p->state, STATE_SETUP_FINISHED);
583 pthread_cond_broadcast(&p->progress_cond);
584 pthread_mutex_unlock(&p->progress_mutex);
587 /// Waits for all threads to finish.
588 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
592 for (i = 0; i < thread_count; i++) {
593 PerThreadContext *p = &fctx->threads[i];
595 if (atomic_load(&p->state) != STATE_INPUT_READY) {
596 pthread_mutex_lock(&p->progress_mutex);
597 while (atomic_load(&p->state) != STATE_INPUT_READY)
598 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
599 pthread_mutex_unlock(&p->progress_mutex);
605 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
607 FrameThreadContext *fctx = avctx->internal->thread_ctx;
608 const AVCodec *codec = avctx->codec;
611 park_frame_worker_threads(fctx, thread_count);
613 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
614 if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
615 av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
616 fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
617 fctx->threads->avctx->internal->is_copy = 1;
620 for (i = 0; i < thread_count; i++) {
621 PerThreadContext *p = &fctx->threads[i];
623 pthread_mutex_lock(&p->mutex);
625 pthread_cond_signal(&p->input_cond);
626 pthread_mutex_unlock(&p->mutex);
629 pthread_join(p->thread, NULL);
632 if (codec->close && p->avctx)
633 codec->close(p->avctx);
635 release_delayed_buffers(p);
636 av_frame_free(&p->frame);
639 for (i = 0; i < thread_count; i++) {
640 PerThreadContext *p = &fctx->threads[i];
642 pthread_mutex_destroy(&p->mutex);
643 pthread_mutex_destroy(&p->progress_mutex);
644 pthread_cond_destroy(&p->input_cond);
645 pthread_cond_destroy(&p->progress_cond);
646 pthread_cond_destroy(&p->output_cond);
647 av_packet_unref(&p->avpkt);
648 av_freep(&p->released_buffers);
651 av_freep(&p->avctx->priv_data);
652 av_freep(&p->avctx->slice_offset);
656 av_freep(&p->avctx->internal);
657 av_buffer_unref(&p->avctx->hw_frames_ctx);
663 av_freep(&fctx->threads);
664 pthread_mutex_destroy(&fctx->buffer_mutex);
665 pthread_mutex_destroy(&fctx->hwaccel_mutex);
666 av_freep(&avctx->internal->thread_ctx);
668 if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
669 av_opt_free(avctx->priv_data);
673 int ff_frame_thread_init(AVCodecContext *avctx)
675 int thread_count = avctx->thread_count;
676 const AVCodec *codec = avctx->codec;
677 AVCodecContext *src = avctx;
678 FrameThreadContext *fctx;
686 int nb_cpus = av_cpu_count();
687 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
689 // use number of cores + 1 as thread count if there is more than one
691 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
693 thread_count = avctx->thread_count = 1;
696 if (thread_count <= 1) {
697 avctx->active_thread_type = 0;
701 avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
703 return AVERROR(ENOMEM);
705 fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
706 if (!fctx->threads) {
707 av_freep(&avctx->internal->thread_ctx);
708 return AVERROR(ENOMEM);
711 pthread_mutex_init(&fctx->buffer_mutex, NULL);
712 pthread_mutex_init(&fctx->hwaccel_mutex, NULL);
715 for (i = 0; i < thread_count; i++) {
716 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
717 PerThreadContext *p = &fctx->threads[i];
719 pthread_mutex_init(&p->mutex, NULL);
720 pthread_mutex_init(&p->progress_mutex, NULL);
721 pthread_cond_init(&p->input_cond, NULL);
722 pthread_cond_init(&p->progress_cond, NULL);
723 pthread_cond_init(&p->output_cond, NULL);
725 p->frame = av_frame_alloc();
728 err = AVERROR(ENOMEM);
736 err = AVERROR(ENOMEM);
742 copy->internal = av_malloc(sizeof(AVCodecInternal));
743 if (!copy->internal) {
744 copy->priv_data = NULL;
745 err = AVERROR(ENOMEM);
748 *copy->internal = *src->internal;
749 copy->internal->thread_ctx = p;
750 copy->internal->pkt = &p->avpkt;
756 err = codec->init(copy);
758 update_context_from_thread(avctx, copy, 1);
760 copy->priv_data = av_malloc(codec->priv_data_size);
761 if (!copy->priv_data) {
762 err = AVERROR(ENOMEM);
765 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
766 copy->internal->is_copy = 1;
768 if (codec->init_thread_copy)
769 err = codec->init_thread_copy(copy);
774 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
775 p->thread_init= !err;
783 ff_frame_thread_free(avctx, i+1);
788 void ff_thread_flush(AVCodecContext *avctx)
791 FrameThreadContext *fctx = avctx->internal->thread_ctx;
795 park_frame_worker_threads(fctx, avctx->thread_count);
796 if (fctx->prev_thread) {
797 if (fctx->prev_thread != &fctx->threads[0])
798 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
801 fctx->next_decoding = fctx->next_finished = 0;
803 fctx->prev_thread = NULL;
804 for (i = 0; i < avctx->thread_count; i++) {
805 PerThreadContext *p = &fctx->threads[i];
806 // Make sure decode flush calls with size=0 won't return old frames
808 av_frame_unref(p->frame);
810 release_delayed_buffers(p);
812 if (avctx->codec->flush)
813 avctx->codec->flush(p->avctx);
817 int ff_thread_can_start_frame(AVCodecContext *avctx)
819 PerThreadContext *p = avctx->internal->thread_ctx;
820 if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
821 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
827 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
829 PerThreadContext *p = avctx->internal->thread_ctx;
834 ff_init_buffer_info(avctx, f->f);
836 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
837 return ff_get_buffer(avctx, f->f, flags);
839 if (atomic_load(&p->state) != STATE_SETTING_UP &&
840 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
841 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
845 if (avctx->internal->allocate_progress) {
846 atomic_int *progress;
847 f->progress = av_buffer_alloc(2 * sizeof(*progress));
849 return AVERROR(ENOMEM);
851 progress = (atomic_int*)f->progress->data;
853 atomic_init(&progress[0], -1);
854 atomic_init(&progress[1], -1);
857 pthread_mutex_lock(&p->parent->buffer_mutex);
858 if (avctx->thread_safe_callbacks ||
859 avctx->get_buffer2 == avcodec_default_get_buffer2) {
860 err = ff_get_buffer(avctx, f->f, flags);
862 pthread_mutex_lock(&p->progress_mutex);
863 p->requested_frame = f->f;
864 p->requested_flags = flags;
865 atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
866 pthread_cond_broadcast(&p->progress_cond);
868 while (atomic_load(&p->state) != STATE_SETTING_UP)
869 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
873 pthread_mutex_unlock(&p->progress_mutex);
876 if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
877 ff_thread_finish_setup(avctx);
879 av_buffer_unref(&f->progress);
881 pthread_mutex_unlock(&p->parent->buffer_mutex);
886 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
888 enum AVPixelFormat res;
889 PerThreadContext *p = avctx->internal->thread_ctx;
890 if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
891 avctx->get_format == avcodec_default_get_format)
892 return ff_get_format(avctx, fmt);
893 if (atomic_load(&p->state) != STATE_SETTING_UP) {
894 av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
897 pthread_mutex_lock(&p->progress_mutex);
898 p->available_formats = fmt;
899 atomic_store(&p->state, STATE_GET_FORMAT);
900 pthread_cond_broadcast(&p->progress_cond);
902 while (atomic_load(&p->state) != STATE_SETTING_UP)
903 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
905 res = p->result_format;
907 pthread_mutex_unlock(&p->progress_mutex);
912 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
914 int ret = thread_get_buffer_internal(avctx, f, flags);
916 av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
920 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
922 PerThreadContext *p = avctx->internal->thread_ctx;
923 FrameThreadContext *fctx;
925 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
926 avctx->thread_safe_callbacks ||
927 avctx->get_buffer2 == avcodec_default_get_buffer2;
929 if (!f->f || !f->f->buf[0])
932 if (avctx->debug & FF_DEBUG_BUFFERS)
933 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
935 av_buffer_unref(&f->progress);
938 if (can_direct_free) {
939 av_frame_unref(f->f);
944 pthread_mutex_lock(&fctx->buffer_mutex);
946 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
948 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
949 (p->num_released_buffers + 1) *
950 sizeof(*p->released_buffers));
953 p->released_buffers = tmp;
955 dst = &p->released_buffers[p->num_released_buffers];
956 av_frame_move_ref(dst, f->f);
958 p->num_released_buffers++;
961 pthread_mutex_unlock(&fctx->buffer_mutex);