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 * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
70 typedef struct PerThreadContext {
71 struct FrameThreadContext *parent;
75 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
76 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
77 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
79 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
80 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
82 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
84 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
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.
93 * Array of frames passed to ff_thread_release_buffer().
94 * Frames are released after all threads referencing them are finished.
96 AVFrame *released_buffers;
97 int num_released_buffers;
98 int released_buffers_allocated;
100 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
101 int requested_flags; ///< flags passed to get_buffer() for requested_frame
103 const enum AVPixelFormat *available_formats; ///< Format array for get_format()
104 enum AVPixelFormat result_format; ///< get_format() result
106 int die; ///< Set when the thread should exit.
108 int hwaccel_serializing;
109 int async_serializing;
111 atomic_int debug_threads; ///< Set if the FF_DEBUG_THREADS option is set.
115 * Context stored in the client AVCodecInternal thread_ctx.
117 typedef struct FrameThreadContext {
118 PerThreadContext *threads; ///< The contexts for each thread.
119 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
121 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
123 * This lock is used for ensuring threads run in serial when hwaccel
126 pthread_mutex_t hwaccel_mutex;
127 pthread_mutex_t async_mutex;
128 pthread_cond_t async_cond;
131 int next_decoding; ///< The next context to submit a packet to.
132 int next_finished; ///< The next context to return output from.
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.
138 } FrameThreadContext;
140 #define THREAD_SAFE_CALLBACKS(avctx) \
141 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
143 static void async_lock(FrameThreadContext *fctx)
145 pthread_mutex_lock(&fctx->async_mutex);
146 while (fctx->async_lock)
147 pthread_cond_wait(&fctx->async_cond, &fctx->async_mutex);
148 fctx->async_lock = 1;
149 pthread_mutex_unlock(&fctx->async_mutex);
152 static void async_unlock(FrameThreadContext *fctx)
154 pthread_mutex_lock(&fctx->async_mutex);
155 av_assert0(fctx->async_lock);
156 fctx->async_lock = 0;
157 pthread_cond_broadcast(&fctx->async_cond);
158 pthread_mutex_unlock(&fctx->async_mutex);
162 * Codec worker thread.
164 * Automatically calls ff_thread_finish_setup() if the codec does
165 * not provide an update_thread_context method, or if the codec returns
168 static attribute_align_arg void *frame_worker_thread(void *arg)
170 PerThreadContext *p = arg;
171 AVCodecContext *avctx = p->avctx;
172 const AVCodec *codec = avctx->codec;
174 pthread_mutex_lock(&p->mutex);
176 while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
177 pthread_cond_wait(&p->input_cond, &p->mutex);
181 if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
182 ff_thread_finish_setup(avctx);
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. */
190 av_assert0(!p->hwaccel_serializing);
192 /* if the previous thread uses hwaccel then we take the lock to ensure
193 * the threads don't run concurrently */
194 if (avctx->hwaccel) {
195 pthread_mutex_lock(&p->parent->hwaccel_mutex);
196 p->hwaccel_serializing = 1;
199 av_frame_unref(p->frame);
201 p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
203 if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
204 if (avctx->codec->caps_internal & FF_CODEC_CAP_ALLOCATE_PROGRESS)
205 av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
206 "free the frame on failure. This is a bug, please report it.\n");
207 av_frame_unref(p->frame);
210 if (atomic_load(&p->state) == STATE_SETTING_UP)
211 ff_thread_finish_setup(avctx);
213 if (p->hwaccel_serializing) {
214 p->hwaccel_serializing = 0;
215 pthread_mutex_unlock(&p->parent->hwaccel_mutex);
218 if (p->async_serializing) {
219 p->async_serializing = 0;
221 async_unlock(p->parent);
224 pthread_mutex_lock(&p->progress_mutex);
226 atomic_store(&p->state, STATE_INPUT_READY);
228 pthread_cond_broadcast(&p->progress_cond);
229 pthread_cond_signal(&p->output_cond);
230 pthread_mutex_unlock(&p->progress_mutex);
232 pthread_mutex_unlock(&p->mutex);
238 * Update the next thread's AVCodecContext with values from the reference thread's context.
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
245 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
249 if (dst != src && (for_user || !(src->codec_descriptor->props & AV_CODEC_PROP_INTRA_ONLY))) {
250 dst->time_base = src->time_base;
251 dst->framerate = src->framerate;
252 dst->width = src->width;
253 dst->height = src->height;
254 dst->pix_fmt = src->pix_fmt;
255 dst->sw_pix_fmt = src->sw_pix_fmt;
257 dst->coded_width = src->coded_width;
258 dst->coded_height = src->coded_height;
260 dst->has_b_frames = src->has_b_frames;
261 dst->idct_algo = src->idct_algo;
263 dst->bits_per_coded_sample = src->bits_per_coded_sample;
264 dst->sample_aspect_ratio = src->sample_aspect_ratio;
266 dst->profile = src->profile;
267 dst->level = src->level;
269 dst->bits_per_raw_sample = src->bits_per_raw_sample;
270 dst->ticks_per_frame = src->ticks_per_frame;
271 dst->color_primaries = src->color_primaries;
273 dst->color_trc = src->color_trc;
274 dst->colorspace = src->colorspace;
275 dst->color_range = src->color_range;
276 dst->chroma_sample_location = src->chroma_sample_location;
278 dst->hwaccel = src->hwaccel;
279 dst->hwaccel_context = src->hwaccel_context;
281 dst->channels = src->channels;
282 dst->sample_rate = src->sample_rate;
283 dst->sample_fmt = src->sample_fmt;
284 dst->channel_layout = src->channel_layout;
285 dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
287 if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
288 (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
289 av_buffer_unref(&dst->hw_frames_ctx);
291 if (src->hw_frames_ctx) {
292 dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
293 if (!dst->hw_frames_ctx)
294 return AVERROR(ENOMEM);
298 dst->hwaccel_flags = src->hwaccel_flags;
302 dst->delay = src->thread_count - 1;
303 #if FF_API_CODED_FRAME
304 FF_DISABLE_DEPRECATION_WARNINGS
305 dst->coded_frame = src->coded_frame;
306 FF_ENABLE_DEPRECATION_WARNINGS
309 if (dst->codec->update_thread_context)
310 err = dst->codec->update_thread_context(dst, src);
317 * Update the next thread's AVCodecContext with values set by the user.
319 * @param dst The destination context.
320 * @param src The source context.
321 * @return 0 on success, negative error code on failure
323 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
325 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
326 dst->flags = src->flags;
328 dst->draw_horiz_band= src->draw_horiz_band;
329 dst->get_buffer2 = src->get_buffer2;
331 dst->opaque = src->opaque;
332 dst->debug = src->debug;
333 dst->debug_mv = src->debug_mv;
335 dst->slice_flags = src->slice_flags;
336 dst->flags2 = src->flags2;
337 dst->export_side_data = src->export_side_data;
339 copy_fields(skip_loop_filter, subtitle_header);
341 dst->frame_number = src->frame_number;
342 dst->reordered_opaque = src->reordered_opaque;
343 dst->thread_safe_callbacks = src->thread_safe_callbacks;
345 if (src->slice_count && src->slice_offset) {
346 if (dst->slice_count < src->slice_count) {
347 int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
348 sizeof(*dst->slice_offset));
352 memcpy(dst->slice_offset, src->slice_offset,
353 src->slice_count * sizeof(*dst->slice_offset));
355 dst->slice_count = src->slice_count;
360 /// Releases the buffers that this decoding thread was the last user of.
361 static void release_delayed_buffers(PerThreadContext *p)
363 FrameThreadContext *fctx = p->parent;
365 while (p->num_released_buffers > 0) {
368 pthread_mutex_lock(&fctx->buffer_mutex);
370 // fix extended data in case the caller screwed it up
371 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
372 p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
373 f = &p->released_buffers[--p->num_released_buffers];
374 f->extended_data = f->data;
377 pthread_mutex_unlock(&fctx->buffer_mutex);
381 static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx,
384 FrameThreadContext *fctx = p->parent;
385 PerThreadContext *prev_thread = fctx->prev_thread;
386 const AVCodec *codec = p->avctx->codec;
389 if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
392 pthread_mutex_lock(&p->mutex);
394 ret = update_context_from_user(p->avctx, user_avctx);
396 pthread_mutex_unlock(&p->mutex);
399 atomic_store_explicit(&p->debug_threads,
400 (p->avctx->debug & FF_DEBUG_THREADS) != 0,
401 memory_order_relaxed);
403 release_delayed_buffers(p);
407 if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
408 pthread_mutex_lock(&prev_thread->progress_mutex);
409 while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
410 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
411 pthread_mutex_unlock(&prev_thread->progress_mutex);
414 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
416 pthread_mutex_unlock(&p->mutex);
421 av_packet_unref(&p->avpkt);
422 ret = av_packet_ref(&p->avpkt, avpkt);
424 pthread_mutex_unlock(&p->mutex);
425 av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
429 atomic_store(&p->state, STATE_SETTING_UP);
430 pthread_cond_signal(&p->input_cond);
431 pthread_mutex_unlock(&p->mutex);
434 * If the client doesn't have a thread-safe get_buffer(),
435 * then decoding threads call back to the main thread,
436 * and it calls back to the client here.
439 if (!p->avctx->thread_safe_callbacks && (
440 p->avctx->get_format != avcodec_default_get_format ||
441 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
442 while (atomic_load(&p->state) != STATE_SETUP_FINISHED && atomic_load(&p->state) != STATE_INPUT_READY) {
444 pthread_mutex_lock(&p->progress_mutex);
445 while (atomic_load(&p->state) == STATE_SETTING_UP)
446 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
448 switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
449 case STATE_GET_BUFFER:
450 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
452 case STATE_GET_FORMAT:
453 p->result_format = ff_get_format(p->avctx, p->available_formats);
460 atomic_store(&p->state, STATE_SETTING_UP);
461 pthread_cond_signal(&p->progress_cond);
463 pthread_mutex_unlock(&p->progress_mutex);
467 fctx->prev_thread = p;
468 fctx->next_decoding++;
473 int ff_thread_decode_frame(AVCodecContext *avctx,
474 AVFrame *picture, int *got_picture_ptr,
477 FrameThreadContext *fctx = avctx->internal->thread_ctx;
478 int finished = fctx->next_finished;
482 /* release the async lock, permitting blocked hwaccel threads to
483 * go forward while we are in this function */
487 * Submit a packet to the next decoding thread.
490 p = &fctx->threads[fctx->next_decoding];
491 err = submit_packet(p, avctx, avpkt);
496 * If we're still receiving the initial packets, don't return a frame.
499 if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
502 if (fctx->delaying) {
511 * Return the next available frame from the oldest thread.
512 * If we're at the end of the stream, then we have to skip threads that
513 * didn't output a frame/error, because we don't want to accidentally signal
514 * EOF (avpkt->size == 0 && *got_picture_ptr == 0 && err >= 0).
518 p = &fctx->threads[finished++];
520 if (atomic_load(&p->state) != STATE_INPUT_READY) {
521 pthread_mutex_lock(&p->progress_mutex);
522 while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
523 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
524 pthread_mutex_unlock(&p->progress_mutex);
527 av_frame_move_ref(picture, p->frame);
528 *got_picture_ptr = p->got_frame;
529 picture->pkt_dts = p->avpkt.dts;
533 * A later call with avkpt->size == 0 may loop over all threads,
534 * including this one, searching for a frame/error to return before being
535 * stopped by the "finished != fctx->next_finished" condition.
536 * Make sure we don't mistakenly return the same frame/error again.
541 if (finished >= avctx->thread_count) finished = 0;
542 } while (!avpkt->size && !*got_picture_ptr && err >= 0 && finished != fctx->next_finished);
544 update_context_from_thread(avctx, p->avctx, 1);
546 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
548 fctx->next_finished = finished;
550 /* return the size of the consumed packet if no error occurred */
558 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
561 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
564 atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
567 p = f->owner[field]->internal->thread_ctx;
569 if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
570 av_log(f->owner[field], AV_LOG_DEBUG,
571 "%p finished %d field %d\n", progress, n, field);
573 pthread_mutex_lock(&p->progress_mutex);
575 atomic_store_explicit(&progress[field], n, memory_order_release);
577 pthread_cond_broadcast(&p->progress_cond);
578 pthread_mutex_unlock(&p->progress_mutex);
581 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
584 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
587 atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
590 p = f->owner[field]->internal->thread_ctx;
592 if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
593 av_log(f->owner[field], AV_LOG_DEBUG,
594 "thread awaiting %d field %d from %p\n", n, field, progress);
596 pthread_mutex_lock(&p->progress_mutex);
597 while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
598 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
599 pthread_mutex_unlock(&p->progress_mutex);
602 void ff_thread_finish_setup(AVCodecContext *avctx) {
603 PerThreadContext *p = avctx->internal->thread_ctx;
605 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
607 if (avctx->hwaccel && !p->hwaccel_serializing) {
608 pthread_mutex_lock(&p->parent->hwaccel_mutex);
609 p->hwaccel_serializing = 1;
612 /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
613 if (avctx->hwaccel &&
614 !(avctx->hwaccel->caps_internal & HWACCEL_CAP_ASYNC_SAFE)) {
615 p->async_serializing = 1;
617 async_lock(p->parent);
620 pthread_mutex_lock(&p->progress_mutex);
621 if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
622 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
625 atomic_store(&p->state, STATE_SETUP_FINISHED);
627 pthread_cond_broadcast(&p->progress_cond);
628 pthread_mutex_unlock(&p->progress_mutex);
631 /// Waits for all threads to finish.
632 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
638 for (i = 0; i < thread_count; i++) {
639 PerThreadContext *p = &fctx->threads[i];
641 if (atomic_load(&p->state) != STATE_INPUT_READY) {
642 pthread_mutex_lock(&p->progress_mutex);
643 while (atomic_load(&p->state) != STATE_INPUT_READY)
644 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
645 pthread_mutex_unlock(&p->progress_mutex);
653 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
655 FrameThreadContext *fctx = avctx->internal->thread_ctx;
656 const AVCodec *codec = avctx->codec;
659 park_frame_worker_threads(fctx, thread_count);
661 if (fctx->prev_thread && avctx->internal->hwaccel_priv_data !=
662 fctx->prev_thread->avctx->internal->hwaccel_priv_data) {
663 if (update_context_from_thread(avctx, fctx->prev_thread->avctx, 1) < 0) {
664 av_log(avctx, AV_LOG_ERROR, "Failed to update user thread.\n");
668 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
669 if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
670 av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
671 fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
672 fctx->threads->avctx->internal->is_copy = 1;
675 for (i = 0; i < thread_count; i++) {
676 PerThreadContext *p = &fctx->threads[i];
678 pthread_mutex_lock(&p->mutex);
680 pthread_cond_signal(&p->input_cond);
681 pthread_mutex_unlock(&p->mutex);
684 pthread_join(p->thread, NULL);
687 if (codec->close && p->avctx)
688 codec->close(p->avctx);
690 release_delayed_buffers(p);
691 av_frame_free(&p->frame);
694 for (i = 0; i < thread_count; i++) {
695 PerThreadContext *p = &fctx->threads[i];
697 pthread_mutex_destroy(&p->mutex);
698 pthread_mutex_destroy(&p->progress_mutex);
699 pthread_cond_destroy(&p->input_cond);
700 pthread_cond_destroy(&p->progress_cond);
701 pthread_cond_destroy(&p->output_cond);
702 av_packet_unref(&p->avpkt);
703 av_freep(&p->released_buffers);
706 av_freep(&p->avctx->priv_data);
707 av_freep(&p->avctx->slice_offset);
711 av_freep(&p->avctx->internal);
712 av_buffer_unref(&p->avctx->hw_frames_ctx);
718 av_freep(&fctx->threads);
719 pthread_mutex_destroy(&fctx->buffer_mutex);
720 pthread_mutex_destroy(&fctx->hwaccel_mutex);
721 pthread_mutex_destroy(&fctx->async_mutex);
722 pthread_cond_destroy(&fctx->async_cond);
724 av_freep(&avctx->internal->thread_ctx);
726 if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
727 av_opt_free(avctx->priv_data);
731 int ff_frame_thread_init(AVCodecContext *avctx)
733 int thread_count = avctx->thread_count;
734 const AVCodec *codec = avctx->codec;
735 AVCodecContext *src = avctx;
736 FrameThreadContext *fctx;
740 int nb_cpus = av_cpu_count();
742 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
745 // use number of cores + 1 as thread count if there is more than one
747 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
749 thread_count = avctx->thread_count = 1;
752 if (thread_count <= 1) {
753 avctx->active_thread_type = 0;
757 avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
759 return AVERROR(ENOMEM);
761 fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
762 if (!fctx->threads) {
763 av_freep(&avctx->internal->thread_ctx);
764 return AVERROR(ENOMEM);
767 pthread_mutex_init(&fctx->buffer_mutex, NULL);
768 pthread_mutex_init(&fctx->hwaccel_mutex, NULL);
769 pthread_mutex_init(&fctx->async_mutex, NULL);
770 pthread_cond_init(&fctx->async_cond, NULL);
772 fctx->async_lock = 1;
775 for (i = 0; i < thread_count; i++) {
776 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
777 PerThreadContext *p = &fctx->threads[i];
779 pthread_mutex_init(&p->mutex, NULL);
780 pthread_mutex_init(&p->progress_mutex, NULL);
781 pthread_cond_init(&p->input_cond, NULL);
782 pthread_cond_init(&p->progress_cond, NULL);
783 pthread_cond_init(&p->output_cond, NULL);
785 p->frame = av_frame_alloc();
788 err = AVERROR(ENOMEM);
796 err = AVERROR(ENOMEM);
802 copy->internal = av_malloc(sizeof(AVCodecInternal));
803 if (!copy->internal) {
804 copy->priv_data = NULL;
805 err = AVERROR(ENOMEM);
808 *copy->internal = *src->internal;
809 copy->internal->thread_ctx = p;
810 copy->internal->last_pkt_props = &p->avpkt;
816 err = codec->init(copy);
818 update_context_from_thread(avctx, copy, 1);
820 copy->priv_data = av_malloc(codec->priv_data_size);
821 if (!copy->priv_data) {
822 err = AVERROR(ENOMEM);
825 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
826 copy->internal->is_copy = 1;
828 if (codec->init_thread_copy)
829 err = codec->init_thread_copy(copy);
834 atomic_init(&p->debug_threads, (copy->debug & FF_DEBUG_THREADS) != 0);
836 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
837 p->thread_init= !err;
845 ff_frame_thread_free(avctx, i+1);
850 void ff_thread_flush(AVCodecContext *avctx)
853 FrameThreadContext *fctx = avctx->internal->thread_ctx;
857 park_frame_worker_threads(fctx, avctx->thread_count);
858 if (fctx->prev_thread) {
859 if (fctx->prev_thread != &fctx->threads[0])
860 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
863 fctx->next_decoding = fctx->next_finished = 0;
865 fctx->prev_thread = NULL;
866 for (i = 0; i < avctx->thread_count; i++) {
867 PerThreadContext *p = &fctx->threads[i];
868 // Make sure decode flush calls with size=0 won't return old frames
870 av_frame_unref(p->frame);
873 release_delayed_buffers(p);
875 if (avctx->codec->flush)
876 avctx->codec->flush(p->avctx);
880 int ff_thread_can_start_frame(AVCodecContext *avctx)
882 PerThreadContext *p = avctx->internal->thread_ctx;
883 if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
884 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
890 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
892 PerThreadContext *p = avctx->internal->thread_ctx;
895 f->owner[0] = f->owner[1] = avctx;
897 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
898 return ff_get_buffer(avctx, f->f, flags);
900 if (atomic_load(&p->state) != STATE_SETTING_UP &&
901 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
902 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
906 if (avctx->codec->caps_internal & FF_CODEC_CAP_ALLOCATE_PROGRESS) {
907 atomic_int *progress;
908 f->progress = av_buffer_alloc(2 * sizeof(*progress));
910 return AVERROR(ENOMEM);
912 progress = (atomic_int*)f->progress->data;
914 atomic_init(&progress[0], -1);
915 atomic_init(&progress[1], -1);
918 pthread_mutex_lock(&p->parent->buffer_mutex);
919 if (THREAD_SAFE_CALLBACKS(avctx)) {
920 err = ff_get_buffer(avctx, f->f, flags);
922 pthread_mutex_lock(&p->progress_mutex);
923 p->requested_frame = f->f;
924 p->requested_flags = flags;
925 atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
926 pthread_cond_broadcast(&p->progress_cond);
928 while (atomic_load(&p->state) != STATE_SETTING_UP)
929 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
933 pthread_mutex_unlock(&p->progress_mutex);
936 if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
937 ff_thread_finish_setup(avctx);
939 av_buffer_unref(&f->progress);
941 pthread_mutex_unlock(&p->parent->buffer_mutex);
946 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
948 enum AVPixelFormat res;
949 PerThreadContext *p = avctx->internal->thread_ctx;
950 if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
951 avctx->get_format == avcodec_default_get_format)
952 return ff_get_format(avctx, fmt);
953 if (atomic_load(&p->state) != STATE_SETTING_UP) {
954 av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
957 pthread_mutex_lock(&p->progress_mutex);
958 p->available_formats = fmt;
959 atomic_store(&p->state, STATE_GET_FORMAT);
960 pthread_cond_broadcast(&p->progress_cond);
962 while (atomic_load(&p->state) != STATE_SETTING_UP)
963 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
965 res = p->result_format;
967 pthread_mutex_unlock(&p->progress_mutex);
972 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
974 int ret = thread_get_buffer_internal(avctx, f, flags);
976 av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
980 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
982 PerThreadContext *p = avctx->internal->thread_ctx;
983 FrameThreadContext *fctx;
986 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
987 THREAD_SAFE_CALLBACKS(avctx);
992 if (avctx->debug & FF_DEBUG_BUFFERS)
993 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
995 av_buffer_unref(&f->progress);
996 f->owner[0] = f->owner[1] = NULL;
998 // when the frame buffers are not allocated, just reset it to clean state
999 if (can_direct_free || !f->f->buf[0]) {
1000 av_frame_unref(f->f);
1005 pthread_mutex_lock(&fctx->buffer_mutex);
1007 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers)) {
1008 ret = AVERROR(ENOMEM);
1011 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
1012 (p->num_released_buffers + 1) *
1013 sizeof(*p->released_buffers));
1015 ret = AVERROR(ENOMEM);
1018 p->released_buffers = tmp;
1020 dst = &p->released_buffers[p->num_released_buffers];
1021 av_frame_move_ref(dst, f->f);
1023 p->num_released_buffers++;
1026 pthread_mutex_unlock(&fctx->buffer_mutex);
1028 // make sure the frame is clean even if we fail to free it
1029 // this leaks, but it is better than crashing
1031 av_log(avctx, AV_LOG_ERROR, "Could not queue a frame for freeing, this will leak\n");
1032 memset(f->f->buf, 0, sizeof(f->f->buf));
1033 if (f->f->extended_buf)
1034 memset(f->f->extended_buf, 0, f->f->nb_extended_buf * sizeof(*f->f->extended_buf));
1035 av_frame_unref(f->f);