2 * This file is part of Libav.
4 * Libav 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 * Libav 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 Libav; 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 "compat/w32pthreads.h"
38 #include "pthread_internal.h"
42 #include "libavutil/avassert.h"
43 #include "libavutil/buffer.h"
44 #include "libavutil/common.h"
45 #include "libavutil/cpu.h"
46 #include "libavutil/frame.h"
47 #include "libavutil/internal.h"
48 #include "libavutil/log.h"
49 #include "libavutil/mem.h"
52 ///< Set when the thread is awaiting a packet.
54 ///< Set before the codec has called ff_thread_finish_setup().
57 * Set when the codec calls get_buffer().
58 * State is returned to STATE_SETTING_UP afterwards.
61 ///< Set after the codec has called ff_thread_finish_setup().
66 * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
68 typedef struct PerThreadContext {
69 struct FrameThreadContext *parent;
73 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
74 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
75 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
77 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
78 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
80 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
82 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
84 AVFrame *frame; ///< Output frame (for decoding) or input (for encoding).
85 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
86 int result; ///< The result of the last codec decode/encode() call.
91 * Array of frames passed to ff_thread_release_buffer().
92 * Frames are released after all threads referencing them are finished.
94 AVFrame *released_buffers;
95 int num_released_buffers;
96 int released_buffers_allocated;
98 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
99 int requested_flags; ///< flags passed to get_buffer() for requested_frame
101 int die; ///< Set when the thread should exit.
105 * Context stored in the client AVCodecInternal thread_ctx.
107 typedef struct FrameThreadContext {
108 PerThreadContext *threads; ///< The contexts for each thread.
109 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
111 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
113 int next_decoding; ///< The next context to submit a packet to.
114 int next_finished; ///< The next context to return output from.
117 * Set for the first N packets, where N is the number of threads.
118 * While it is set, ff_thread_en/decode_frame won't return any results.
120 } FrameThreadContext;
123 * Codec worker thread.
125 * Automatically calls ff_thread_finish_setup() if the codec does
126 * not provide an update_thread_context method, or if the codec returns
129 static attribute_align_arg void *frame_worker_thread(void *arg)
131 PerThreadContext *p = arg;
132 AVCodecContext *avctx = p->avctx;
133 const AVCodec *codec = avctx->codec;
136 if (atomic_load(&p->state) == STATE_INPUT_READY) {
137 pthread_mutex_lock(&p->mutex);
138 while (atomic_load(&p->state) == STATE_INPUT_READY) {
140 pthread_mutex_unlock(&p->mutex);
143 pthread_cond_wait(&p->input_cond, &p->mutex);
145 pthread_mutex_unlock(&p->mutex);
148 if (!codec->update_thread_context && avctx->thread_safe_callbacks)
149 ff_thread_finish_setup(avctx);
151 pthread_mutex_lock(&p->mutex);
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 atomic_store(&p->state, STATE_INPUT_READY);
168 pthread_mutex_lock(&p->progress_mutex);
169 pthread_cond_signal(&p->output_cond);
170 pthread_mutex_unlock(&p->progress_mutex);
172 pthread_mutex_unlock(&p->mutex);
180 * Update the next thread's AVCodecContext with values from the reference thread's context.
182 * @param dst The destination context.
183 * @param src The source context.
184 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
186 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
191 dst->time_base = src->time_base;
192 dst->framerate = src->framerate;
193 dst->width = src->width;
194 dst->height = src->height;
195 dst->pix_fmt = src->pix_fmt;
197 dst->coded_width = src->coded_width;
198 dst->coded_height = src->coded_height;
200 dst->has_b_frames = src->has_b_frames;
201 dst->idct_algo = src->idct_algo;
203 dst->bits_per_coded_sample = src->bits_per_coded_sample;
204 dst->sample_aspect_ratio = src->sample_aspect_ratio;
206 FF_DISABLE_DEPRECATION_WARNINGS
207 dst->dtg_active_format = src->dtg_active_format;
208 FF_ENABLE_DEPRECATION_WARNINGS
209 #endif /* FF_API_AFD */
211 dst->profile = src->profile;
212 dst->level = src->level;
214 dst->bits_per_raw_sample = src->bits_per_raw_sample;
215 dst->ticks_per_frame = src->ticks_per_frame;
216 dst->color_primaries = src->color_primaries;
218 dst->color_trc = src->color_trc;
219 dst->colorspace = src->colorspace;
220 dst->color_range = src->color_range;
221 dst->chroma_sample_location = src->chroma_sample_location;
223 dst->hwaccel = src->hwaccel;
224 dst->hwaccel_context = src->hwaccel_context;
225 dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
229 #if FF_API_CODED_FRAME
230 FF_DISABLE_DEPRECATION_WARNINGS
231 dst->coded_frame = src->coded_frame;
232 FF_ENABLE_DEPRECATION_WARNINGS
235 if (dst->codec->update_thread_context)
236 err = dst->codec->update_thread_context(dst, src);
243 * Update the next thread's AVCodecContext with values set by the user.
245 * @param dst The destination context.
246 * @param src The source context.
247 * @return 0 on success, negative error code on failure
249 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
251 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
252 dst->flags = src->flags;
254 dst->draw_horiz_band= src->draw_horiz_band;
255 dst->get_buffer2 = src->get_buffer2;
257 dst->opaque = src->opaque;
258 dst->debug = src->debug;
260 dst->slice_flags = src->slice_flags;
261 dst->flags2 = src->flags2;
263 copy_fields(skip_loop_filter, subtitle_header);
265 dst->frame_number = src->frame_number;
266 dst->reordered_opaque = src->reordered_opaque;
268 if (src->slice_count && src->slice_offset) {
269 if (dst->slice_count < src->slice_count) {
270 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
271 sizeof(*dst->slice_offset));
273 av_free(dst->slice_offset);
274 return AVERROR(ENOMEM);
276 dst->slice_offset = tmp;
278 memcpy(dst->slice_offset, src->slice_offset,
279 src->slice_count * sizeof(*dst->slice_offset));
281 dst->slice_count = src->slice_count;
286 /// Releases the buffers that this decoding thread was the last user of.
287 static void release_delayed_buffers(PerThreadContext *p)
289 FrameThreadContext *fctx = p->parent;
291 while (p->num_released_buffers > 0) {
294 pthread_mutex_lock(&fctx->buffer_mutex);
296 // fix extended data in case the caller screwed it up
297 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
298 f = &p->released_buffers[--p->num_released_buffers];
299 f->extended_data = f->data;
302 pthread_mutex_unlock(&fctx->buffer_mutex);
306 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
308 FrameThreadContext *fctx = p->parent;
309 PerThreadContext *prev_thread = fctx->prev_thread;
310 const AVCodec *codec = p->avctx->codec;
312 if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
315 pthread_mutex_lock(&p->mutex);
317 release_delayed_buffers(p);
321 if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
322 pthread_mutex_lock(&prev_thread->progress_mutex);
323 while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
324 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
325 pthread_mutex_unlock(&prev_thread->progress_mutex);
328 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
330 pthread_mutex_unlock(&p->mutex);
335 av_packet_unref(&p->avpkt);
336 av_packet_ref(&p->avpkt, avpkt);
338 atomic_store(&p->state, STATE_SETTING_UP);
339 pthread_cond_signal(&p->input_cond);
340 pthread_mutex_unlock(&p->mutex);
343 * If the client doesn't have a thread-safe get_buffer(),
344 * then decoding threads call back to the main thread,
345 * and it calls back to the client here.
348 if (!p->avctx->thread_safe_callbacks &&
349 p->avctx->get_buffer2 != avcodec_default_get_buffer2) {
350 while (atomic_load(&p->state) != STATE_SETUP_FINISHED &&
351 atomic_load(&p->state) != STATE_INPUT_READY) {
352 pthread_mutex_lock(&p->progress_mutex);
353 while (atomic_load(&p->state) == STATE_SETTING_UP)
354 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
356 if (atomic_load_explicit(&p->state, memory_order_acquire) == STATE_GET_BUFFER) {
357 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
358 atomic_store(&p->state, STATE_SETTING_UP);
359 pthread_cond_signal(&p->progress_cond);
361 pthread_mutex_unlock(&p->progress_mutex);
365 fctx->prev_thread = p;
366 fctx->next_decoding++;
371 int ff_thread_decode_frame(AVCodecContext *avctx,
372 AVFrame *picture, int *got_picture_ptr,
375 FrameThreadContext *fctx = avctx->internal->thread_ctx;
376 int finished = fctx->next_finished;
381 * Submit a packet to the next decoding thread.
384 p = &fctx->threads[fctx->next_decoding];
385 err = update_context_from_user(p->avctx, avctx);
387 err = submit_packet(p, avpkt);
391 * If we're still receiving the initial packets, don't return a frame.
394 if (fctx->delaying) {
395 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
403 * Return the next available frame from the oldest thread.
404 * If we're at the end of the stream, then we have to skip threads that
405 * didn't output a frame, because we don't want to accidentally signal
406 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
410 p = &fctx->threads[finished++];
412 if (atomic_load(&p->state) != STATE_INPUT_READY) {
413 pthread_mutex_lock(&p->progress_mutex);
414 while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
415 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
416 pthread_mutex_unlock(&p->progress_mutex);
419 av_frame_move_ref(picture, p->frame);
420 *got_picture_ptr = p->got_frame;
421 picture->pkt_dts = p->avpkt.dts;
424 * A later call with avkpt->size == 0 may loop over all threads,
425 * including this one, searching for a frame to return before being
426 * stopped by the "finished != fctx->next_finished" condition.
427 * Make sure we don't mistakenly return the same frame again.
431 if (finished >= avctx->thread_count) finished = 0;
432 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
434 update_context_from_thread(avctx, p->avctx, 1);
436 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
438 fctx->next_finished = finished;
440 /* return the size of the consumed packet if no error occurred */
441 return (p->result >= 0) ? avpkt->size : p->result;
444 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
447 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
450 atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
453 p = f->owner->internal->thread_ctx;
455 if (f->owner->debug&FF_DEBUG_THREADS)
456 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
458 pthread_mutex_lock(&p->progress_mutex);
460 atomic_store(&progress[field], n);
462 pthread_cond_broadcast(&p->progress_cond);
463 pthread_mutex_unlock(&p->progress_mutex);
466 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
469 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
472 atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
475 p = f->owner->internal->thread_ctx;
477 if (f->owner->debug&FF_DEBUG_THREADS)
478 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
480 pthread_mutex_lock(&p->progress_mutex);
481 while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
482 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
483 pthread_mutex_unlock(&p->progress_mutex);
486 void ff_thread_finish_setup(AVCodecContext *avctx) {
487 PerThreadContext *p = avctx->internal->thread_ctx;
489 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
491 pthread_mutex_lock(&p->progress_mutex);
493 atomic_store(&p->state, STATE_SETUP_FINISHED);
495 pthread_cond_broadcast(&p->progress_cond);
496 pthread_mutex_unlock(&p->progress_mutex);
499 /// Waits for all threads to finish.
500 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
504 for (i = 0; i < thread_count; i++) {
505 PerThreadContext *p = &fctx->threads[i];
507 if (atomic_load(&p->state) != STATE_INPUT_READY) {
508 pthread_mutex_lock(&p->progress_mutex);
509 while (atomic_load(&p->state) != STATE_INPUT_READY)
510 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
511 pthread_mutex_unlock(&p->progress_mutex);
516 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
518 FrameThreadContext *fctx = avctx->internal->thread_ctx;
519 const AVCodec *codec = avctx->codec;
522 park_frame_worker_threads(fctx, thread_count);
524 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
525 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
527 for (i = 0; i < thread_count; i++) {
528 PerThreadContext *p = &fctx->threads[i];
530 pthread_mutex_lock(&p->mutex);
532 pthread_cond_signal(&p->input_cond);
533 pthread_mutex_unlock(&p->mutex);
536 pthread_join(p->thread, NULL);
539 codec->close(p->avctx);
543 release_delayed_buffers(p);
544 av_frame_free(&p->frame);
547 for (i = 0; i < thread_count; i++) {
548 PerThreadContext *p = &fctx->threads[i];
550 pthread_mutex_destroy(&p->mutex);
551 pthread_mutex_destroy(&p->progress_mutex);
552 pthread_cond_destroy(&p->input_cond);
553 pthread_cond_destroy(&p->progress_cond);
554 pthread_cond_destroy(&p->output_cond);
555 av_packet_unref(&p->avpkt);
556 av_freep(&p->released_buffers);
559 av_freep(&p->avctx->priv_data);
560 av_freep(&p->avctx->slice_offset);
563 av_freep(&p->avctx->internal);
567 av_freep(&fctx->threads);
568 pthread_mutex_destroy(&fctx->buffer_mutex);
569 av_freep(&avctx->internal->thread_ctx);
572 int ff_frame_thread_init(AVCodecContext *avctx)
574 int thread_count = avctx->thread_count;
575 const AVCodec *codec = avctx->codec;
576 AVCodecContext *src = avctx;
577 FrameThreadContext *fctx;
585 int nb_cpus = av_cpu_count();
586 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
587 // use number of cores + 1 as thread count if there is more than one
589 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
591 thread_count = avctx->thread_count = 1;
594 if (thread_count <= 1) {
595 avctx->active_thread_type = 0;
599 avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
601 return AVERROR(ENOMEM);
603 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
604 if (!fctx->threads) {
605 av_freep(&avctx->internal->thread_ctx);
606 return AVERROR(ENOMEM);
609 pthread_mutex_init(&fctx->buffer_mutex, NULL);
612 for (i = 0; i < thread_count; i++) {
613 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
614 PerThreadContext *p = &fctx->threads[i];
616 pthread_mutex_init(&p->mutex, NULL);
617 pthread_mutex_init(&p->progress_mutex, NULL);
618 pthread_cond_init(&p->input_cond, NULL);
619 pthread_cond_init(&p->progress_cond, NULL);
620 pthread_cond_init(&p->output_cond, NULL);
622 p->frame = av_frame_alloc();
625 err = AVERROR(ENOMEM);
633 err = AVERROR(ENOMEM);
639 copy->internal = av_malloc(sizeof(AVCodecInternal));
640 if (!copy->internal) {
641 err = AVERROR(ENOMEM);
644 *copy->internal = *src->internal;
645 copy->internal->thread_ctx = p;
646 copy->internal->pkt = &p->avpkt;
652 err = codec->init(copy);
654 update_context_from_thread(avctx, copy, 1);
656 copy->priv_data = av_malloc(codec->priv_data_size);
657 if (!copy->priv_data) {
658 err = AVERROR(ENOMEM);
661 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
662 copy->internal->is_copy = 1;
664 if (codec->init_thread_copy)
665 err = codec->init_thread_copy(copy);
670 if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
677 ff_frame_thread_free(avctx, i+1);
682 void ff_thread_flush(AVCodecContext *avctx)
685 FrameThreadContext *fctx = avctx->internal->thread_ctx;
689 park_frame_worker_threads(fctx, avctx->thread_count);
690 if (fctx->prev_thread) {
691 if (fctx->prev_thread != &fctx->threads[0])
692 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
695 fctx->next_decoding = fctx->next_finished = 0;
697 fctx->prev_thread = NULL;
698 for (i = 0; i < avctx->thread_count; i++) {
699 PerThreadContext *p = &fctx->threads[i];
700 // Make sure decode flush calls with size=0 won't return old frames
702 av_frame_unref(p->frame);
704 release_delayed_buffers(p);
706 if (avctx->codec->flush)
707 avctx->codec->flush(p->avctx);
711 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
713 PerThreadContext *p = avctx->internal->thread_ctx;
718 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
719 return ff_get_buffer(avctx, f->f, flags);
721 if (atomic_load(&p->state) != STATE_SETTING_UP &&
722 (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
723 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
727 if (avctx->internal->allocate_progress) {
728 atomic_int *progress;
729 f->progress = av_buffer_alloc(2 * sizeof(*progress));
731 return AVERROR(ENOMEM);
733 progress = (atomic_int*)f->progress->data;
735 atomic_store(&progress[0], -1);
736 atomic_store(&progress[1], -1);
739 pthread_mutex_lock(&p->parent->buffer_mutex);
740 if (avctx->thread_safe_callbacks ||
741 avctx->get_buffer2 == avcodec_default_get_buffer2) {
742 err = ff_get_buffer(avctx, f->f, flags);
744 p->requested_frame = f->f;
745 p->requested_flags = flags;
746 atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
747 pthread_mutex_lock(&p->progress_mutex);
748 pthread_cond_signal(&p->progress_cond);
750 while (atomic_load(&p->state) != STATE_SETTING_UP)
751 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
755 pthread_mutex_unlock(&p->progress_mutex);
758 if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
759 ff_thread_finish_setup(avctx);
762 av_buffer_unref(&f->progress);
764 pthread_mutex_unlock(&p->parent->buffer_mutex);
769 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
771 PerThreadContext *p = avctx->internal->thread_ctx;
772 FrameThreadContext *fctx;
774 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
775 avctx->thread_safe_callbacks ||
776 avctx->get_buffer2 == avcodec_default_get_buffer2;
778 if (!f->f || !f->f->buf[0])
781 if (avctx->debug & FF_DEBUG_BUFFERS)
782 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
784 av_buffer_unref(&f->progress);
787 if (can_direct_free) {
788 av_frame_unref(f->f);
793 pthread_mutex_lock(&fctx->buffer_mutex);
795 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
797 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
798 (p->num_released_buffers + 1) *
799 sizeof(*p->released_buffers));
802 p->released_buffers = tmp;
804 dst = &p->released_buffers[p->num_released_buffers];
805 av_frame_move_ref(dst, f->f);
807 p->num_released_buffers++;
810 pthread_mutex_unlock(&fctx->buffer_mutex);