2 * Copyright (c) 2004 Roman Shaposhnik
3 * Copyright (c) 2008 Alexander Strange (astrange@ithinksw.com)
5 * Many thanks to Steven M. Schultz for providing clever ideas and
6 * to Michael Niedermayer <michaelni@gmx.at> for writing initial
9 * This file is part of FFmpeg.
11 * FFmpeg is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * FFmpeg is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with FFmpeg; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 * Multithreading support functions
29 * @see doc/multithreading.txt
37 #include "libavutil/avassert.h"
38 #include "libavutil/common.h"
39 #include "libavutil/cpu.h"
40 #include "libavutil/internal.h"
45 #include "compat/w32pthreads.h"
47 #include "compat/os2threads.h"
50 typedef int (action_func)(AVCodecContext *c, void *arg);
51 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
53 typedef struct ThreadContext {
63 pthread_cond_t last_job_cond;
64 pthread_cond_t current_job_cond;
65 pthread_mutex_t current_job_lock;
67 unsigned int current_execute;
72 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
74 typedef struct PerThreadContext {
75 struct FrameThreadContext *parent;
79 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
80 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
81 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
83 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
84 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
86 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
88 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
89 uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
90 int allocated_buf_size; ///< Size allocated for buf
92 AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
93 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
94 int result; ///< The result of the last codec decode/encode() call.
97 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
98 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
99 STATE_GET_BUFFER, /**<
100 * Set when the codec calls get_buffer().
101 * State is returned to STATE_SETTING_UP afterwards.
103 STATE_GET_FORMAT, /**<
104 * Set when the codec calls get_format().
105 * State is returned to STATE_SETTING_UP afterwards.
107 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
111 * Array of frames passed to ff_thread_release_buffer().
112 * Frames are released after all threads referencing them are finished.
114 AVFrame *released_buffers;
115 int num_released_buffers;
116 int released_buffers_allocated;
118 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
119 int requested_flags; ///< flags passed to get_buffer() for requested_frame
121 const enum AVPixelFormat *available_formats; ///< Format array for get_format()
122 enum AVPixelFormat result_format; ///< get_format() result
126 * Context stored in the client AVCodecContext thread_opaque.
128 typedef struct FrameThreadContext {
129 PerThreadContext *threads; ///< The contexts for each thread.
130 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
132 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
134 int next_decoding; ///< The next context to submit a packet to.
135 int next_finished; ///< The next context to return output from.
138 * Set for the first N packets, where N is the number of threads.
139 * While it is set, ff_thread_en/decode_frame won't return any results.
142 int die; ///< Set when threads should exit.
143 } FrameThreadContext;
146 /* H264 slice threading seems to be buggy with more than 16 threads,
147 * limit the number of threads to 16 for automatic detection */
148 #define MAX_AUTO_THREADS 16
150 static void* attribute_align_arg worker(void *v)
152 AVCodecContext *avctx = v;
153 ThreadContext *c = avctx->thread_opaque;
154 int our_job = c->job_count;
155 int last_execute = 0;
156 int thread_count = avctx->thread_count;
159 pthread_mutex_lock(&c->current_job_lock);
160 self_id = c->current_job++;
162 while (our_job >= c->job_count) {
163 if (c->current_job == thread_count + c->job_count)
164 pthread_cond_signal(&c->last_job_cond);
166 while (last_execute == c->current_execute && !c->done)
167 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
168 last_execute = c->current_execute;
172 pthread_mutex_unlock(&c->current_job_lock);
176 pthread_mutex_unlock(&c->current_job_lock);
178 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
179 c->func2(avctx, c->args, our_job, self_id);
181 pthread_mutex_lock(&c->current_job_lock);
182 our_job = c->current_job++;
186 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
188 while (c->current_job != thread_count + c->job_count)
189 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
190 pthread_mutex_unlock(&c->current_job_lock);
193 static void thread_free(AVCodecContext *avctx)
195 ThreadContext *c = avctx->thread_opaque;
198 pthread_mutex_lock(&c->current_job_lock);
200 pthread_cond_broadcast(&c->current_job_cond);
201 pthread_mutex_unlock(&c->current_job_lock);
203 for (i=0; i<avctx->thread_count; i++)
204 pthread_join(c->workers[i], NULL);
206 pthread_mutex_destroy(&c->current_job_lock);
207 pthread_cond_destroy(&c->current_job_cond);
208 pthread_cond_destroy(&c->last_job_cond);
210 av_freep(&avctx->thread_opaque);
213 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
215 ThreadContext *c= avctx->thread_opaque;
218 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
219 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
224 pthread_mutex_lock(&c->current_job_lock);
226 c->current_job = avctx->thread_count;
227 c->job_count = job_count;
228 c->job_size = job_size;
233 c->rets_count = job_count;
235 c->rets = &dummy_ret;
238 c->current_execute++;
239 pthread_cond_broadcast(&c->current_job_cond);
241 avcodec_thread_park_workers(c, avctx->thread_count);
246 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
248 ThreadContext *c= avctx->thread_opaque;
250 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
253 static int thread_init_internal(AVCodecContext *avctx)
257 int thread_count = avctx->thread_count;
260 int nb_cpus = av_cpu_count();
262 nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
263 // use number of cores + 1 as thread count if there is more than one
265 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
267 thread_count = avctx->thread_count = 1;
270 if (thread_count <= 1) {
271 avctx->active_thread_type = 0;
275 c = av_mallocz(sizeof(ThreadContext));
279 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
285 avctx->thread_opaque = c;
290 pthread_cond_init(&c->current_job_cond, NULL);
291 pthread_cond_init(&c->last_job_cond, NULL);
292 pthread_mutex_init(&c->current_job_lock, NULL);
293 pthread_mutex_lock(&c->current_job_lock);
294 for (i=0; i<thread_count; i++) {
295 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
296 avctx->thread_count = i;
297 pthread_mutex_unlock(&c->current_job_lock);
298 ff_thread_free(avctx);
303 avcodec_thread_park_workers(c, thread_count);
305 avctx->execute = avcodec_thread_execute;
306 avctx->execute2 = avcodec_thread_execute2;
310 #define THREAD_SAFE_CALLBACKS(avctx) \
311 ((avctx)->thread_safe_callbacks || (!(avctx)->get_buffer && (avctx)->get_buffer2 == avcodec_default_get_buffer2))
314 * Codec worker thread.
316 * Automatically calls ff_thread_finish_setup() if the codec does
317 * not provide an update_thread_context method, or if the codec returns
320 static attribute_align_arg void *frame_worker_thread(void *arg)
322 PerThreadContext *p = arg;
323 FrameThreadContext *fctx = p->parent;
324 AVCodecContext *avctx = p->avctx;
325 const AVCodec *codec = avctx->codec;
327 pthread_mutex_lock(&p->mutex);
329 while (p->state == STATE_INPUT_READY && !fctx->die)
330 pthread_cond_wait(&p->input_cond, &p->mutex);
332 if (fctx->die) break;
334 if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
335 ff_thread_finish_setup(avctx);
337 avcodec_get_frame_defaults(&p->frame);
339 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
341 /* many decoders assign whole AVFrames, thus overwriting extended_data;
342 * make sure it's set correctly */
343 p->frame.extended_data = p->frame.data;
345 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
347 pthread_mutex_lock(&p->progress_mutex);
349 for (i = 0; i < MAX_BUFFERS; i++)
350 if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
351 p->progress[i][0] = INT_MAX;
352 p->progress[i][1] = INT_MAX;
355 p->state = STATE_INPUT_READY;
357 pthread_cond_broadcast(&p->progress_cond);
358 pthread_cond_signal(&p->output_cond);
359 pthread_mutex_unlock(&p->progress_mutex);
361 pthread_mutex_unlock(&p->mutex);
367 * Update the next thread's AVCodecContext with values from the reference thread's context.
369 * @param dst The destination context.
370 * @param src The source context.
371 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
373 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
378 dst->time_base = src->time_base;
379 dst->width = src->width;
380 dst->height = src->height;
381 dst->pix_fmt = src->pix_fmt;
383 dst->coded_width = src->coded_width;
384 dst->coded_height = src->coded_height;
386 dst->has_b_frames = src->has_b_frames;
387 dst->idct_algo = src->idct_algo;
389 dst->bits_per_coded_sample = src->bits_per_coded_sample;
390 dst->sample_aspect_ratio = src->sample_aspect_ratio;
391 dst->dtg_active_format = src->dtg_active_format;
393 dst->profile = src->profile;
394 dst->level = src->level;
396 dst->bits_per_raw_sample = src->bits_per_raw_sample;
397 dst->ticks_per_frame = src->ticks_per_frame;
398 dst->color_primaries = src->color_primaries;
400 dst->color_trc = src->color_trc;
401 dst->colorspace = src->colorspace;
402 dst->color_range = src->color_range;
403 dst->chroma_sample_location = src->chroma_sample_location;
405 dst->hwaccel = src->hwaccel;
406 dst->hwaccel_context = src->hwaccel_context;
408 dst->channels = src->channels;
409 dst->sample_rate = src->sample_rate;
410 dst->sample_fmt = src->sample_fmt;
411 dst->channel_layout = src->channel_layout;
415 dst->delay = src->thread_count - 1;
416 dst->coded_frame = src->coded_frame;
418 if (dst->codec->update_thread_context)
419 err = dst->codec->update_thread_context(dst, src);
426 * Update the next thread's AVCodecContext with values set by the user.
428 * @param dst The destination context.
429 * @param src The source context.
430 * @return 0 on success, negative error code on failure
432 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
434 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
435 dst->flags = src->flags;
437 dst->draw_horiz_band= src->draw_horiz_band;
438 dst->get_buffer2 = src->get_buffer2;
439 #if FF_API_GET_BUFFER
440 FF_DISABLE_DEPRECATION_WARNINGS
441 dst->get_buffer = src->get_buffer;
442 dst->release_buffer = src->release_buffer;
443 FF_ENABLE_DEPRECATION_WARNINGS
446 dst->opaque = src->opaque;
447 dst->debug = src->debug;
448 dst->debug_mv = src->debug_mv;
450 dst->slice_flags = src->slice_flags;
451 dst->flags2 = src->flags2;
453 copy_fields(skip_loop_filter, subtitle_header);
455 dst->frame_number = src->frame_number;
456 dst->reordered_opaque = src->reordered_opaque;
457 dst->thread_safe_callbacks = src->thread_safe_callbacks;
459 if (src->slice_count && src->slice_offset) {
460 if (dst->slice_count < src->slice_count) {
461 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
462 sizeof(*dst->slice_offset));
464 av_free(dst->slice_offset);
465 return AVERROR(ENOMEM);
467 dst->slice_offset = tmp;
469 memcpy(dst->slice_offset, src->slice_offset,
470 src->slice_count * sizeof(*dst->slice_offset));
472 dst->slice_count = src->slice_count;
477 /// Releases the buffers that this decoding thread was the last user of.
478 static void release_delayed_buffers(PerThreadContext *p)
480 FrameThreadContext *fctx = p->parent;
482 while (p->num_released_buffers > 0) {
485 pthread_mutex_lock(&fctx->buffer_mutex);
487 // fix extended data in case the caller screwed it up
488 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
489 p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
490 f = &p->released_buffers[--p->num_released_buffers];
491 f->extended_data = f->data;
494 pthread_mutex_unlock(&fctx->buffer_mutex);
498 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
500 FrameThreadContext *fctx = p->parent;
501 PerThreadContext *prev_thread = fctx->prev_thread;
502 const AVCodec *codec = p->avctx->codec;
504 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
506 pthread_mutex_lock(&p->mutex);
508 release_delayed_buffers(p);
512 if (prev_thread->state == STATE_SETTING_UP) {
513 pthread_mutex_lock(&prev_thread->progress_mutex);
514 while (prev_thread->state == STATE_SETTING_UP)
515 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
516 pthread_mutex_unlock(&prev_thread->progress_mutex);
519 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
521 pthread_mutex_unlock(&p->mutex);
526 av_buffer_unref(&p->avpkt.buf);
529 p->avpkt.buf = av_buffer_ref(avpkt->buf);
531 av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
532 p->avpkt.data = p->buf;
533 memcpy(p->buf, avpkt->data, avpkt->size);
534 memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
537 p->state = STATE_SETTING_UP;
538 pthread_cond_signal(&p->input_cond);
539 pthread_mutex_unlock(&p->mutex);
542 * If the client doesn't have a thread-safe get_buffer(),
543 * then decoding threads call back to the main thread,
544 * and it calls back to the client here.
547 FF_DISABLE_DEPRECATION_WARNINGS
548 if (!p->avctx->thread_safe_callbacks && (
549 p->avctx->get_format != avcodec_default_get_format ||
550 #if FF_API_GET_BUFFER
551 p->avctx->get_buffer ||
553 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
554 FF_ENABLE_DEPRECATION_WARNINGS
555 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
557 pthread_mutex_lock(&p->progress_mutex);
558 while (p->state == STATE_SETTING_UP)
559 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
562 case STATE_GET_BUFFER:
563 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
565 case STATE_GET_FORMAT:
566 p->result_format = p->avctx->get_format(p->avctx, p->available_formats);
573 p->state = STATE_SETTING_UP;
574 pthread_cond_signal(&p->progress_cond);
576 pthread_mutex_unlock(&p->progress_mutex);
580 fctx->prev_thread = p;
581 fctx->next_decoding++;
586 int ff_thread_decode_frame(AVCodecContext *avctx,
587 AVFrame *picture, int *got_picture_ptr,
590 FrameThreadContext *fctx = avctx->thread_opaque;
591 int finished = fctx->next_finished;
596 * Submit a packet to the next decoding thread.
599 p = &fctx->threads[fctx->next_decoding];
600 err = update_context_from_user(p->avctx, avctx);
602 err = submit_packet(p, avpkt);
606 * If we're still receiving the initial packets, don't return a frame.
609 if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
612 if (fctx->delaying) {
619 * Return the next available frame from the oldest thread.
620 * If we're at the end of the stream, then we have to skip threads that
621 * didn't output a frame, because we don't want to accidentally signal
622 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
626 p = &fctx->threads[finished++];
628 if (p->state != STATE_INPUT_READY) {
629 pthread_mutex_lock(&p->progress_mutex);
630 while (p->state != STATE_INPUT_READY)
631 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
632 pthread_mutex_unlock(&p->progress_mutex);
635 av_frame_move_ref(picture, &p->frame);
636 *got_picture_ptr = p->got_frame;
637 picture->pkt_dts = p->avpkt.dts;
640 * A later call with avkpt->size == 0 may loop over all threads,
641 * including this one, searching for a frame to return before being
642 * stopped by the "finished != fctx->next_finished" condition.
643 * Make sure we don't mistakenly return the same frame again.
647 if (finished >= avctx->thread_count) finished = 0;
648 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
650 update_context_from_thread(avctx, p->avctx, 1);
652 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
654 fctx->next_finished = finished;
656 /* return the size of the consumed packet if no error occurred */
657 return (p->result >= 0) ? avpkt->size : p->result;
660 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
663 volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
665 if (!progress || progress[field] >= n) return;
667 p = f->owner->thread_opaque;
669 if (f->owner->debug&FF_DEBUG_THREADS)
670 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
672 pthread_mutex_lock(&p->progress_mutex);
674 pthread_cond_broadcast(&p->progress_cond);
675 pthread_mutex_unlock(&p->progress_mutex);
678 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
681 volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
683 if (!progress || progress[field] >= n) return;
685 p = f->owner->thread_opaque;
687 if (f->owner->debug&FF_DEBUG_THREADS)
688 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
690 pthread_mutex_lock(&p->progress_mutex);
691 while (progress[field] < n)
692 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
693 pthread_mutex_unlock(&p->progress_mutex);
696 void ff_thread_finish_setup(AVCodecContext *avctx) {
697 PerThreadContext *p = avctx->thread_opaque;
699 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
701 if(p->state == STATE_SETUP_FINISHED){
702 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
705 pthread_mutex_lock(&p->progress_mutex);
706 p->state = STATE_SETUP_FINISHED;
707 pthread_cond_broadcast(&p->progress_cond);
708 pthread_mutex_unlock(&p->progress_mutex);
711 /// Waits for all threads to finish.
712 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
716 for (i = 0; i < thread_count; i++) {
717 PerThreadContext *p = &fctx->threads[i];
719 if (p->state != STATE_INPUT_READY) {
720 pthread_mutex_lock(&p->progress_mutex);
721 while (p->state != STATE_INPUT_READY)
722 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
723 pthread_mutex_unlock(&p->progress_mutex);
729 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
731 FrameThreadContext *fctx = avctx->thread_opaque;
732 const AVCodec *codec = avctx->codec;
735 park_frame_worker_threads(fctx, thread_count);
737 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
738 if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
739 av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
740 fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
741 fctx->threads->avctx->internal->is_copy = 1;
746 for (i = 0; i < thread_count; i++) {
747 PerThreadContext *p = &fctx->threads[i];
749 pthread_mutex_lock(&p->mutex);
750 pthread_cond_signal(&p->input_cond);
751 pthread_mutex_unlock(&p->mutex);
754 pthread_join(p->thread, NULL);
758 codec->close(p->avctx);
762 release_delayed_buffers(p);
763 av_frame_unref(&p->frame);
766 for (i = 0; i < thread_count; i++) {
767 PerThreadContext *p = &fctx->threads[i];
769 pthread_mutex_destroy(&p->mutex);
770 pthread_mutex_destroy(&p->progress_mutex);
771 pthread_cond_destroy(&p->input_cond);
772 pthread_cond_destroy(&p->progress_cond);
773 pthread_cond_destroy(&p->output_cond);
774 av_buffer_unref(&p->avpkt.buf);
776 av_freep(&p->released_buffers);
779 av_freep(&p->avctx->priv_data);
780 av_freep(&p->avctx->internal);
781 av_freep(&p->avctx->slice_offset);
787 av_freep(&fctx->threads);
788 pthread_mutex_destroy(&fctx->buffer_mutex);
789 av_freep(&avctx->thread_opaque);
792 static int frame_thread_init(AVCodecContext *avctx)
794 int thread_count = avctx->thread_count;
795 const AVCodec *codec = avctx->codec;
796 AVCodecContext *src = avctx;
797 FrameThreadContext *fctx;
801 int nb_cpus = av_cpu_count();
802 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
804 // use number of cores + 1 as thread count if there is more than one
806 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
808 thread_count = avctx->thread_count = 1;
811 if (thread_count <= 1) {
812 avctx->active_thread_type = 0;
816 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
818 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
819 pthread_mutex_init(&fctx->buffer_mutex, NULL);
822 for (i = 0; i < thread_count; i++) {
823 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
824 PerThreadContext *p = &fctx->threads[i];
826 pthread_mutex_init(&p->mutex, NULL);
827 pthread_mutex_init(&p->progress_mutex, NULL);
828 pthread_cond_init(&p->input_cond, NULL);
829 pthread_cond_init(&p->progress_cond, NULL);
830 pthread_cond_init(&p->output_cond, NULL);
836 err = AVERROR(ENOMEM);
841 copy->thread_opaque = p;
842 copy->pkt = &p->avpkt;
848 err = codec->init(copy);
850 update_context_from_thread(avctx, copy, 1);
852 copy->priv_data = av_malloc(codec->priv_data_size);
853 if (!copy->priv_data) {
854 err = AVERROR(ENOMEM);
857 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
858 copy->internal = av_malloc(sizeof(AVCodecInternal));
859 if (!copy->internal) {
860 err = AVERROR(ENOMEM);
863 *copy->internal = *src->internal;
864 copy->internal->is_copy = 1;
866 if (codec->init_thread_copy)
867 err = codec->init_thread_copy(copy);
872 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
873 p->thread_init= !err;
881 frame_thread_free(avctx, i+1);
886 void ff_thread_flush(AVCodecContext *avctx)
889 FrameThreadContext *fctx = avctx->thread_opaque;
891 if (!avctx->thread_opaque) return;
893 park_frame_worker_threads(fctx, avctx->thread_count);
894 if (fctx->prev_thread) {
895 if (fctx->prev_thread != &fctx->threads[0])
896 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
897 if (avctx->codec->flush)
898 avctx->codec->flush(fctx->threads[0].avctx);
901 fctx->next_decoding = fctx->next_finished = 0;
903 fctx->prev_thread = NULL;
904 for (i = 0; i < avctx->thread_count; i++) {
905 PerThreadContext *p = &fctx->threads[i];
906 // Make sure decode flush calls with size=0 won't return old frames
908 av_frame_unref(&p->frame);
910 release_delayed_buffers(p);
914 int ff_thread_can_start_frame(AVCodecContext *avctx)
916 PerThreadContext *p = avctx->thread_opaque;
917 if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
918 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
924 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
926 PerThreadContext *p = avctx->thread_opaque;
931 ff_init_buffer_info(avctx, f->f);
933 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
934 return ff_get_buffer(avctx, f->f, flags);
936 if (p->state != STATE_SETTING_UP &&
937 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
938 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
942 if (avctx->internal->allocate_progress) {
944 f->progress = av_buffer_alloc(2 * sizeof(int));
946 return AVERROR(ENOMEM);
948 progress = (int*)f->progress->data;
950 progress[0] = progress[1] = -1;
953 pthread_mutex_lock(&p->parent->buffer_mutex);
955 FF_DISABLE_DEPRECATION_WARNINGS
956 if (avctx->thread_safe_callbacks || (
957 #if FF_API_GET_BUFFER
958 !avctx->get_buffer &&
960 avctx->get_buffer2 == avcodec_default_get_buffer2)) {
961 FF_ENABLE_DEPRECATION_WARNINGS
962 err = ff_get_buffer(avctx, f->f, flags);
964 pthread_mutex_lock(&p->progress_mutex);
965 p->requested_frame = f->f;
966 p->requested_flags = flags;
967 p->state = STATE_GET_BUFFER;
968 pthread_cond_broadcast(&p->progress_cond);
970 while (p->state != STATE_SETTING_UP)
971 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
975 pthread_mutex_unlock(&p->progress_mutex);
978 if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
979 ff_thread_finish_setup(avctx);
982 av_buffer_unref(&f->progress);
984 pthread_mutex_unlock(&p->parent->buffer_mutex);
989 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
991 enum AVPixelFormat res;
992 PerThreadContext *p = avctx->thread_opaque;
993 if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
994 avctx->get_format == avcodec_default_get_format)
995 return avctx->get_format(avctx, fmt);
996 if (p->state != STATE_SETTING_UP) {
997 av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
1000 pthread_mutex_lock(&p->progress_mutex);
1001 p->available_formats = fmt;
1002 p->state = STATE_GET_FORMAT;
1003 pthread_cond_broadcast(&p->progress_cond);
1005 while (p->state != STATE_SETTING_UP)
1006 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
1008 res = p->result_format;
1010 pthread_mutex_unlock(&p->progress_mutex);
1015 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1017 int ret = thread_get_buffer_internal(avctx, f, flags);
1019 av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1023 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1025 PerThreadContext *p = avctx->thread_opaque;
1026 FrameThreadContext *fctx;
1028 FF_DISABLE_DEPRECATION_WARNINGS
1029 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1030 avctx->thread_safe_callbacks ||
1032 #if FF_API_GET_BUFFER
1033 !avctx->get_buffer &&
1035 avctx->get_buffer2 == avcodec_default_get_buffer2);
1036 FF_ENABLE_DEPRECATION_WARNINGS
1041 if (avctx->debug & FF_DEBUG_BUFFERS)
1042 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1044 av_buffer_unref(&f->progress);
1047 if (can_direct_free) {
1048 av_frame_unref(f->f);
1053 pthread_mutex_lock(&fctx->buffer_mutex);
1055 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
1057 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
1058 (p->num_released_buffers + 1) *
1059 sizeof(*p->released_buffers));
1062 p->released_buffers = tmp;
1064 dst = &p->released_buffers[p->num_released_buffers];
1065 av_frame_move_ref(dst, f->f);
1067 p->num_released_buffers++;
1070 pthread_mutex_unlock(&fctx->buffer_mutex);
1074 * Set the threading algorithms used.
1076 * Threading requires more than one thread.
1077 * Frame threading requires entire frames to be passed to the codec,
1078 * and introduces extra decoding delay, so is incompatible with low_delay.
1080 * @param avctx The context.
1082 static void validate_thread_parameters(AVCodecContext *avctx)
1084 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1085 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1086 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1087 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1088 if (avctx->thread_count == 1) {
1089 avctx->active_thread_type = 0;
1090 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1091 avctx->active_thread_type = FF_THREAD_FRAME;
1092 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1093 avctx->thread_type & FF_THREAD_SLICE) {
1094 avctx->active_thread_type = FF_THREAD_SLICE;
1095 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1096 avctx->thread_count = 1;
1097 avctx->active_thread_type = 0;
1100 if (avctx->thread_count > MAX_AUTO_THREADS)
1101 av_log(avctx, AV_LOG_WARNING,
1102 "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1103 avctx->thread_count, MAX_AUTO_THREADS);
1106 int ff_thread_init(AVCodecContext *avctx)
1112 validate_thread_parameters(avctx);
1114 if (avctx->active_thread_type&FF_THREAD_SLICE)
1115 return thread_init_internal(avctx);
1116 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1117 return frame_thread_init(avctx);
1122 void ff_thread_free(AVCodecContext *avctx)
1124 if (avctx->active_thread_type&FF_THREAD_FRAME)
1125 frame_thread_free(avctx, avctx->thread_count);