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
34 #if HAVE_SCHED_GETAFFINITY
40 #if HAVE_GETPROCESSAFFINITYMASK
45 #include <sys/param.h>
47 #include <sys/types.h>
48 #include <sys/param.h>
49 #include <sys/sysctl.h>
58 #include "libavutil/common.h"
63 #include "w32pthreads.h"
65 #include "os2threads.h"
68 typedef int (action_func)(AVCodecContext *c, void *arg);
69 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
71 typedef struct ThreadContext {
81 pthread_cond_t last_job_cond;
82 pthread_cond_t current_job_cond;
83 pthread_mutex_t current_job_lock;
85 unsigned int current_execute;
89 /// Max number of frame buffers that can be allocated when using frame threads.
90 #define MAX_BUFFERS (34+1)
93 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
95 typedef struct PerThreadContext {
96 struct FrameThreadContext *parent;
100 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
101 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
102 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
104 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
105 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
107 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
109 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
110 int allocated_buf_size; ///< Size allocated for avpkt.data
112 AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
113 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
114 int result; ///< The result of the last codec decode/encode() call.
117 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
118 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
119 STATE_GET_BUFFER, /**<
120 * Set when the codec calls get_buffer().
121 * State is returned to STATE_SETTING_UP afterwards.
123 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
127 * Array of frames passed to ff_thread_release_buffer().
128 * Frames are released after all threads referencing them are finished.
130 AVFrame released_buffers[MAX_BUFFERS];
131 int num_released_buffers;
134 * Array of progress values used by ff_thread_get_buffer().
136 volatile int progress[MAX_BUFFERS][2];
137 volatile uint8_t progress_used[MAX_BUFFERS];
139 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
143 * Context stored in the client AVCodecContext thread_opaque.
145 typedef struct FrameThreadContext {
146 PerThreadContext *threads; ///< The contexts for each thread.
147 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
149 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
151 int next_decoding; ///< The next context to submit a packet to.
152 int next_finished; ///< The next context to return output from.
155 * Set for the first N packets, where N is the number of threads.
156 * While it is set, ff_thread_en/decode_frame won't return any results.
159 int die; ///< Set when threads should exit.
160 } FrameThreadContext;
163 /* H264 slice threading seems to be buggy with more than 16 threads,
164 * limit the number of threads to 16 for automatic detection */
165 #define MAX_AUTO_THREADS 16
167 int ff_get_logical_cpus(AVCodecContext *avctx)
169 int ret, nb_cpus = 1;
170 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
175 ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
177 nb_cpus = CPU_COUNT(&cpuset);
179 #elif HAVE_GETPROCESSAFFINITYMASK
180 DWORD_PTR proc_aff, sys_aff;
181 ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
183 nb_cpus = av_popcount64(proc_aff);
184 #elif HAVE_SYSCTL && defined(HW_NCPU)
185 int mib[2] = { CTL_HW, HW_NCPU };
186 size_t len = sizeof(nb_cpus);
188 ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
191 #elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
192 nb_cpus = sysconf(_SC_NPROC_ONLN);
193 #elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
194 nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
196 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
199 nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
205 static void* attribute_align_arg worker(void *v)
207 AVCodecContext *avctx = v;
208 ThreadContext *c = avctx->thread_opaque;
209 int our_job = c->job_count;
210 int last_execute = 0;
211 int thread_count = avctx->thread_count;
214 pthread_mutex_lock(&c->current_job_lock);
215 self_id = c->current_job++;
217 while (our_job >= c->job_count) {
218 if (c->current_job == thread_count + c->job_count)
219 pthread_cond_signal(&c->last_job_cond);
221 while (last_execute == c->current_execute && !c->done)
222 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
223 last_execute = c->current_execute;
227 pthread_mutex_unlock(&c->current_job_lock);
231 pthread_mutex_unlock(&c->current_job_lock);
233 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
234 c->func2(avctx, c->args, our_job, self_id);
236 pthread_mutex_lock(&c->current_job_lock);
237 our_job = c->current_job++;
241 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
243 while (c->current_job != thread_count + c->job_count)
244 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
245 pthread_mutex_unlock(&c->current_job_lock);
248 static void thread_free(AVCodecContext *avctx)
250 ThreadContext *c = avctx->thread_opaque;
253 pthread_mutex_lock(&c->current_job_lock);
255 pthread_cond_broadcast(&c->current_job_cond);
256 pthread_mutex_unlock(&c->current_job_lock);
258 for (i=0; i<avctx->thread_count; i++)
259 pthread_join(c->workers[i], NULL);
261 pthread_mutex_destroy(&c->current_job_lock);
262 pthread_cond_destroy(&c->current_job_cond);
263 pthread_cond_destroy(&c->last_job_cond);
265 av_freep(&avctx->thread_opaque);
268 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
270 ThreadContext *c= avctx->thread_opaque;
273 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
274 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
279 pthread_mutex_lock(&c->current_job_lock);
281 c->current_job = avctx->thread_count;
282 c->job_count = job_count;
283 c->job_size = job_size;
288 c->rets_count = job_count;
290 c->rets = &dummy_ret;
293 c->current_execute++;
294 pthread_cond_broadcast(&c->current_job_cond);
296 avcodec_thread_park_workers(c, avctx->thread_count);
301 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
303 ThreadContext *c= avctx->thread_opaque;
305 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
308 static int thread_init(AVCodecContext *avctx)
312 int thread_count = avctx->thread_count;
315 int nb_cpus = ff_get_logical_cpus(avctx);
316 // use number of cores + 1 as thread count if there is more than one
318 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
320 thread_count = avctx->thread_count = 1;
323 if (thread_count <= 1) {
324 avctx->active_thread_type = 0;
328 c = av_mallocz(sizeof(ThreadContext));
332 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
338 avctx->thread_opaque = c;
343 pthread_cond_init(&c->current_job_cond, NULL);
344 pthread_cond_init(&c->last_job_cond, NULL);
345 pthread_mutex_init(&c->current_job_lock, NULL);
346 pthread_mutex_lock(&c->current_job_lock);
347 for (i=0; i<thread_count; i++) {
348 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
349 avctx->thread_count = i;
350 pthread_mutex_unlock(&c->current_job_lock);
351 ff_thread_free(avctx);
356 avcodec_thread_park_workers(c, thread_count);
358 avctx->execute = avcodec_thread_execute;
359 avctx->execute2 = avcodec_thread_execute2;
364 * Codec worker thread.
366 * Automatically calls ff_thread_finish_setup() if the codec does
367 * not provide an update_thread_context method, or if the codec returns
370 static attribute_align_arg void *frame_worker_thread(void *arg)
372 PerThreadContext *p = arg;
373 FrameThreadContext *fctx = p->parent;
374 AVCodecContext *avctx = p->avctx;
375 const AVCodec *codec = avctx->codec;
377 pthread_mutex_lock(&p->mutex);
380 while (p->state == STATE_INPUT_READY && !fctx->die)
381 pthread_cond_wait(&p->input_cond, &p->mutex);
383 if (fctx->die) break;
385 if (!codec->update_thread_context && (avctx->thread_safe_callbacks || avctx->get_buffer == avcodec_default_get_buffer))
386 ff_thread_finish_setup(avctx);
388 avcodec_get_frame_defaults(&p->frame);
390 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
392 /* many decoders assign whole AVFrames, thus overwriting extended_data;
393 * make sure it's set correctly */
394 p->frame.extended_data = p->frame.data;
396 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
398 pthread_mutex_lock(&p->progress_mutex);
399 for (i = 0; i < MAX_BUFFERS; i++)
400 if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
401 p->progress[i][0] = INT_MAX;
402 p->progress[i][1] = INT_MAX;
404 p->state = STATE_INPUT_READY;
406 pthread_cond_broadcast(&p->progress_cond);
407 pthread_cond_signal(&p->output_cond);
408 pthread_mutex_unlock(&p->progress_mutex);
410 pthread_mutex_unlock(&p->mutex);
416 * Update the next thread's AVCodecContext with values from the reference thread's context.
418 * @param dst The destination context.
419 * @param src The source context.
420 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
422 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
427 dst->time_base = src->time_base;
428 dst->width = src->width;
429 dst->height = src->height;
430 dst->pix_fmt = src->pix_fmt;
432 dst->coded_width = src->coded_width;
433 dst->coded_height = src->coded_height;
435 dst->has_b_frames = src->has_b_frames;
436 dst->idct_algo = src->idct_algo;
438 dst->bits_per_coded_sample = src->bits_per_coded_sample;
439 dst->sample_aspect_ratio = src->sample_aspect_ratio;
440 dst->dtg_active_format = src->dtg_active_format;
442 dst->profile = src->profile;
443 dst->level = src->level;
445 dst->bits_per_raw_sample = src->bits_per_raw_sample;
446 dst->ticks_per_frame = src->ticks_per_frame;
447 dst->color_primaries = src->color_primaries;
449 dst->color_trc = src->color_trc;
450 dst->colorspace = src->colorspace;
451 dst->color_range = src->color_range;
452 dst->chroma_sample_location = src->chroma_sample_location;
456 dst->delay = src->thread_count - 1;
457 dst->coded_frame = src->coded_frame;
459 if (dst->codec->update_thread_context)
460 err = dst->codec->update_thread_context(dst, src);
467 * Update the next thread's AVCodecContext with values set by the user.
469 * @param dst The destination context.
470 * @param src The source context.
471 * @return 0 on success, negative error code on failure
473 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
475 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
476 dst->flags = src->flags;
478 dst->draw_horiz_band= src->draw_horiz_band;
479 dst->get_buffer = src->get_buffer;
480 dst->release_buffer = src->release_buffer;
482 dst->opaque = src->opaque;
483 dst->debug = src->debug;
484 dst->debug_mv = src->debug_mv;
486 dst->slice_flags = src->slice_flags;
487 dst->flags2 = src->flags2;
489 copy_fields(skip_loop_filter, subtitle_header);
491 dst->frame_number = src->frame_number;
492 dst->reordered_opaque = src->reordered_opaque;
493 dst->thread_safe_callbacks = src->thread_safe_callbacks;
495 if (src->slice_count && src->slice_offset) {
496 if (dst->slice_count < src->slice_count) {
497 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
498 sizeof(*dst->slice_offset));
500 av_free(dst->slice_offset);
501 return AVERROR(ENOMEM);
503 dst->slice_offset = tmp;
505 memcpy(dst->slice_offset, src->slice_offset,
506 src->slice_count * sizeof(*dst->slice_offset));
508 dst->slice_count = src->slice_count;
513 static void free_progress(AVFrame *f)
515 PerThreadContext *p = f->owner->thread_opaque;
516 volatile int *progress = f->thread_opaque;
518 p->progress_used[(progress - p->progress[0]) / 2] = 0;
521 /// Releases the buffers that this decoding thread was the last user of.
522 static void release_delayed_buffers(PerThreadContext *p)
524 FrameThreadContext *fctx = p->parent;
526 while (p->num_released_buffers > 0) {
529 pthread_mutex_lock(&fctx->buffer_mutex);
530 f = &p->released_buffers[--p->num_released_buffers];
532 f->thread_opaque = NULL;
534 f->owner->release_buffer(f->owner, f);
535 pthread_mutex_unlock(&fctx->buffer_mutex);
539 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
541 FrameThreadContext *fctx = p->parent;
542 PerThreadContext *prev_thread = fctx->prev_thread;
543 const AVCodec *codec = p->avctx->codec;
544 uint8_t *buf = p->avpkt.data;
546 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
548 pthread_mutex_lock(&p->mutex);
550 release_delayed_buffers(p);
554 if (prev_thread->state == STATE_SETTING_UP) {
555 pthread_mutex_lock(&prev_thread->progress_mutex);
556 while (prev_thread->state == STATE_SETTING_UP)
557 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
558 pthread_mutex_unlock(&prev_thread->progress_mutex);
561 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
563 pthread_mutex_unlock(&p->mutex);
568 av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
571 memcpy(buf, avpkt->data, avpkt->size);
572 memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
574 p->state = STATE_SETTING_UP;
575 pthread_cond_signal(&p->input_cond);
576 pthread_mutex_unlock(&p->mutex);
579 * If the client doesn't have a thread-safe get_buffer(),
580 * then decoding threads call back to the main thread,
581 * and it calls back to the client here.
584 if (!p->avctx->thread_safe_callbacks &&
585 p->avctx->get_buffer != avcodec_default_get_buffer) {
586 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
587 pthread_mutex_lock(&p->progress_mutex);
588 while (p->state == STATE_SETTING_UP)
589 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
591 if (p->state == STATE_GET_BUFFER) {
592 p->result = ff_get_buffer(p->avctx, p->requested_frame);
593 p->state = STATE_SETTING_UP;
594 pthread_cond_signal(&p->progress_cond);
596 pthread_mutex_unlock(&p->progress_mutex);
600 fctx->prev_thread = p;
601 fctx->next_decoding++;
606 int ff_thread_decode_frame(AVCodecContext *avctx,
607 AVFrame *picture, int *got_picture_ptr,
610 FrameThreadContext *fctx = avctx->thread_opaque;
611 int finished = fctx->next_finished;
616 * Submit a packet to the next decoding thread.
619 p = &fctx->threads[fctx->next_decoding];
620 err = update_context_from_user(p->avctx, avctx);
622 err = submit_packet(p, avpkt);
626 * If we're still receiving the initial packets, don't return a frame.
629 if (fctx->delaying) {
630 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
638 * Return the next available frame from the oldest thread.
639 * If we're at the end of the stream, then we have to skip threads that
640 * didn't output a frame, because we don't want to accidentally signal
641 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
645 p = &fctx->threads[finished++];
647 if (p->state != STATE_INPUT_READY) {
648 pthread_mutex_lock(&p->progress_mutex);
649 while (p->state != STATE_INPUT_READY)
650 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
651 pthread_mutex_unlock(&p->progress_mutex);
655 *got_picture_ptr = p->got_frame;
656 picture->pkt_dts = p->avpkt.dts;
659 * A later call with avkpt->size == 0 may loop over all threads,
660 * including this one, searching for a frame to return before being
661 * stopped by the "finished != fctx->next_finished" condition.
662 * Make sure we don't mistakenly return the same frame again.
666 if (finished >= avctx->thread_count) finished = 0;
667 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
669 update_context_from_thread(avctx, p->avctx, 1);
671 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
673 fctx->next_finished = finished;
675 /* return the size of the consumed packet if no error occurred */
676 return (p->result >= 0) ? avpkt->size : p->result;
679 void ff_thread_report_progress(AVFrame *f, int n, int field)
682 volatile int *progress = f->thread_opaque;
684 if (!progress || progress[field] >= n) return;
686 p = f->owner->thread_opaque;
688 if (f->owner->debug&FF_DEBUG_THREADS)
689 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
691 pthread_mutex_lock(&p->progress_mutex);
693 pthread_cond_broadcast(&p->progress_cond);
694 pthread_mutex_unlock(&p->progress_mutex);
697 void ff_thread_await_progress(AVFrame *f, int n, int field)
700 volatile int *progress = f->thread_opaque;
702 if (!progress || progress[field] >= n) return;
704 p = f->owner->thread_opaque;
706 if (f->owner->debug&FF_DEBUG_THREADS)
707 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
709 pthread_mutex_lock(&p->progress_mutex);
710 while (progress[field] < n)
711 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
712 pthread_mutex_unlock(&p->progress_mutex);
715 void ff_thread_finish_setup(AVCodecContext *avctx) {
716 PerThreadContext *p = avctx->thread_opaque;
718 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
720 if(p->state == STATE_SETUP_FINISHED){
721 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
724 pthread_mutex_lock(&p->progress_mutex);
725 p->state = STATE_SETUP_FINISHED;
726 pthread_cond_broadcast(&p->progress_cond);
727 pthread_mutex_unlock(&p->progress_mutex);
730 /// Waits for all threads to finish.
731 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
735 for (i = 0; i < thread_count; i++) {
736 PerThreadContext *p = &fctx->threads[i];
738 if (p->state != STATE_INPUT_READY) {
739 pthread_mutex_lock(&p->progress_mutex);
740 while (p->state != STATE_INPUT_READY)
741 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
742 pthread_mutex_unlock(&p->progress_mutex);
748 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
750 FrameThreadContext *fctx = avctx->thread_opaque;
751 const AVCodec *codec = avctx->codec;
754 park_frame_worker_threads(fctx, thread_count);
756 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
757 if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
758 av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
759 fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
760 fctx->threads->avctx->internal->is_copy = 1;
765 for (i = 0; i < thread_count; i++) {
766 PerThreadContext *p = &fctx->threads[i];
768 pthread_mutex_lock(&p->mutex);
769 pthread_cond_signal(&p->input_cond);
770 pthread_mutex_unlock(&p->mutex);
773 pthread_join(p->thread, NULL);
777 codec->close(p->avctx);
781 release_delayed_buffers(p);
784 for (i = 0; i < thread_count; i++) {
785 PerThreadContext *p = &fctx->threads[i];
787 avcodec_default_free_buffers(p->avctx);
789 pthread_mutex_destroy(&p->mutex);
790 pthread_mutex_destroy(&p->progress_mutex);
791 pthread_cond_destroy(&p->input_cond);
792 pthread_cond_destroy(&p->progress_cond);
793 pthread_cond_destroy(&p->output_cond);
794 av_freep(&p->avpkt.data);
797 av_freep(&p->avctx->priv_data);
798 av_freep(&p->avctx->internal);
799 av_freep(&p->avctx->slice_offset);
805 av_freep(&fctx->threads);
806 pthread_mutex_destroy(&fctx->buffer_mutex);
807 av_freep(&avctx->thread_opaque);
810 static int frame_thread_init(AVCodecContext *avctx)
812 int thread_count = avctx->thread_count;
813 const AVCodec *codec = avctx->codec;
814 AVCodecContext *src = avctx;
815 FrameThreadContext *fctx;
819 int nb_cpus = ff_get_logical_cpus(avctx);
820 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
822 // use number of cores + 1 as thread count if there is more than one
824 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
826 thread_count = avctx->thread_count = 1;
829 if (thread_count <= 1) {
830 avctx->active_thread_type = 0;
834 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
836 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
837 pthread_mutex_init(&fctx->buffer_mutex, NULL);
840 for (i = 0; i < thread_count; i++) {
841 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
842 PerThreadContext *p = &fctx->threads[i];
844 pthread_mutex_init(&p->mutex, NULL);
845 pthread_mutex_init(&p->progress_mutex, NULL);
846 pthread_cond_init(&p->input_cond, NULL);
847 pthread_cond_init(&p->progress_cond, NULL);
848 pthread_cond_init(&p->output_cond, NULL);
854 err = AVERROR(ENOMEM);
859 copy->thread_opaque = p;
860 copy->pkt = &p->avpkt;
866 err = codec->init(copy);
868 update_context_from_thread(avctx, copy, 1);
870 copy->priv_data = av_malloc(codec->priv_data_size);
871 if (!copy->priv_data) {
872 err = AVERROR(ENOMEM);
875 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
876 copy->internal = av_malloc(sizeof(AVCodecInternal));
877 if (!copy->internal) {
878 err = AVERROR(ENOMEM);
881 *copy->internal = *src->internal;
882 copy->internal->is_copy = 1;
884 if (codec->init_thread_copy)
885 err = codec->init_thread_copy(copy);
890 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
891 p->thread_init= !err;
899 frame_thread_free(avctx, i+1);
904 void ff_thread_flush(AVCodecContext *avctx)
907 FrameThreadContext *fctx = avctx->thread_opaque;
909 if (!avctx->thread_opaque) return;
911 park_frame_worker_threads(fctx, avctx->thread_count);
912 if (fctx->prev_thread) {
913 if (fctx->prev_thread != &fctx->threads[0])
914 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
915 if (avctx->codec->flush)
916 avctx->codec->flush(fctx->threads[0].avctx);
919 fctx->next_decoding = fctx->next_finished = 0;
921 fctx->prev_thread = NULL;
922 for (i = 0; i < avctx->thread_count; i++) {
923 PerThreadContext *p = &fctx->threads[i];
924 // Make sure decode flush calls with size=0 won't return old frames
927 release_delayed_buffers(p);
931 static volatile int *allocate_progress(PerThreadContext *p)
935 for (i = 0; i < MAX_BUFFERS; i++)
936 if (!p->progress_used[i]) break;
938 if (i == MAX_BUFFERS) {
939 av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
943 p->progress_used[i] = 1;
945 return p->progress[i];
948 int ff_thread_can_start_frame(AVCodecContext *avctx)
950 PerThreadContext *p = avctx->thread_opaque;
951 if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
952 (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&
953 avctx->get_buffer != avcodec_default_get_buffer))) {
959 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
961 PerThreadContext *p = avctx->thread_opaque;
963 volatile int *progress;
967 ff_init_buffer_info(avctx, f);
969 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
970 f->thread_opaque = NULL;
971 return ff_get_buffer(avctx, f);
974 if (p->state != STATE_SETTING_UP &&
975 (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&
976 avctx->get_buffer != avcodec_default_get_buffer))) {
977 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
981 pthread_mutex_lock(&p->parent->buffer_mutex);
982 f->thread_opaque = (int*)(progress = allocate_progress(p));
985 pthread_mutex_unlock(&p->parent->buffer_mutex);
992 if (avctx->thread_safe_callbacks ||
993 avctx->get_buffer == avcodec_default_get_buffer) {
994 err = ff_get_buffer(avctx, f);
996 pthread_mutex_lock(&p->progress_mutex);
997 p->requested_frame = f;
998 p->state = STATE_GET_BUFFER;
999 pthread_cond_broadcast(&p->progress_cond);
1001 while (p->state != STATE_SETTING_UP)
1002 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
1006 pthread_mutex_unlock(&p->progress_mutex);
1008 if (!avctx->codec->update_thread_context)
1009 ff_thread_finish_setup(avctx);
1014 f->thread_opaque = NULL;
1016 pthread_mutex_unlock(&p->parent->buffer_mutex);
1021 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
1023 PerThreadContext *p = avctx->thread_opaque;
1024 FrameThreadContext *fctx;
1029 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
1030 avctx->release_buffer(avctx, f);
1034 if (p->num_released_buffers >= MAX_BUFFERS) {
1035 av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
1039 if(avctx->debug & FF_DEBUG_BUFFERS)
1040 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1043 pthread_mutex_lock(&fctx->buffer_mutex);
1044 p->released_buffers[p->num_released_buffers++] = *f;
1045 pthread_mutex_unlock(&fctx->buffer_mutex);
1046 memset(f->data, 0, sizeof(f->data));
1050 * Set the threading algorithms used.
1052 * Threading requires more than one thread.
1053 * Frame threading requires entire frames to be passed to the codec,
1054 * and introduces extra decoding delay, so is incompatible with low_delay.
1056 * @param avctx The context.
1058 static void validate_thread_parameters(AVCodecContext *avctx)
1060 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1061 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1062 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1063 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1064 if (avctx->thread_count == 1) {
1065 avctx->active_thread_type = 0;
1066 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1067 avctx->active_thread_type = FF_THREAD_FRAME;
1068 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1069 avctx->thread_type & FF_THREAD_SLICE) {
1070 avctx->active_thread_type = FF_THREAD_SLICE;
1071 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1072 avctx->thread_count = 1;
1073 avctx->active_thread_type = 0;
1076 if (avctx->thread_count > MAX_AUTO_THREADS)
1077 av_log(avctx, AV_LOG_WARNING,
1078 "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1079 avctx->thread_count, MAX_AUTO_THREADS);
1082 int ff_thread_init(AVCodecContext *avctx)
1084 if (avctx->thread_opaque) {
1085 av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
1094 validate_thread_parameters(avctx);
1096 if (avctx->active_thread_type&FF_THREAD_SLICE)
1097 return thread_init(avctx);
1098 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1099 return frame_thread_init(avctx);
1105 void ff_thread_free(AVCodecContext *avctx)
1107 if (avctx->active_thread_type&FF_THREAD_FRAME)
1108 frame_thread_free(avctx, avctx->thread_count);