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;
113 * Context stored in the client AVCodecInternal thread_ctx.
115 typedef struct FrameThreadContext {
116 PerThreadContext *threads; ///< The contexts for each thread.
117 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
119 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
121 * This lock is used for ensuring threads run in serial when hwaccel
124 pthread_mutex_t hwaccel_mutex;
125 pthread_mutex_t async_mutex;
127 int next_decoding; ///< The next context to submit a packet to.
128 int next_finished; ///< The next context to return output from.
131 * Set for the first N packets, where N is the number of threads.
132 * While it is set, ff_thread_en/decode_frame won't return any results.
134 } FrameThreadContext;
136 #define THREAD_SAFE_CALLBACKS(avctx) \
137 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
140 * Codec worker thread.
142 * Automatically calls ff_thread_finish_setup() if the codec does
143 * not provide an update_thread_context method, or if the codec returns
146 static attribute_align_arg void *frame_worker_thread(void *arg)
148 PerThreadContext *p = arg;
149 AVCodecContext *avctx = p->avctx;
150 const AVCodec *codec = avctx->codec;
152 pthread_mutex_lock(&p->mutex);
154 while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
155 pthread_cond_wait(&p->input_cond, &p->mutex);
159 if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
160 ff_thread_finish_setup(avctx);
162 /* If a decoder supports hwaccel, then it must call ff_get_format().
163 * Since that call must happen before ff_thread_finish_setup(), the
164 * decoder is required to implement update_thread_context() and call
165 * ff_thread_finish_setup() manually. Therefore the above
166 * ff_thread_finish_setup() call did not happen and hwaccel_serializing
167 * cannot be true here. */
168 av_assert0(!p->hwaccel_serializing);
170 /* if the previous thread uses hwaccel then we take the lock to ensure
171 * the threads don't run concurrently */
172 if (avctx->hwaccel) {
173 pthread_mutex_lock(&p->parent->hwaccel_mutex);
174 p->hwaccel_serializing = 1;
177 av_frame_unref(p->frame);
179 p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
181 if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
182 if (avctx->internal->allocate_progress)
183 av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
184 "free the frame on failure. This is a bug, please report it.\n");
185 av_frame_unref(p->frame);
188 if (atomic_load(&p->state) == STATE_SETTING_UP)
189 ff_thread_finish_setup(avctx);
191 if (p->hwaccel_serializing) {
192 p->hwaccel_serializing = 0;
193 pthread_mutex_unlock(&p->parent->hwaccel_mutex);
196 if (p->async_serializing) {
197 p->async_serializing = 0;
198 pthread_mutex_unlock(&p->parent->async_mutex);
201 pthread_mutex_lock(&p->progress_mutex);
203 for (i = 0; i < MAX_BUFFERS; i++)
204 if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
205 p->progress[i][0] = INT_MAX;
206 p->progress[i][1] = INT_MAX;
209 atomic_store(&p->state, STATE_INPUT_READY);
211 pthread_cond_broadcast(&p->progress_cond);
212 pthread_cond_signal(&p->output_cond);
213 pthread_mutex_unlock(&p->progress_mutex);
215 pthread_mutex_unlock(&p->mutex);
221 * Update the next thread's AVCodecContext with values from the reference thread's context.
223 * @param dst The destination context.
224 * @param src The source context.
225 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
226 * @return 0 on success, negative error code on failure
228 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
233 dst->time_base = src->time_base;
234 dst->framerate = src->framerate;
235 dst->width = src->width;
236 dst->height = src->height;
237 dst->pix_fmt = src->pix_fmt;
239 dst->coded_width = src->coded_width;
240 dst->coded_height = src->coded_height;
242 dst->has_b_frames = src->has_b_frames;
243 dst->idct_algo = src->idct_algo;
245 dst->bits_per_coded_sample = src->bits_per_coded_sample;
246 dst->sample_aspect_ratio = src->sample_aspect_ratio;
248 FF_DISABLE_DEPRECATION_WARNINGS
249 dst->dtg_active_format = src->dtg_active_format;
250 FF_ENABLE_DEPRECATION_WARNINGS
251 #endif /* FF_API_AFD */
253 dst->profile = src->profile;
254 dst->level = src->level;
256 dst->bits_per_raw_sample = src->bits_per_raw_sample;
257 dst->ticks_per_frame = src->ticks_per_frame;
258 dst->color_primaries = src->color_primaries;
260 dst->color_trc = src->color_trc;
261 dst->colorspace = src->colorspace;
262 dst->color_range = src->color_range;
263 dst->chroma_sample_location = src->chroma_sample_location;
265 dst->hwaccel = src->hwaccel;
266 dst->hwaccel_context = src->hwaccel_context;
268 dst->channels = src->channels;
269 dst->sample_rate = src->sample_rate;
270 dst->sample_fmt = src->sample_fmt;
271 dst->channel_layout = src->channel_layout;
272 dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
274 if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
275 (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
276 av_buffer_unref(&dst->hw_frames_ctx);
278 if (src->hw_frames_ctx) {
279 dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
280 if (!dst->hw_frames_ctx)
281 return AVERROR(ENOMEM);
287 dst->delay = src->thread_count - 1;
288 #if FF_API_CODED_FRAME
289 FF_DISABLE_DEPRECATION_WARNINGS
290 dst->coded_frame = src->coded_frame;
291 FF_ENABLE_DEPRECATION_WARNINGS
294 if (dst->codec->update_thread_context)
295 err = dst->codec->update_thread_context(dst, src);
302 * Update the next thread's AVCodecContext with values set by the user.
304 * @param dst The destination context.
305 * @param src The source context.
306 * @return 0 on success, negative error code on failure
308 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
310 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
311 dst->flags = src->flags;
313 dst->draw_horiz_band= src->draw_horiz_band;
314 dst->get_buffer2 = src->get_buffer2;
316 dst->opaque = src->opaque;
317 dst->debug = src->debug;
318 dst->debug_mv = src->debug_mv;
320 dst->slice_flags = src->slice_flags;
321 dst->flags2 = src->flags2;
323 copy_fields(skip_loop_filter, subtitle_header);
325 dst->frame_number = src->frame_number;
326 dst->reordered_opaque = src->reordered_opaque;
327 dst->thread_safe_callbacks = src->thread_safe_callbacks;
329 if (src->slice_count && src->slice_offset) {
330 if (dst->slice_count < src->slice_count) {
331 int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
332 sizeof(*dst->slice_offset));
336 memcpy(dst->slice_offset, src->slice_offset,
337 src->slice_count * sizeof(*dst->slice_offset));
339 dst->slice_count = src->slice_count;
344 /// Releases the buffers that this decoding thread was the last user of.
345 static void release_delayed_buffers(PerThreadContext *p)
347 FrameThreadContext *fctx = p->parent;
349 while (p->num_released_buffers > 0) {
352 pthread_mutex_lock(&fctx->buffer_mutex);
354 // fix extended data in case the caller screwed it up
355 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
356 p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
357 f = &p->released_buffers[--p->num_released_buffers];
358 f->extended_data = f->data;
361 pthread_mutex_unlock(&fctx->buffer_mutex);
365 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
367 FrameThreadContext *fctx = p->parent;
368 PerThreadContext *prev_thread = fctx->prev_thread;
369 const AVCodec *codec = p->avctx->codec;
372 if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
375 pthread_mutex_lock(&p->mutex);
377 release_delayed_buffers(p);
381 if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
382 pthread_mutex_lock(&prev_thread->progress_mutex);
383 while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
384 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
385 pthread_mutex_unlock(&prev_thread->progress_mutex);
388 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
390 pthread_mutex_unlock(&p->mutex);
395 av_packet_unref(&p->avpkt);
396 ret = av_packet_ref(&p->avpkt, avpkt);
398 pthread_mutex_unlock(&p->mutex);
399 av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
403 atomic_store(&p->state, STATE_SETTING_UP);
404 pthread_cond_signal(&p->input_cond);
405 pthread_mutex_unlock(&p->mutex);
408 * If the client doesn't have a thread-safe get_buffer(),
409 * then decoding threads call back to the main thread,
410 * and it calls back to the client here.
413 if (!p->avctx->thread_safe_callbacks && (
414 p->avctx->get_format != avcodec_default_get_format ||
415 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
416 while (atomic_load(&p->state) != STATE_SETUP_FINISHED && atomic_load(&p->state) != STATE_INPUT_READY) {
418 pthread_mutex_lock(&p->progress_mutex);
419 while (atomic_load(&p->state) == STATE_SETTING_UP)
420 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
422 switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
423 case STATE_GET_BUFFER:
424 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
426 case STATE_GET_FORMAT:
427 p->result_format = ff_get_format(p->avctx, p->available_formats);
434 atomic_store(&p->state, STATE_SETTING_UP);
435 pthread_cond_signal(&p->progress_cond);
437 pthread_mutex_unlock(&p->progress_mutex);
441 fctx->prev_thread = p;
442 fctx->next_decoding++;
447 int ff_thread_decode_frame(AVCodecContext *avctx,
448 AVFrame *picture, int *got_picture_ptr,
451 FrameThreadContext *fctx = avctx->internal->thread_ctx;
452 int finished = fctx->next_finished;
456 /* release the async lock, permitting blocked hwaccel threads to
457 * go forward while we are in this function */
458 pthread_mutex_unlock(&fctx->async_mutex);
461 * Submit a packet to the next decoding thread.
464 p = &fctx->threads[fctx->next_decoding];
465 err = update_context_from_user(p->avctx, avctx);
468 err = submit_packet(p, avpkt);
473 * If we're still receiving the initial packets, don't return a frame.
476 if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
479 if (fctx->delaying) {
488 * Return the next available frame from the oldest thread.
489 * If we're at the end of the stream, then we have to skip threads that
490 * didn't output a frame, because we don't want to accidentally signal
491 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
495 p = &fctx->threads[finished++];
497 if (atomic_load(&p->state) != STATE_INPUT_READY) {
498 pthread_mutex_lock(&p->progress_mutex);
499 while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
500 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
501 pthread_mutex_unlock(&p->progress_mutex);
504 av_frame_move_ref(picture, p->frame);
505 *got_picture_ptr = p->got_frame;
506 picture->pkt_dts = p->avpkt.dts;
512 * A later call with avkpt->size == 0 may loop over all threads,
513 * including this one, searching for a frame to return before being
514 * stopped by the "finished != fctx->next_finished" condition.
515 * Make sure we don't mistakenly return the same frame again.
519 if (finished >= avctx->thread_count) finished = 0;
520 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
522 update_context_from_thread(avctx, p->avctx, 1);
524 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
526 fctx->next_finished = finished;
529 * When no frame was found while flushing, but an error occurred in
530 * any thread, return it instead of 0.
531 * Otherwise the error can get lost.
533 if (!avpkt->size && !*got_picture_ptr)
536 /* return the size of the consumed packet if no error occurred */
537 ret = (p->result >= 0) ? avpkt->size : p->result;
539 pthread_mutex_lock(&fctx->async_mutex);
545 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
548 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
551 atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
554 p = f->owner->internal->thread_ctx;
556 if (f->owner->debug&FF_DEBUG_THREADS)
557 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
559 pthread_mutex_lock(&p->progress_mutex);
561 atomic_store_explicit(&progress[field], n, memory_order_release);
563 pthread_cond_broadcast(&p->progress_cond);
564 pthread_mutex_unlock(&p->progress_mutex);
567 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
570 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
573 atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
576 p = f->owner->internal->thread_ctx;
578 if (f->owner->debug&FF_DEBUG_THREADS)
579 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
581 pthread_mutex_lock(&p->progress_mutex);
582 while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
583 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
584 pthread_mutex_unlock(&p->progress_mutex);
587 void ff_thread_finish_setup(AVCodecContext *avctx) {
588 PerThreadContext *p = avctx->internal->thread_ctx;
590 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
592 if (avctx->hwaccel && !p->hwaccel_serializing) {
593 pthread_mutex_lock(&p->parent->hwaccel_mutex);
594 p->hwaccel_serializing = 1;
597 /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
598 if (avctx->hwaccel &&
599 !(avctx->hwaccel->caps_internal & HWACCEL_CAP_ASYNC_SAFE)) {
600 p->async_serializing = 1;
601 pthread_mutex_lock(&p->parent->async_mutex);
604 pthread_mutex_lock(&p->progress_mutex);
605 if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
606 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
609 atomic_store(&p->state, STATE_SETUP_FINISHED);
611 pthread_cond_broadcast(&p->progress_cond);
612 pthread_mutex_unlock(&p->progress_mutex);
615 /// Waits for all threads to finish.
616 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
620 pthread_mutex_unlock(&fctx->async_mutex);
622 for (i = 0; i < thread_count; i++) {
623 PerThreadContext *p = &fctx->threads[i];
625 if (atomic_load(&p->state) != STATE_INPUT_READY) {
626 pthread_mutex_lock(&p->progress_mutex);
627 while (atomic_load(&p->state) != STATE_INPUT_READY)
628 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
629 pthread_mutex_unlock(&p->progress_mutex);
634 pthread_mutex_lock(&fctx->async_mutex);
637 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
639 FrameThreadContext *fctx = avctx->internal->thread_ctx;
640 const AVCodec *codec = avctx->codec;
643 park_frame_worker_threads(fctx, thread_count);
645 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
646 if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
647 av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
648 fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
649 fctx->threads->avctx->internal->is_copy = 1;
652 for (i = 0; i < thread_count; i++) {
653 PerThreadContext *p = &fctx->threads[i];
655 pthread_mutex_lock(&p->mutex);
657 pthread_cond_signal(&p->input_cond);
658 pthread_mutex_unlock(&p->mutex);
661 pthread_join(p->thread, NULL);
664 if (codec->close && p->avctx)
665 codec->close(p->avctx);
667 release_delayed_buffers(p);
668 av_frame_free(&p->frame);
671 for (i = 0; i < thread_count; i++) {
672 PerThreadContext *p = &fctx->threads[i];
674 pthread_mutex_destroy(&p->mutex);
675 pthread_mutex_destroy(&p->progress_mutex);
676 pthread_cond_destroy(&p->input_cond);
677 pthread_cond_destroy(&p->progress_cond);
678 pthread_cond_destroy(&p->output_cond);
679 av_packet_unref(&p->avpkt);
680 av_freep(&p->released_buffers);
683 av_freep(&p->avctx->priv_data);
684 av_freep(&p->avctx->slice_offset);
688 av_freep(&p->avctx->internal);
689 av_buffer_unref(&p->avctx->hw_frames_ctx);
695 av_freep(&fctx->threads);
696 pthread_mutex_destroy(&fctx->buffer_mutex);
697 pthread_mutex_destroy(&fctx->hwaccel_mutex);
699 pthread_mutex_unlock(&fctx->async_mutex);
700 pthread_mutex_destroy(&fctx->async_mutex);
702 av_freep(&avctx->internal->thread_ctx);
704 if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
705 av_opt_free(avctx->priv_data);
709 int ff_frame_thread_init(AVCodecContext *avctx)
711 int thread_count = avctx->thread_count;
712 const AVCodec *codec = avctx->codec;
713 AVCodecContext *src = avctx;
714 FrameThreadContext *fctx;
722 int nb_cpus = av_cpu_count();
723 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
725 // use number of cores + 1 as thread count if there is more than one
727 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
729 thread_count = avctx->thread_count = 1;
732 if (thread_count <= 1) {
733 avctx->active_thread_type = 0;
737 avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
739 return AVERROR(ENOMEM);
741 fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
742 if (!fctx->threads) {
743 av_freep(&avctx->internal->thread_ctx);
744 return AVERROR(ENOMEM);
747 pthread_mutex_init(&fctx->buffer_mutex, NULL);
748 pthread_mutex_init(&fctx->hwaccel_mutex, NULL);
750 pthread_mutex_init(&fctx->async_mutex, NULL);
751 pthread_mutex_lock(&fctx->async_mutex);
755 for (i = 0; i < thread_count; i++) {
756 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
757 PerThreadContext *p = &fctx->threads[i];
759 pthread_mutex_init(&p->mutex, NULL);
760 pthread_mutex_init(&p->progress_mutex, NULL);
761 pthread_cond_init(&p->input_cond, NULL);
762 pthread_cond_init(&p->progress_cond, NULL);
763 pthread_cond_init(&p->output_cond, NULL);
765 p->frame = av_frame_alloc();
768 err = AVERROR(ENOMEM);
776 err = AVERROR(ENOMEM);
782 copy->internal = av_malloc(sizeof(AVCodecInternal));
783 if (!copy->internal) {
784 copy->priv_data = NULL;
785 err = AVERROR(ENOMEM);
788 *copy->internal = *src->internal;
789 copy->internal->thread_ctx = p;
790 copy->internal->pkt = &p->avpkt;
796 err = codec->init(copy);
798 update_context_from_thread(avctx, copy, 1);
800 copy->priv_data = av_malloc(codec->priv_data_size);
801 if (!copy->priv_data) {
802 err = AVERROR(ENOMEM);
805 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
806 copy->internal->is_copy = 1;
808 if (codec->init_thread_copy)
809 err = codec->init_thread_copy(copy);
814 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
815 p->thread_init= !err;
823 ff_frame_thread_free(avctx, i+1);
828 void ff_thread_flush(AVCodecContext *avctx)
831 FrameThreadContext *fctx = avctx->internal->thread_ctx;
835 park_frame_worker_threads(fctx, avctx->thread_count);
836 if (fctx->prev_thread) {
837 if (fctx->prev_thread != &fctx->threads[0])
838 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
841 fctx->next_decoding = fctx->next_finished = 0;
843 fctx->prev_thread = NULL;
844 for (i = 0; i < avctx->thread_count; i++) {
845 PerThreadContext *p = &fctx->threads[i];
846 // Make sure decode flush calls with size=0 won't return old frames
848 av_frame_unref(p->frame);
850 release_delayed_buffers(p);
852 if (avctx->codec->flush)
853 avctx->codec->flush(p->avctx);
857 int ff_thread_can_start_frame(AVCodecContext *avctx)
859 PerThreadContext *p = avctx->internal->thread_ctx;
860 if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
861 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
867 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
869 PerThreadContext *p = avctx->internal->thread_ctx;
874 ff_init_buffer_info(avctx, f->f);
876 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
877 return ff_get_buffer(avctx, f->f, flags);
879 if (atomic_load(&p->state) != STATE_SETTING_UP &&
880 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
881 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
885 if (avctx->internal->allocate_progress) {
886 atomic_int *progress;
887 f->progress = av_buffer_alloc(2 * sizeof(*progress));
889 return AVERROR(ENOMEM);
891 progress = (atomic_int*)f->progress->data;
893 atomic_init(&progress[0], -1);
894 atomic_init(&progress[1], -1);
897 pthread_mutex_lock(&p->parent->buffer_mutex);
898 if (avctx->thread_safe_callbacks ||
899 avctx->get_buffer2 == avcodec_default_get_buffer2) {
900 err = ff_get_buffer(avctx, f->f, flags);
902 pthread_mutex_lock(&p->progress_mutex);
903 p->requested_frame = f->f;
904 p->requested_flags = flags;
905 atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
906 pthread_cond_broadcast(&p->progress_cond);
908 while (atomic_load(&p->state) != STATE_SETTING_UP)
909 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
913 pthread_mutex_unlock(&p->progress_mutex);
916 if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
917 ff_thread_finish_setup(avctx);
919 av_buffer_unref(&f->progress);
921 pthread_mutex_unlock(&p->parent->buffer_mutex);
926 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
928 enum AVPixelFormat res;
929 PerThreadContext *p = avctx->internal->thread_ctx;
930 if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
931 avctx->get_format == avcodec_default_get_format)
932 return ff_get_format(avctx, fmt);
933 if (atomic_load(&p->state) != STATE_SETTING_UP) {
934 av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
937 pthread_mutex_lock(&p->progress_mutex);
938 p->available_formats = fmt;
939 atomic_store(&p->state, STATE_GET_FORMAT);
940 pthread_cond_broadcast(&p->progress_cond);
942 while (atomic_load(&p->state) != STATE_SETTING_UP)
943 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
945 res = p->result_format;
947 pthread_mutex_unlock(&p->progress_mutex);
952 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
954 int ret = thread_get_buffer_internal(avctx, f, flags);
956 av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
960 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
962 PerThreadContext *p = avctx->internal->thread_ctx;
963 FrameThreadContext *fctx;
965 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
966 avctx->thread_safe_callbacks ||
967 avctx->get_buffer2 == avcodec_default_get_buffer2;
969 if (!f->f || !f->f->buf[0])
972 if (avctx->debug & FF_DEBUG_BUFFERS)
973 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
975 av_buffer_unref(&f->progress);
978 if (can_direct_free) {
979 av_frame_unref(f->f);
984 pthread_mutex_lock(&fctx->buffer_mutex);
986 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
988 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
989 (p->num_released_buffers + 1) *
990 sizeof(*p->released_buffers));
993 p->released_buffers = tmp;
995 dst = &p->released_buffers[p->num_released_buffers];
996 av_frame_move_ref(dst, f->f);
998 p->num_released_buffers++;
1001 pthread_mutex_unlock(&fctx->buffer_mutex);