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"
40 #include "libavutil/avassert.h"
41 #include "libavutil/buffer.h"
42 #include "libavutil/common.h"
43 #include "libavutil/cpu.h"
44 #include "libavutil/frame.h"
45 #include "libavutil/log.h"
46 #include "libavutil/mem.h"
49 * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
51 typedef struct PerThreadContext {
52 struct FrameThreadContext *parent;
56 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
57 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
58 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
60 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
61 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
63 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
65 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
66 uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
67 int allocated_buf_size; ///< Size allocated for buf
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 avcodec_get_frame_defaults(&p->frame);
145 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
147 /* many decoders assign whole AVFrames, thus overwriting extended_data;
148 * make sure it's set correctly */
149 p->frame.extended_data = p->frame.data;
151 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
153 p->state = STATE_INPUT_READY;
155 pthread_mutex_lock(&p->progress_mutex);
156 pthread_cond_signal(&p->output_cond);
157 pthread_mutex_unlock(&p->progress_mutex);
159 pthread_mutex_unlock(&p->mutex);
166 * Update the next thread's AVCodecContext with values from the reference thread's context.
168 * @param dst The destination context.
169 * @param src The source context.
170 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
172 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
177 dst->time_base = src->time_base;
178 dst->width = src->width;
179 dst->height = src->height;
180 dst->pix_fmt = src->pix_fmt;
182 dst->coded_width = src->coded_width;
183 dst->coded_height = src->coded_height;
185 dst->has_b_frames = src->has_b_frames;
186 dst->idct_algo = src->idct_algo;
188 dst->bits_per_coded_sample = src->bits_per_coded_sample;
189 dst->sample_aspect_ratio = src->sample_aspect_ratio;
190 dst->dtg_active_format = src->dtg_active_format;
192 dst->profile = src->profile;
193 dst->level = src->level;
195 dst->bits_per_raw_sample = src->bits_per_raw_sample;
196 dst->ticks_per_frame = src->ticks_per_frame;
197 dst->color_primaries = src->color_primaries;
199 dst->color_trc = src->color_trc;
200 dst->colorspace = src->colorspace;
201 dst->color_range = src->color_range;
202 dst->chroma_sample_location = src->chroma_sample_location;
204 dst->hwaccel = src->hwaccel;
205 dst->hwaccel_context = src->hwaccel_context;
209 dst->coded_frame = src->coded_frame;
211 if (dst->codec->update_thread_context)
212 err = dst->codec->update_thread_context(dst, src);
219 * Update the next thread's AVCodecContext with values set by the user.
221 * @param dst The destination context.
222 * @param src The source context.
223 * @return 0 on success, negative error code on failure
225 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
227 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
228 dst->flags = src->flags;
230 dst->draw_horiz_band= src->draw_horiz_band;
231 dst->get_buffer2 = src->get_buffer2;
232 #if FF_API_GET_BUFFER
233 FF_DISABLE_DEPRECATION_WARNINGS
234 dst->get_buffer = src->get_buffer;
235 dst->release_buffer = src->release_buffer;
236 FF_ENABLE_DEPRECATION_WARNINGS
239 dst->opaque = src->opaque;
240 dst->debug = src->debug;
242 dst->slice_flags = src->slice_flags;
243 dst->flags2 = src->flags2;
245 copy_fields(skip_loop_filter, subtitle_header);
247 dst->frame_number = src->frame_number;
248 dst->reordered_opaque = src->reordered_opaque;
250 if (src->slice_count && src->slice_offset) {
251 if (dst->slice_count < src->slice_count) {
252 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
253 sizeof(*dst->slice_offset));
255 av_free(dst->slice_offset);
256 return AVERROR(ENOMEM);
258 dst->slice_offset = tmp;
260 memcpy(dst->slice_offset, src->slice_offset,
261 src->slice_count * sizeof(*dst->slice_offset));
263 dst->slice_count = src->slice_count;
268 /// Releases the buffers that this decoding thread was the last user of.
269 static void release_delayed_buffers(PerThreadContext *p)
271 FrameThreadContext *fctx = p->parent;
273 while (p->num_released_buffers > 0) {
276 pthread_mutex_lock(&fctx->buffer_mutex);
278 // fix extended data in case the caller screwed it up
279 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
280 f = &p->released_buffers[--p->num_released_buffers];
281 f->extended_data = f->data;
284 pthread_mutex_unlock(&fctx->buffer_mutex);
288 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
290 FrameThreadContext *fctx = p->parent;
291 PerThreadContext *prev_thread = fctx->prev_thread;
292 const AVCodec *codec = p->avctx->codec;
294 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
296 pthread_mutex_lock(&p->mutex);
298 release_delayed_buffers(p);
302 if (prev_thread->state == STATE_SETTING_UP) {
303 pthread_mutex_lock(&prev_thread->progress_mutex);
304 while (prev_thread->state == STATE_SETTING_UP)
305 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
306 pthread_mutex_unlock(&prev_thread->progress_mutex);
309 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
311 pthread_mutex_unlock(&p->mutex);
316 av_buffer_unref(&p->avpkt.buf);
319 p->avpkt.buf = av_buffer_ref(avpkt->buf);
321 av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
322 p->avpkt.data = p->buf;
323 memcpy(p->buf, avpkt->data, avpkt->size);
324 memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
327 p->state = STATE_SETTING_UP;
328 pthread_cond_signal(&p->input_cond);
329 pthread_mutex_unlock(&p->mutex);
332 * If the client doesn't have a thread-safe get_buffer(),
333 * then decoding threads call back to the main thread,
334 * and it calls back to the client here.
337 FF_DISABLE_DEPRECATION_WARNINGS
338 if (!p->avctx->thread_safe_callbacks && (
339 #if FF_API_GET_BUFFER
340 p->avctx->get_buffer ||
342 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
343 FF_ENABLE_DEPRECATION_WARNINGS
344 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
345 pthread_mutex_lock(&p->progress_mutex);
346 while (p->state == STATE_SETTING_UP)
347 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
349 if (p->state == STATE_GET_BUFFER) {
350 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
351 p->state = STATE_SETTING_UP;
352 pthread_cond_signal(&p->progress_cond);
354 pthread_mutex_unlock(&p->progress_mutex);
358 fctx->prev_thread = p;
359 fctx->next_decoding++;
364 int ff_thread_decode_frame(AVCodecContext *avctx,
365 AVFrame *picture, int *got_picture_ptr,
368 FrameThreadContext *fctx = avctx->internal->thread_ctx;
369 int finished = fctx->next_finished;
374 * Submit a packet to the next decoding thread.
377 p = &fctx->threads[fctx->next_decoding];
378 err = update_context_from_user(p->avctx, avctx);
380 err = submit_packet(p, avpkt);
384 * If we're still receiving the initial packets, don't return a frame.
387 if (fctx->delaying) {
388 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
396 * Return the next available frame from the oldest thread.
397 * If we're at the end of the stream, then we have to skip threads that
398 * didn't output a frame, because we don't want to accidentally signal
399 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
403 p = &fctx->threads[finished++];
405 if (p->state != STATE_INPUT_READY) {
406 pthread_mutex_lock(&p->progress_mutex);
407 while (p->state != STATE_INPUT_READY)
408 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
409 pthread_mutex_unlock(&p->progress_mutex);
412 av_frame_move_ref(picture, &p->frame);
413 *got_picture_ptr = p->got_frame;
414 picture->pkt_dts = p->avpkt.dts;
417 * A later call with avkpt->size == 0 may loop over all threads,
418 * including this one, searching for a frame to return before being
419 * stopped by the "finished != fctx->next_finished" condition.
420 * Make sure we don't mistakenly return the same frame again.
424 if (finished >= avctx->thread_count) finished = 0;
425 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
427 update_context_from_thread(avctx, p->avctx, 1);
429 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
431 fctx->next_finished = finished;
433 /* return the size of the consumed packet if no error occurred */
434 return (p->result >= 0) ? avpkt->size : p->result;
437 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
440 int *progress = f->progress ? (int*)f->progress->data : NULL;
442 if (!progress || progress[field] >= n) return;
444 p = f->owner->internal->thread_ctx;
446 if (f->owner->debug&FF_DEBUG_THREADS)
447 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
449 pthread_mutex_lock(&p->progress_mutex);
451 pthread_cond_broadcast(&p->progress_cond);
452 pthread_mutex_unlock(&p->progress_mutex);
455 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
458 int *progress = f->progress ? (int*)f->progress->data : NULL;
460 if (!progress || progress[field] >= n) return;
462 p = f->owner->internal->thread_ctx;
464 if (f->owner->debug&FF_DEBUG_THREADS)
465 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
467 pthread_mutex_lock(&p->progress_mutex);
468 while (progress[field] < n)
469 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
470 pthread_mutex_unlock(&p->progress_mutex);
473 void ff_thread_finish_setup(AVCodecContext *avctx) {
474 PerThreadContext *p = avctx->internal->thread_ctx;
476 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
478 pthread_mutex_lock(&p->progress_mutex);
479 p->state = STATE_SETUP_FINISHED;
480 pthread_cond_broadcast(&p->progress_cond);
481 pthread_mutex_unlock(&p->progress_mutex);
484 /// Waits for all threads to finish.
485 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
489 for (i = 0; i < thread_count; i++) {
490 PerThreadContext *p = &fctx->threads[i];
492 if (p->state != STATE_INPUT_READY) {
493 pthread_mutex_lock(&p->progress_mutex);
494 while (p->state != STATE_INPUT_READY)
495 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
496 pthread_mutex_unlock(&p->progress_mutex);
501 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
503 FrameThreadContext *fctx = avctx->internal->thread_ctx;
504 const AVCodec *codec = avctx->codec;
507 park_frame_worker_threads(fctx, thread_count);
509 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
510 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
514 for (i = 0; i < thread_count; i++) {
515 PerThreadContext *p = &fctx->threads[i];
517 pthread_mutex_lock(&p->mutex);
518 pthread_cond_signal(&p->input_cond);
519 pthread_mutex_unlock(&p->mutex);
522 pthread_join(p->thread, NULL);
525 codec->close(p->avctx);
529 release_delayed_buffers(p);
530 av_frame_unref(&p->frame);
533 for (i = 0; i < thread_count; i++) {
534 PerThreadContext *p = &fctx->threads[i];
536 pthread_mutex_destroy(&p->mutex);
537 pthread_mutex_destroy(&p->progress_mutex);
538 pthread_cond_destroy(&p->input_cond);
539 pthread_cond_destroy(&p->progress_cond);
540 pthread_cond_destroy(&p->output_cond);
541 av_buffer_unref(&p->avpkt.buf);
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 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
589 pthread_mutex_init(&fctx->buffer_mutex, NULL);
592 for (i = 0; i < thread_count; i++) {
593 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
594 PerThreadContext *p = &fctx->threads[i];
596 pthread_mutex_init(&p->mutex, NULL);
597 pthread_mutex_init(&p->progress_mutex, NULL);
598 pthread_cond_init(&p->input_cond, NULL);
599 pthread_cond_init(&p->progress_cond, NULL);
600 pthread_cond_init(&p->output_cond, NULL);
606 err = AVERROR(ENOMEM);
611 copy->pkt = &p->avpkt;
613 copy->internal = av_malloc(sizeof(AVCodecInternal));
614 if (!copy->internal) {
615 err = AVERROR(ENOMEM);
618 *copy->internal = *src->internal;
619 copy->internal->thread_ctx = p;
625 err = codec->init(copy);
627 update_context_from_thread(avctx, copy, 1);
629 copy->priv_data = av_malloc(codec->priv_data_size);
630 if (!copy->priv_data) {
631 err = AVERROR(ENOMEM);
634 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
635 copy->internal->is_copy = 1;
637 if (codec->init_thread_copy)
638 err = codec->init_thread_copy(copy);
643 if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
650 ff_frame_thread_free(avctx, i+1);
655 void ff_thread_flush(AVCodecContext *avctx)
658 FrameThreadContext *fctx = avctx->internal->thread_ctx;
662 park_frame_worker_threads(fctx, avctx->thread_count);
663 if (fctx->prev_thread) {
664 if (fctx->prev_thread != &fctx->threads[0])
665 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
666 if (avctx->codec->flush)
667 avctx->codec->flush(fctx->threads[0].avctx);
670 fctx->next_decoding = fctx->next_finished = 0;
672 fctx->prev_thread = NULL;
673 for (i = 0; i < avctx->thread_count; i++) {
674 PerThreadContext *p = &fctx->threads[i];
675 // Make sure decode flush calls with size=0 won't return old frames
677 av_frame_unref(&p->frame);
679 release_delayed_buffers(p);
683 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
685 PerThreadContext *p = avctx->internal->thread_ctx;
690 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
691 return ff_get_buffer(avctx, f->f, flags);
693 if (p->state != STATE_SETTING_UP &&
694 (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
695 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
699 if (avctx->internal->allocate_progress) {
701 f->progress = av_buffer_alloc(2 * sizeof(int));
703 return AVERROR(ENOMEM);
705 progress = (int*)f->progress->data;
707 progress[0] = progress[1] = -1;
710 pthread_mutex_lock(&p->parent->buffer_mutex);
711 FF_DISABLE_DEPRECATION_WARNINGS
712 if (avctx->thread_safe_callbacks || (
713 #if FF_API_GET_BUFFER
714 !avctx->get_buffer &&
716 avctx->get_buffer2 == avcodec_default_get_buffer2)) {
717 FF_ENABLE_DEPRECATION_WARNINGS
718 err = ff_get_buffer(avctx, f->f, flags);
720 p->requested_frame = f->f;
721 p->requested_flags = flags;
722 p->state = STATE_GET_BUFFER;
723 pthread_mutex_lock(&p->progress_mutex);
724 pthread_cond_signal(&p->progress_cond);
726 while (p->state != STATE_SETTING_UP)
727 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
731 pthread_mutex_unlock(&p->progress_mutex);
734 if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
735 ff_thread_finish_setup(avctx);
738 av_buffer_unref(&f->progress);
740 pthread_mutex_unlock(&p->parent->buffer_mutex);
745 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
747 PerThreadContext *p = avctx->internal->thread_ctx;
748 FrameThreadContext *fctx;
750 FF_DISABLE_DEPRECATION_WARNINGS
751 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
752 avctx->thread_safe_callbacks ||
754 #if FF_API_GET_BUFFER
755 !avctx->get_buffer &&
757 avctx->get_buffer2 == avcodec_default_get_buffer2);
758 FF_ENABLE_DEPRECATION_WARNINGS
763 if (avctx->debug & FF_DEBUG_BUFFERS)
764 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
766 av_buffer_unref(&f->progress);
769 if (can_direct_free) {
770 av_frame_unref(f->f);
775 pthread_mutex_lock(&fctx->buffer_mutex);
777 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
779 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
780 (p->num_released_buffers + 1) *
781 sizeof(*p->released_buffers));
784 p->released_buffers = tmp;
786 dst = &p->released_buffers[p->num_released_buffers];
787 av_frame_move_ref(dst, f->f);
789 p->num_released_buffers++;
792 pthread_mutex_unlock(&fctx->buffer_mutex);