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.
109 * Context stored in the client AVCodecInternal thread_ctx.
111 typedef struct FrameThreadContext {
112 PerThreadContext *threads; ///< The contexts for each thread.
113 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
115 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
117 int next_decoding; ///< The next context to submit a packet to.
118 int next_finished; ///< The next context to return output from.
121 * Set for the first N packets, where N is the number of threads.
122 * While it is set, ff_thread_en/decode_frame won't return any results.
124 } FrameThreadContext;
126 #define THREAD_SAFE_CALLBACKS(avctx) \
127 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
130 * Codec worker thread.
132 * Automatically calls ff_thread_finish_setup() if the codec does
133 * not provide an update_thread_context method, or if the codec returns
136 static attribute_align_arg void *frame_worker_thread(void *arg)
138 PerThreadContext *p = arg;
139 AVCodecContext *avctx = p->avctx;
140 const AVCodec *codec = avctx->codec;
142 pthread_mutex_lock(&p->mutex);
144 while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
145 pthread_cond_wait(&p->input_cond, &p->mutex);
149 if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
150 ff_thread_finish_setup(avctx);
152 av_frame_unref(p->frame);
154 p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
156 if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
157 if (avctx->internal->allocate_progress)
158 av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
159 "free the frame on failure. This is a bug, please report it.\n");
160 av_frame_unref(p->frame);
163 if (atomic_load(&p->state) == STATE_SETTING_UP)
164 ff_thread_finish_setup(avctx);
166 pthread_mutex_lock(&p->progress_mutex);
168 for (i = 0; i < MAX_BUFFERS; i++)
169 if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
170 p->progress[i][0] = INT_MAX;
171 p->progress[i][1] = INT_MAX;
174 atomic_store(&p->state, STATE_INPUT_READY);
176 pthread_cond_broadcast(&p->progress_cond);
177 pthread_cond_signal(&p->output_cond);
178 pthread_mutex_unlock(&p->progress_mutex);
180 pthread_mutex_unlock(&p->mutex);
186 * Update the next thread's AVCodecContext with values from the reference thread's context.
188 * @param dst The destination context.
189 * @param src The source context.
190 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
191 * @return 0 on success, negative error code on failure
193 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
198 dst->time_base = src->time_base;
199 dst->framerate = src->framerate;
200 dst->width = src->width;
201 dst->height = src->height;
202 dst->pix_fmt = src->pix_fmt;
204 dst->coded_width = src->coded_width;
205 dst->coded_height = src->coded_height;
207 dst->has_b_frames = src->has_b_frames;
208 dst->idct_algo = src->idct_algo;
210 dst->bits_per_coded_sample = src->bits_per_coded_sample;
211 dst->sample_aspect_ratio = src->sample_aspect_ratio;
213 FF_DISABLE_DEPRECATION_WARNINGS
214 dst->dtg_active_format = src->dtg_active_format;
215 FF_ENABLE_DEPRECATION_WARNINGS
216 #endif /* FF_API_AFD */
218 dst->profile = src->profile;
219 dst->level = src->level;
221 dst->bits_per_raw_sample = src->bits_per_raw_sample;
222 dst->ticks_per_frame = src->ticks_per_frame;
223 dst->color_primaries = src->color_primaries;
225 dst->color_trc = src->color_trc;
226 dst->colorspace = src->colorspace;
227 dst->color_range = src->color_range;
228 dst->chroma_sample_location = src->chroma_sample_location;
230 dst->hwaccel = src->hwaccel;
231 dst->hwaccel_context = src->hwaccel_context;
233 dst->channels = src->channels;
234 dst->sample_rate = src->sample_rate;
235 dst->sample_fmt = src->sample_fmt;
236 dst->channel_layout = src->channel_layout;
237 dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
239 if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
240 (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
241 av_buffer_unref(&dst->hw_frames_ctx);
243 if (src->hw_frames_ctx) {
244 dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
245 if (!dst->hw_frames_ctx)
246 return AVERROR(ENOMEM);
252 dst->delay = src->thread_count - 1;
253 #if FF_API_CODED_FRAME
254 FF_DISABLE_DEPRECATION_WARNINGS
255 dst->coded_frame = src->coded_frame;
256 FF_ENABLE_DEPRECATION_WARNINGS
259 if (dst->codec->update_thread_context)
260 err = dst->codec->update_thread_context(dst, src);
267 * Update the next thread's AVCodecContext with values set by the user.
269 * @param dst The destination context.
270 * @param src The source context.
271 * @return 0 on success, negative error code on failure
273 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
275 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
276 dst->flags = src->flags;
278 dst->draw_horiz_band= src->draw_horiz_band;
279 dst->get_buffer2 = src->get_buffer2;
281 dst->opaque = src->opaque;
282 dst->debug = src->debug;
283 dst->debug_mv = src->debug_mv;
285 dst->slice_flags = src->slice_flags;
286 dst->flags2 = src->flags2;
288 copy_fields(skip_loop_filter, subtitle_header);
290 dst->frame_number = src->frame_number;
291 dst->reordered_opaque = src->reordered_opaque;
292 dst->thread_safe_callbacks = src->thread_safe_callbacks;
294 if (src->slice_count && src->slice_offset) {
295 if (dst->slice_count < src->slice_count) {
296 int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
297 sizeof(*dst->slice_offset));
301 memcpy(dst->slice_offset, src->slice_offset,
302 src->slice_count * sizeof(*dst->slice_offset));
304 dst->slice_count = src->slice_count;
309 /// Releases the buffers that this decoding thread was the last user of.
310 static void release_delayed_buffers(PerThreadContext *p)
312 FrameThreadContext *fctx = p->parent;
314 while (p->num_released_buffers > 0) {
317 pthread_mutex_lock(&fctx->buffer_mutex);
319 // fix extended data in case the caller screwed it up
320 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
321 p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
322 f = &p->released_buffers[--p->num_released_buffers];
323 f->extended_data = f->data;
326 pthread_mutex_unlock(&fctx->buffer_mutex);
330 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
332 FrameThreadContext *fctx = p->parent;
333 PerThreadContext *prev_thread = fctx->prev_thread;
334 const AVCodec *codec = p->avctx->codec;
337 if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
340 pthread_mutex_lock(&p->mutex);
342 release_delayed_buffers(p);
346 if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
347 pthread_mutex_lock(&prev_thread->progress_mutex);
348 while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
349 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
350 pthread_mutex_unlock(&prev_thread->progress_mutex);
353 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
355 pthread_mutex_unlock(&p->mutex);
360 av_packet_unref(&p->avpkt);
361 ret = av_packet_ref(&p->avpkt, avpkt);
363 pthread_mutex_unlock(&p->mutex);
364 av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
368 atomic_store(&p->state, STATE_SETTING_UP);
369 pthread_cond_signal(&p->input_cond);
370 pthread_mutex_unlock(&p->mutex);
373 * If the client doesn't have a thread-safe get_buffer(),
374 * then decoding threads call back to the main thread,
375 * and it calls back to the client here.
378 if (!p->avctx->thread_safe_callbacks && (
379 p->avctx->get_format != avcodec_default_get_format ||
380 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
381 while (atomic_load(&p->state) != STATE_SETUP_FINISHED && atomic_load(&p->state) != STATE_INPUT_READY) {
383 pthread_mutex_lock(&p->progress_mutex);
384 while (atomic_load(&p->state) == STATE_SETTING_UP)
385 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
387 switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
388 case STATE_GET_BUFFER:
389 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
391 case STATE_GET_FORMAT:
392 p->result_format = ff_get_format(p->avctx, p->available_formats);
399 atomic_store(&p->state, STATE_SETTING_UP);
400 pthread_cond_signal(&p->progress_cond);
402 pthread_mutex_unlock(&p->progress_mutex);
406 fctx->prev_thread = p;
407 fctx->next_decoding++;
412 int ff_thread_decode_frame(AVCodecContext *avctx,
413 AVFrame *picture, int *got_picture_ptr,
416 FrameThreadContext *fctx = avctx->internal->thread_ctx;
417 int finished = fctx->next_finished;
422 * Submit a packet to the next decoding thread.
425 p = &fctx->threads[fctx->next_decoding];
426 err = update_context_from_user(p->avctx, avctx);
428 err = submit_packet(p, avpkt);
432 * If we're still receiving the initial packets, don't return a frame.
435 if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
438 if (fctx->delaying) {
445 * Return the next available frame from the oldest thread.
446 * If we're at the end of the stream, then we have to skip threads that
447 * didn't output a frame, because we don't want to accidentally signal
448 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
452 p = &fctx->threads[finished++];
454 if (atomic_load(&p->state) != STATE_INPUT_READY) {
455 pthread_mutex_lock(&p->progress_mutex);
456 while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
457 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
458 pthread_mutex_unlock(&p->progress_mutex);
461 av_frame_move_ref(picture, p->frame);
462 *got_picture_ptr = p->got_frame;
463 picture->pkt_dts = p->avpkt.dts;
469 * A later call with avkpt->size == 0 may loop over all threads,
470 * including this one, searching for a frame to return before being
471 * stopped by the "finished != fctx->next_finished" condition.
472 * Make sure we don't mistakenly return the same frame again.
476 if (finished >= avctx->thread_count) finished = 0;
477 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
479 update_context_from_thread(avctx, p->avctx, 1);
481 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
483 fctx->next_finished = finished;
486 * When no frame was found while flushing, but an error occurred in
487 * any thread, return it instead of 0.
488 * Otherwise the error can get lost.
490 if (!avpkt->size && !*got_picture_ptr)
493 /* return the size of the consumed packet if no error occurred */
494 return (p->result >= 0) ? avpkt->size : p->result;
497 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
500 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
503 atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
506 p = f->owner->internal->thread_ctx;
508 if (f->owner->debug&FF_DEBUG_THREADS)
509 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
511 pthread_mutex_lock(&p->progress_mutex);
513 atomic_store_explicit(&progress[field], n, memory_order_release);
515 pthread_cond_broadcast(&p->progress_cond);
516 pthread_mutex_unlock(&p->progress_mutex);
519 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
522 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
525 atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
528 p = f->owner->internal->thread_ctx;
530 if (f->owner->debug&FF_DEBUG_THREADS)
531 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
533 pthread_mutex_lock(&p->progress_mutex);
534 while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
535 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
536 pthread_mutex_unlock(&p->progress_mutex);
539 void ff_thread_finish_setup(AVCodecContext *avctx) {
540 PerThreadContext *p = avctx->internal->thread_ctx;
542 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
544 pthread_mutex_lock(&p->progress_mutex);
545 if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
546 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
549 atomic_store(&p->state, STATE_SETUP_FINISHED);
551 pthread_cond_broadcast(&p->progress_cond);
552 pthread_mutex_unlock(&p->progress_mutex);
555 /// Waits for all threads to finish.
556 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
560 for (i = 0; i < thread_count; i++) {
561 PerThreadContext *p = &fctx->threads[i];
563 if (atomic_load(&p->state) != STATE_INPUT_READY) {
564 pthread_mutex_lock(&p->progress_mutex);
565 while (atomic_load(&p->state) != STATE_INPUT_READY)
566 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
567 pthread_mutex_unlock(&p->progress_mutex);
573 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
575 FrameThreadContext *fctx = avctx->internal->thread_ctx;
576 const AVCodec *codec = avctx->codec;
579 park_frame_worker_threads(fctx, thread_count);
581 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
582 if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
583 av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
584 fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
585 fctx->threads->avctx->internal->is_copy = 1;
588 for (i = 0; i < thread_count; i++) {
589 PerThreadContext *p = &fctx->threads[i];
591 pthread_mutex_lock(&p->mutex);
593 pthread_cond_signal(&p->input_cond);
594 pthread_mutex_unlock(&p->mutex);
597 pthread_join(p->thread, NULL);
600 if (codec->close && p->avctx)
601 codec->close(p->avctx);
603 release_delayed_buffers(p);
604 av_frame_free(&p->frame);
607 for (i = 0; i < thread_count; i++) {
608 PerThreadContext *p = &fctx->threads[i];
610 pthread_mutex_destroy(&p->mutex);
611 pthread_mutex_destroy(&p->progress_mutex);
612 pthread_cond_destroy(&p->input_cond);
613 pthread_cond_destroy(&p->progress_cond);
614 pthread_cond_destroy(&p->output_cond);
615 av_packet_unref(&p->avpkt);
616 av_freep(&p->released_buffers);
619 av_freep(&p->avctx->priv_data);
620 av_freep(&p->avctx->slice_offset);
624 av_freep(&p->avctx->internal);
625 av_buffer_unref(&p->avctx->hw_frames_ctx);
631 av_freep(&fctx->threads);
632 pthread_mutex_destroy(&fctx->buffer_mutex);
633 av_freep(&avctx->internal->thread_ctx);
635 if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
636 av_opt_free(avctx->priv_data);
640 int ff_frame_thread_init(AVCodecContext *avctx)
642 int thread_count = avctx->thread_count;
643 const AVCodec *codec = avctx->codec;
644 AVCodecContext *src = avctx;
645 FrameThreadContext *fctx;
653 int nb_cpus = av_cpu_count();
654 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
656 // use number of cores + 1 as thread count if there is more than one
658 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
660 thread_count = avctx->thread_count = 1;
663 if (thread_count <= 1) {
664 avctx->active_thread_type = 0;
668 avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
670 return AVERROR(ENOMEM);
672 fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
673 if (!fctx->threads) {
674 av_freep(&avctx->internal->thread_ctx);
675 return AVERROR(ENOMEM);
678 pthread_mutex_init(&fctx->buffer_mutex, NULL);
681 for (i = 0; i < thread_count; i++) {
682 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
683 PerThreadContext *p = &fctx->threads[i];
685 pthread_mutex_init(&p->mutex, NULL);
686 pthread_mutex_init(&p->progress_mutex, NULL);
687 pthread_cond_init(&p->input_cond, NULL);
688 pthread_cond_init(&p->progress_cond, NULL);
689 pthread_cond_init(&p->output_cond, NULL);
691 p->frame = av_frame_alloc();
694 err = AVERROR(ENOMEM);
702 err = AVERROR(ENOMEM);
708 copy->internal = av_malloc(sizeof(AVCodecInternal));
709 if (!copy->internal) {
710 copy->priv_data = NULL;
711 err = AVERROR(ENOMEM);
714 *copy->internal = *src->internal;
715 copy->internal->thread_ctx = p;
716 copy->internal->pkt = &p->avpkt;
722 err = codec->init(copy);
724 update_context_from_thread(avctx, copy, 1);
726 copy->priv_data = av_malloc(codec->priv_data_size);
727 if (!copy->priv_data) {
728 err = AVERROR(ENOMEM);
731 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
732 copy->internal->is_copy = 1;
734 if (codec->init_thread_copy)
735 err = codec->init_thread_copy(copy);
740 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
741 p->thread_init= !err;
749 ff_frame_thread_free(avctx, i+1);
754 void ff_thread_flush(AVCodecContext *avctx)
757 FrameThreadContext *fctx = avctx->internal->thread_ctx;
761 park_frame_worker_threads(fctx, avctx->thread_count);
762 if (fctx->prev_thread) {
763 if (fctx->prev_thread != &fctx->threads[0])
764 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
767 fctx->next_decoding = fctx->next_finished = 0;
769 fctx->prev_thread = NULL;
770 for (i = 0; i < avctx->thread_count; i++) {
771 PerThreadContext *p = &fctx->threads[i];
772 // Make sure decode flush calls with size=0 won't return old frames
774 av_frame_unref(p->frame);
776 release_delayed_buffers(p);
778 if (avctx->codec->flush)
779 avctx->codec->flush(p->avctx);
783 int ff_thread_can_start_frame(AVCodecContext *avctx)
785 PerThreadContext *p = avctx->internal->thread_ctx;
786 if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
787 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
793 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
795 PerThreadContext *p = avctx->internal->thread_ctx;
800 ff_init_buffer_info(avctx, f->f);
802 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
803 return ff_get_buffer(avctx, f->f, flags);
805 if (atomic_load(&p->state) != STATE_SETTING_UP &&
806 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
807 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
811 if (avctx->internal->allocate_progress) {
812 atomic_int *progress;
813 f->progress = av_buffer_alloc(2 * sizeof(*progress));
815 return AVERROR(ENOMEM);
817 progress = (atomic_int*)f->progress->data;
819 atomic_init(&progress[0], -1);
820 atomic_init(&progress[1], -1);
823 pthread_mutex_lock(&p->parent->buffer_mutex);
824 if (avctx->thread_safe_callbacks ||
825 avctx->get_buffer2 == avcodec_default_get_buffer2) {
826 err = ff_get_buffer(avctx, f->f, flags);
828 pthread_mutex_lock(&p->progress_mutex);
829 p->requested_frame = f->f;
830 p->requested_flags = flags;
831 atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
832 pthread_cond_broadcast(&p->progress_cond);
834 while (atomic_load(&p->state) != STATE_SETTING_UP)
835 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
839 pthread_mutex_unlock(&p->progress_mutex);
842 if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
843 ff_thread_finish_setup(avctx);
845 av_buffer_unref(&f->progress);
847 pthread_mutex_unlock(&p->parent->buffer_mutex);
852 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
854 enum AVPixelFormat res;
855 PerThreadContext *p = avctx->internal->thread_ctx;
856 if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
857 avctx->get_format == avcodec_default_get_format)
858 return ff_get_format(avctx, fmt);
859 if (atomic_load(&p->state) != STATE_SETTING_UP) {
860 av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
863 pthread_mutex_lock(&p->progress_mutex);
864 p->available_formats = fmt;
865 atomic_store(&p->state, STATE_GET_FORMAT);
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);
871 res = p->result_format;
873 pthread_mutex_unlock(&p->progress_mutex);
878 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
880 int ret = thread_get_buffer_internal(avctx, f, flags);
882 av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
886 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
888 PerThreadContext *p = avctx->internal->thread_ctx;
889 FrameThreadContext *fctx;
891 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
892 avctx->thread_safe_callbacks ||
893 avctx->get_buffer2 == avcodec_default_get_buffer2;
895 if (!f->f || !f->f->buf[0])
898 if (avctx->debug & FF_DEBUG_BUFFERS)
899 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
901 av_buffer_unref(&f->progress);
904 if (can_direct_free) {
905 av_frame_unref(f->f);
910 pthread_mutex_lock(&fctx->buffer_mutex);
912 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
914 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
915 (p->num_released_buffers + 1) *
916 sizeof(*p->released_buffers));
919 p->released_buffers = tmp;
921 dst = &p->released_buffers[p->num_released_buffers];
922 av_frame_move_ref(dst, f->f);
924 p->num_released_buffers++;
927 pthread_mutex_unlock(&fctx->buffer_mutex);