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
32 #include "compat/w32pthreads.h"
37 #include "pthread_internal.h"
41 #include "libavutil/avassert.h"
42 #include "libavutil/buffer.h"
43 #include "libavutil/common.h"
44 #include "libavutil/cpu.h"
45 #include "libavutil/frame.h"
46 #include "libavutil/internal.h"
47 #include "libavutil/log.h"
48 #include "libavutil/mem.h"
51 * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
53 typedef struct PerThreadContext {
54 struct FrameThreadContext *parent;
58 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
59 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
60 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
62 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
63 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
65 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
67 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
69 AVFrame *frame; ///< Output frame (for decoding) or input (for encoding).
70 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
71 int result; ///< The result of the last codec decode/encode() call.
74 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
75 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
76 STATE_GET_BUFFER, /**<
77 * Set when the codec calls get_buffer().
78 * State is returned to STATE_SETTING_UP afterwards.
80 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
84 * Array of frames passed to ff_thread_release_buffer().
85 * Frames are released after all threads referencing them are finished.
87 AVFrame *released_buffers;
88 int num_released_buffers;
89 int released_buffers_allocated;
91 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
92 int requested_flags; ///< flags passed to get_buffer() for requested_frame
96 * Context stored in the client AVCodecInternal thread_ctx.
98 typedef struct FrameThreadContext {
99 PerThreadContext *threads; ///< The contexts for each thread.
100 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
102 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
104 int next_decoding; ///< The next context to submit a packet to.
105 int next_finished; ///< The next context to return output from.
108 * Set for the first N packets, where N is the number of threads.
109 * While it is set, ff_thread_en/decode_frame won't return any results.
112 int die; ///< Set when threads should exit.
113 } FrameThreadContext;
116 * Codec worker thread.
118 * Automatically calls ff_thread_finish_setup() if the codec does
119 * not provide an update_thread_context method, or if the codec returns
122 static attribute_align_arg void *frame_worker_thread(void *arg)
124 PerThreadContext *p = arg;
125 FrameThreadContext *fctx = p->parent;
126 AVCodecContext *avctx = p->avctx;
127 const AVCodec *codec = avctx->codec;
130 if (p->state == STATE_INPUT_READY && !fctx->die) {
131 pthread_mutex_lock(&p->mutex);
132 while (p->state == STATE_INPUT_READY && !fctx->die)
133 pthread_cond_wait(&p->input_cond, &p->mutex);
134 pthread_mutex_unlock(&p->mutex);
137 if (fctx->die) break;
139 if (!codec->update_thread_context && avctx->thread_safe_callbacks)
140 ff_thread_finish_setup(avctx);
142 pthread_mutex_lock(&p->mutex);
143 av_frame_unref(p->frame);
145 p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
147 if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
148 if (avctx->internal->allocate_progress)
149 av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
150 "free the frame on failure. This is a bug, please report it.\n");
151 av_frame_unref(p->frame);
154 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
156 p->state = STATE_INPUT_READY;
158 pthread_mutex_lock(&p->progress_mutex);
159 pthread_cond_signal(&p->output_cond);
160 pthread_mutex_unlock(&p->progress_mutex);
162 pthread_mutex_unlock(&p->mutex);
169 * Update the next thread's AVCodecContext with values from the reference thread's context.
171 * @param dst The destination context.
172 * @param src The source context.
173 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
175 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
180 dst->time_base = src->time_base;
181 dst->framerate = src->framerate;
182 dst->width = src->width;
183 dst->height = src->height;
184 dst->pix_fmt = src->pix_fmt;
186 dst->coded_width = src->coded_width;
187 dst->coded_height = src->coded_height;
189 dst->has_b_frames = src->has_b_frames;
190 dst->idct_algo = src->idct_algo;
192 dst->bits_per_coded_sample = src->bits_per_coded_sample;
193 dst->sample_aspect_ratio = src->sample_aspect_ratio;
195 FF_DISABLE_DEPRECATION_WARNINGS
196 dst->dtg_active_format = src->dtg_active_format;
197 FF_ENABLE_DEPRECATION_WARNINGS
198 #endif /* FF_API_AFD */
200 dst->profile = src->profile;
201 dst->level = src->level;
203 dst->bits_per_raw_sample = src->bits_per_raw_sample;
204 dst->ticks_per_frame = src->ticks_per_frame;
205 dst->color_primaries = src->color_primaries;
207 dst->color_trc = src->color_trc;
208 dst->colorspace = src->colorspace;
209 dst->color_range = src->color_range;
210 dst->chroma_sample_location = src->chroma_sample_location;
212 dst->hwaccel = src->hwaccel;
213 dst->hwaccel_context = src->hwaccel_context;
214 dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
218 dst->coded_frame = src->coded_frame;
220 if (dst->codec->update_thread_context)
221 err = dst->codec->update_thread_context(dst, src);
228 * Update the next thread's AVCodecContext with values set by the user.
230 * @param dst The destination context.
231 * @param src The source context.
232 * @return 0 on success, negative error code on failure
234 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
236 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
237 dst->flags = src->flags;
239 dst->draw_horiz_band= src->draw_horiz_band;
240 dst->get_buffer2 = src->get_buffer2;
241 #if FF_API_GET_BUFFER
242 FF_DISABLE_DEPRECATION_WARNINGS
243 dst->get_buffer = src->get_buffer;
244 dst->release_buffer = src->release_buffer;
245 FF_ENABLE_DEPRECATION_WARNINGS
248 dst->opaque = src->opaque;
249 dst->debug = src->debug;
251 dst->slice_flags = src->slice_flags;
252 dst->flags2 = src->flags2;
254 copy_fields(skip_loop_filter, subtitle_header);
256 dst->frame_number = src->frame_number;
257 dst->reordered_opaque = src->reordered_opaque;
259 if (src->slice_count && src->slice_offset) {
260 if (dst->slice_count < src->slice_count) {
261 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
262 sizeof(*dst->slice_offset));
264 av_free(dst->slice_offset);
265 return AVERROR(ENOMEM);
267 dst->slice_offset = tmp;
269 memcpy(dst->slice_offset, src->slice_offset,
270 src->slice_count * sizeof(*dst->slice_offset));
272 dst->slice_count = src->slice_count;
277 /// Releases the buffers that this decoding thread was the last user of.
278 static void release_delayed_buffers(PerThreadContext *p)
280 FrameThreadContext *fctx = p->parent;
282 while (p->num_released_buffers > 0) {
285 pthread_mutex_lock(&fctx->buffer_mutex);
287 // fix extended data in case the caller screwed it up
288 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
289 f = &p->released_buffers[--p->num_released_buffers];
290 f->extended_data = f->data;
293 pthread_mutex_unlock(&fctx->buffer_mutex);
297 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
299 FrameThreadContext *fctx = p->parent;
300 PerThreadContext *prev_thread = fctx->prev_thread;
301 const AVCodec *codec = p->avctx->codec;
303 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
305 pthread_mutex_lock(&p->mutex);
307 release_delayed_buffers(p);
311 if (prev_thread->state == STATE_SETTING_UP) {
312 pthread_mutex_lock(&prev_thread->progress_mutex);
313 while (prev_thread->state == STATE_SETTING_UP)
314 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
315 pthread_mutex_unlock(&prev_thread->progress_mutex);
318 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
320 pthread_mutex_unlock(&p->mutex);
325 av_packet_unref(&p->avpkt);
326 av_packet_ref(&p->avpkt, avpkt);
328 p->state = STATE_SETTING_UP;
329 pthread_cond_signal(&p->input_cond);
330 pthread_mutex_unlock(&p->mutex);
333 * If the client doesn't have a thread-safe get_buffer(),
334 * then decoding threads call back to the main thread,
335 * and it calls back to the client here.
338 FF_DISABLE_DEPRECATION_WARNINGS
339 if (!p->avctx->thread_safe_callbacks && (
340 #if FF_API_GET_BUFFER
341 p->avctx->get_buffer ||
343 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
344 FF_ENABLE_DEPRECATION_WARNINGS
345 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
346 pthread_mutex_lock(&p->progress_mutex);
347 while (p->state == STATE_SETTING_UP)
348 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
350 if (p->state == STATE_GET_BUFFER) {
351 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
352 p->state = STATE_SETTING_UP;
353 pthread_cond_signal(&p->progress_cond);
355 pthread_mutex_unlock(&p->progress_mutex);
359 fctx->prev_thread = p;
360 fctx->next_decoding++;
365 int ff_thread_decode_frame(AVCodecContext *avctx,
366 AVFrame *picture, int *got_picture_ptr,
369 FrameThreadContext *fctx = avctx->internal->thread_ctx;
370 int finished = fctx->next_finished;
375 * Submit a packet to the next decoding thread.
378 p = &fctx->threads[fctx->next_decoding];
379 err = update_context_from_user(p->avctx, avctx);
381 err = submit_packet(p, avpkt);
385 * If we're still receiving the initial packets, don't return a frame.
388 if (fctx->delaying) {
389 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
397 * Return the next available frame from the oldest thread.
398 * If we're at the end of the stream, then we have to skip threads that
399 * didn't output a frame, because we don't want to accidentally signal
400 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
404 p = &fctx->threads[finished++];
406 if (p->state != STATE_INPUT_READY) {
407 pthread_mutex_lock(&p->progress_mutex);
408 while (p->state != STATE_INPUT_READY)
409 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
410 pthread_mutex_unlock(&p->progress_mutex);
413 av_frame_move_ref(picture, p->frame);
414 *got_picture_ptr = p->got_frame;
415 picture->pkt_dts = p->avpkt.dts;
418 * A later call with avkpt->size == 0 may loop over all threads,
419 * including this one, searching for a frame to return before being
420 * stopped by the "finished != fctx->next_finished" condition.
421 * Make sure we don't mistakenly return the same frame again.
425 if (finished >= avctx->thread_count) finished = 0;
426 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
428 update_context_from_thread(avctx, p->avctx, 1);
430 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
432 fctx->next_finished = finished;
434 /* return the size of the consumed packet if no error occurred */
435 return (p->result >= 0) ? avpkt->size : p->result;
438 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
441 int *progress = f->progress ? (int*)f->progress->data : NULL;
443 if (!progress || progress[field] >= n) return;
445 p = f->owner->internal->thread_ctx;
447 if (f->owner->debug&FF_DEBUG_THREADS)
448 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
450 pthread_mutex_lock(&p->progress_mutex);
452 pthread_cond_broadcast(&p->progress_cond);
453 pthread_mutex_unlock(&p->progress_mutex);
456 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
459 int *progress = f->progress ? (int*)f->progress->data : NULL;
461 if (!progress || progress[field] >= n) return;
463 p = f->owner->internal->thread_ctx;
465 if (f->owner->debug&FF_DEBUG_THREADS)
466 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
468 pthread_mutex_lock(&p->progress_mutex);
469 while (progress[field] < n)
470 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
471 pthread_mutex_unlock(&p->progress_mutex);
474 void ff_thread_finish_setup(AVCodecContext *avctx) {
475 PerThreadContext *p = avctx->internal->thread_ctx;
477 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
479 pthread_mutex_lock(&p->progress_mutex);
480 p->state = STATE_SETUP_FINISHED;
481 pthread_cond_broadcast(&p->progress_cond);
482 pthread_mutex_unlock(&p->progress_mutex);
485 /// Waits for all threads to finish.
486 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
490 for (i = 0; i < thread_count; i++) {
491 PerThreadContext *p = &fctx->threads[i];
493 if (p->state != STATE_INPUT_READY) {
494 pthread_mutex_lock(&p->progress_mutex);
495 while (p->state != STATE_INPUT_READY)
496 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
497 pthread_mutex_unlock(&p->progress_mutex);
502 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
504 FrameThreadContext *fctx = avctx->internal->thread_ctx;
505 const AVCodec *codec = avctx->codec;
508 park_frame_worker_threads(fctx, thread_count);
510 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
511 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
515 for (i = 0; i < thread_count; i++) {
516 PerThreadContext *p = &fctx->threads[i];
518 pthread_mutex_lock(&p->mutex);
519 pthread_cond_signal(&p->input_cond);
520 pthread_mutex_unlock(&p->mutex);
523 pthread_join(p->thread, NULL);
526 codec->close(p->avctx);
530 release_delayed_buffers(p);
531 av_frame_free(&p->frame);
534 for (i = 0; i < thread_count; i++) {
535 PerThreadContext *p = &fctx->threads[i];
537 pthread_mutex_destroy(&p->mutex);
538 pthread_mutex_destroy(&p->progress_mutex);
539 pthread_cond_destroy(&p->input_cond);
540 pthread_cond_destroy(&p->progress_cond);
541 pthread_cond_destroy(&p->output_cond);
542 av_packet_unref(&p->avpkt);
543 av_freep(&p->released_buffers);
546 av_freep(&p->avctx->priv_data);
547 av_freep(&p->avctx->slice_offset);
550 av_freep(&p->avctx->internal);
554 av_freep(&fctx->threads);
555 pthread_mutex_destroy(&fctx->buffer_mutex);
556 av_freep(&avctx->internal->thread_ctx);
559 int ff_frame_thread_init(AVCodecContext *avctx)
561 int thread_count = avctx->thread_count;
562 const AVCodec *codec = avctx->codec;
563 AVCodecContext *src = avctx;
564 FrameThreadContext *fctx;
572 int nb_cpus = av_cpu_count();
573 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
574 // use number of cores + 1 as thread count if there is more than one
576 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
578 thread_count = avctx->thread_count = 1;
581 if (thread_count <= 1) {
582 avctx->active_thread_type = 0;
586 avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
588 return AVERROR(ENOMEM);
590 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
591 if (!fctx->threads) {
592 av_freep(&avctx->internal->thread_ctx);
593 return AVERROR(ENOMEM);
596 pthread_mutex_init(&fctx->buffer_mutex, NULL);
599 for (i = 0; i < thread_count; i++) {
600 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
601 PerThreadContext *p = &fctx->threads[i];
603 pthread_mutex_init(&p->mutex, NULL);
604 pthread_mutex_init(&p->progress_mutex, NULL);
605 pthread_cond_init(&p->input_cond, NULL);
606 pthread_cond_init(&p->progress_cond, NULL);
607 pthread_cond_init(&p->output_cond, NULL);
609 p->frame = av_frame_alloc();
612 err = AVERROR(ENOMEM);
620 err = AVERROR(ENOMEM);
626 copy->internal = av_malloc(sizeof(AVCodecInternal));
627 if (!copy->internal) {
628 err = AVERROR(ENOMEM);
631 *copy->internal = *src->internal;
632 copy->internal->thread_ctx = p;
633 copy->internal->pkt = &p->avpkt;
639 err = codec->init(copy);
641 update_context_from_thread(avctx, copy, 1);
643 copy->priv_data = av_malloc(codec->priv_data_size);
644 if (!copy->priv_data) {
645 err = AVERROR(ENOMEM);
648 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
649 copy->internal->is_copy = 1;
651 if (codec->init_thread_copy)
652 err = codec->init_thread_copy(copy);
657 if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
664 ff_frame_thread_free(avctx, i+1);
669 void ff_thread_flush(AVCodecContext *avctx)
672 FrameThreadContext *fctx = avctx->internal->thread_ctx;
676 park_frame_worker_threads(fctx, avctx->thread_count);
677 if (fctx->prev_thread) {
678 if (fctx->prev_thread != &fctx->threads[0])
679 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
682 fctx->next_decoding = fctx->next_finished = 0;
684 fctx->prev_thread = NULL;
685 for (i = 0; i < avctx->thread_count; i++) {
686 PerThreadContext *p = &fctx->threads[i];
687 // Make sure decode flush calls with size=0 won't return old frames
689 av_frame_unref(p->frame);
691 release_delayed_buffers(p);
693 if (avctx->codec->flush)
694 avctx->codec->flush(p->avctx);
698 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
700 PerThreadContext *p = avctx->internal->thread_ctx;
705 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
706 return ff_get_buffer(avctx, f->f, flags);
708 if (p->state != STATE_SETTING_UP &&
709 (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
710 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
714 if (avctx->internal->allocate_progress) {
716 f->progress = av_buffer_alloc(2 * sizeof(int));
718 return AVERROR(ENOMEM);
720 progress = (int*)f->progress->data;
722 progress[0] = progress[1] = -1;
725 pthread_mutex_lock(&p->parent->buffer_mutex);
726 FF_DISABLE_DEPRECATION_WARNINGS
727 if (avctx->thread_safe_callbacks || (
728 #if FF_API_GET_BUFFER
729 !avctx->get_buffer &&
731 avctx->get_buffer2 == avcodec_default_get_buffer2)) {
732 FF_ENABLE_DEPRECATION_WARNINGS
733 err = ff_get_buffer(avctx, f->f, flags);
735 p->requested_frame = f->f;
736 p->requested_flags = flags;
737 p->state = STATE_GET_BUFFER;
738 pthread_mutex_lock(&p->progress_mutex);
739 pthread_cond_signal(&p->progress_cond);
741 while (p->state != STATE_SETTING_UP)
742 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
746 pthread_mutex_unlock(&p->progress_mutex);
749 if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
750 ff_thread_finish_setup(avctx);
753 av_buffer_unref(&f->progress);
755 pthread_mutex_unlock(&p->parent->buffer_mutex);
760 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
762 PerThreadContext *p = avctx->internal->thread_ctx;
763 FrameThreadContext *fctx;
765 FF_DISABLE_DEPRECATION_WARNINGS
766 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
767 avctx->thread_safe_callbacks ||
769 #if FF_API_GET_BUFFER
770 !avctx->get_buffer &&
772 avctx->get_buffer2 == avcodec_default_get_buffer2);
773 FF_ENABLE_DEPRECATION_WARNINGS
775 if (!f->f || !f->f->buf[0])
778 if (avctx->debug & FF_DEBUG_BUFFERS)
779 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
781 av_buffer_unref(&f->progress);
784 if (can_direct_free) {
785 av_frame_unref(f->f);
790 pthread_mutex_lock(&fctx->buffer_mutex);
792 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
794 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
795 (p->num_released_buffers + 1) *
796 sizeof(*p->released_buffers));
799 p->released_buffers = tmp;
801 dst = &p->released_buffers[p->num_released_buffers];
802 av_frame_move_ref(dst, f->f);
804 p->num_released_buffers++;
807 pthread_mutex_unlock(&fctx->buffer_mutex);