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
38 #if HAVE_GETPROCESSAFFINITYMASK
43 #include <sys/param.h>
45 #include <sys/types.h>
46 #include <sys/param.h>
47 #include <sys/sysctl.h>
56 #include "libavutil/common.h"
61 #include "w32pthreads.h"
63 #include "os2threads.h"
66 typedef int (action_func)(AVCodecContext *c, void *arg);
67 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
69 typedef struct ThreadContext {
79 pthread_cond_t last_job_cond;
80 pthread_cond_t current_job_cond;
81 pthread_mutex_t current_job_lock;
83 unsigned int current_execute;
87 /// Max number of frame buffers that can be allocated when using frame threads.
88 #define MAX_BUFFERS (32+1)
91 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
93 typedef struct PerThreadContext {
94 struct FrameThreadContext *parent;
98 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
99 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
100 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
102 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
103 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
105 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
107 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
108 int allocated_buf_size; ///< Size allocated for avpkt.data
110 AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
111 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
112 int result; ///< The result of the last codec decode/encode() call.
115 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
116 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
117 STATE_GET_BUFFER, /**<
118 * Set when the codec calls get_buffer().
119 * State is returned to STATE_SETTING_UP afterwards.
121 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
125 * Array of frames passed to ff_thread_release_buffer().
126 * Frames are released after all threads referencing them are finished.
128 AVFrame released_buffers[MAX_BUFFERS];
129 int num_released_buffers;
132 * Array of progress values used by ff_thread_get_buffer().
134 volatile int progress[MAX_BUFFERS][2];
135 volatile uint8_t progress_used[MAX_BUFFERS];
137 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
141 * Context stored in the client AVCodecContext thread_opaque.
143 typedef struct FrameThreadContext {
144 PerThreadContext *threads; ///< The contexts for each thread.
145 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
147 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
149 int next_decoding; ///< The next context to submit a packet to.
150 int next_finished; ///< The next context to return output from.
153 * Set for the first N packets, where N is the number of threads.
154 * While it is set, ff_thread_en/decode_frame won't return any results.
157 int die; ///< Set when threads should exit.
158 } FrameThreadContext;
161 /* H264 slice threading seems to be buggy with more than 16 threads,
162 * limit the number of threads to 16 for automatic detection */
163 #define MAX_AUTO_THREADS 16
165 int ff_get_logical_cpus(AVCodecContext *avctx)
167 int ret, nb_cpus = 1;
168 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
173 ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
175 nb_cpus = CPU_COUNT(&cpuset);
177 #elif HAVE_GETPROCESSAFFINITYMASK
178 DWORD_PTR proc_aff, sys_aff;
179 ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
181 nb_cpus = av_popcount64(proc_aff);
182 #elif HAVE_SYSCTL && defined(HW_NCPU)
183 int mib[2] = { CTL_HW, HW_NCPU };
184 size_t len = sizeof(nb_cpus);
186 ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
189 #elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
190 nb_cpus = sysconf(_SC_NPROC_ONLN);
191 #elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
192 nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
194 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
197 nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
203 static void* attribute_align_arg worker(void *v)
205 AVCodecContext *avctx = v;
206 ThreadContext *c = avctx->thread_opaque;
207 int our_job = c->job_count;
208 int last_execute = 0;
209 int thread_count = avctx->thread_count;
212 pthread_mutex_lock(&c->current_job_lock);
213 self_id = c->current_job++;
215 while (our_job >= c->job_count) {
216 if (c->current_job == thread_count + c->job_count)
217 pthread_cond_signal(&c->last_job_cond);
219 while (last_execute == c->current_execute && !c->done)
220 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
221 last_execute = c->current_execute;
225 pthread_mutex_unlock(&c->current_job_lock);
229 pthread_mutex_unlock(&c->current_job_lock);
231 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
232 c->func2(avctx, c->args, our_job, self_id);
234 pthread_mutex_lock(&c->current_job_lock);
235 our_job = c->current_job++;
239 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
241 while (c->current_job != thread_count + c->job_count)
242 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
243 pthread_mutex_unlock(&c->current_job_lock);
246 static void thread_free(AVCodecContext *avctx)
248 ThreadContext *c = avctx->thread_opaque;
251 pthread_mutex_lock(&c->current_job_lock);
253 pthread_cond_broadcast(&c->current_job_cond);
254 pthread_mutex_unlock(&c->current_job_lock);
256 for (i=0; i<avctx->thread_count; i++)
257 pthread_join(c->workers[i], NULL);
259 pthread_mutex_destroy(&c->current_job_lock);
260 pthread_cond_destroy(&c->current_job_cond);
261 pthread_cond_destroy(&c->last_job_cond);
263 av_freep(&avctx->thread_opaque);
266 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
268 ThreadContext *c= avctx->thread_opaque;
271 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
272 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
277 pthread_mutex_lock(&c->current_job_lock);
279 c->current_job = avctx->thread_count;
280 c->job_count = job_count;
281 c->job_size = job_size;
286 c->rets_count = job_count;
288 c->rets = &dummy_ret;
291 c->current_execute++;
292 pthread_cond_broadcast(&c->current_job_cond);
294 avcodec_thread_park_workers(c, avctx->thread_count);
299 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
301 ThreadContext *c= avctx->thread_opaque;
303 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
306 static int thread_init(AVCodecContext *avctx)
310 int thread_count = avctx->thread_count;
313 int nb_cpus = ff_get_logical_cpus(avctx);
314 // use number of cores + 1 as thread count if there is more than one
316 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
318 thread_count = avctx->thread_count = 1;
321 if (thread_count <= 1) {
322 avctx->active_thread_type = 0;
326 c = av_mallocz(sizeof(ThreadContext));
330 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
336 avctx->thread_opaque = c;
341 pthread_cond_init(&c->current_job_cond, NULL);
342 pthread_cond_init(&c->last_job_cond, NULL);
343 pthread_mutex_init(&c->current_job_lock, NULL);
344 pthread_mutex_lock(&c->current_job_lock);
345 for (i=0; i<thread_count; i++) {
346 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
347 avctx->thread_count = i;
348 pthread_mutex_unlock(&c->current_job_lock);
349 ff_thread_free(avctx);
354 avcodec_thread_park_workers(c, thread_count);
356 avctx->execute = avcodec_thread_execute;
357 avctx->execute2 = avcodec_thread_execute2;
362 * Codec worker thread.
364 * Automatically calls ff_thread_finish_setup() if the codec does
365 * not provide an update_thread_context method, or if the codec returns
368 static attribute_align_arg void *frame_worker_thread(void *arg)
370 PerThreadContext *p = arg;
371 FrameThreadContext *fctx = p->parent;
372 AVCodecContext *avctx = p->avctx;
373 const AVCodec *codec = avctx->codec;
375 pthread_mutex_lock(&p->mutex);
378 while (p->state == STATE_INPUT_READY && !fctx->die)
379 pthread_cond_wait(&p->input_cond, &p->mutex);
381 if (fctx->die) break;
383 if (!codec->update_thread_context && (avctx->thread_safe_callbacks || avctx->get_buffer == avcodec_default_get_buffer))
384 ff_thread_finish_setup(avctx);
386 avcodec_get_frame_defaults(&p->frame);
388 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
390 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
392 pthread_mutex_lock(&p->progress_mutex);
393 for (i = 0; i < MAX_BUFFERS; i++)
394 if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
395 p->progress[i][0] = INT_MAX;
396 p->progress[i][1] = INT_MAX;
398 p->state = STATE_INPUT_READY;
400 pthread_cond_broadcast(&p->progress_cond);
401 pthread_cond_signal(&p->output_cond);
402 pthread_mutex_unlock(&p->progress_mutex);
404 pthread_mutex_unlock(&p->mutex);
410 * Update the next thread's AVCodecContext with values from the reference thread's context.
412 * @param dst The destination context.
413 * @param src The source context.
414 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
416 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
421 dst->time_base = src->time_base;
422 dst->width = src->width;
423 dst->height = src->height;
424 dst->pix_fmt = src->pix_fmt;
426 dst->coded_width = src->coded_width;
427 dst->coded_height = src->coded_height;
429 dst->has_b_frames = src->has_b_frames;
430 dst->idct_algo = src->idct_algo;
432 dst->bits_per_coded_sample = src->bits_per_coded_sample;
433 dst->sample_aspect_ratio = src->sample_aspect_ratio;
434 dst->dtg_active_format = src->dtg_active_format;
436 dst->profile = src->profile;
437 dst->level = src->level;
439 dst->bits_per_raw_sample = src->bits_per_raw_sample;
440 dst->ticks_per_frame = src->ticks_per_frame;
441 dst->color_primaries = src->color_primaries;
443 dst->color_trc = src->color_trc;
444 dst->colorspace = src->colorspace;
445 dst->color_range = src->color_range;
446 dst->chroma_sample_location = src->chroma_sample_location;
450 dst->delay = src->thread_count - 1;
451 dst->coded_frame = src->coded_frame;
453 if (dst->codec->update_thread_context)
454 err = dst->codec->update_thread_context(dst, src);
461 * Update the next thread's AVCodecContext with values set by the user.
463 * @param dst The destination context.
464 * @param src The source context.
465 * @return 0 on success, negative error code on failure
467 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
469 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
470 dst->flags = src->flags;
472 dst->draw_horiz_band= src->draw_horiz_band;
473 dst->get_buffer = src->get_buffer;
474 dst->release_buffer = src->release_buffer;
476 dst->opaque = src->opaque;
477 dst->debug = src->debug;
478 dst->debug_mv = src->debug_mv;
480 dst->slice_flags = src->slice_flags;
481 dst->flags2 = src->flags2;
483 copy_fields(skip_loop_filter, subtitle_header);
485 dst->frame_number = src->frame_number;
486 dst->reordered_opaque = src->reordered_opaque;
487 dst->thread_safe_callbacks = src->thread_safe_callbacks;
489 if (src->slice_count && src->slice_offset) {
490 if (dst->slice_count < src->slice_count) {
491 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
492 sizeof(*dst->slice_offset));
494 av_free(dst->slice_offset);
495 return AVERROR(ENOMEM);
497 dst->slice_offset = tmp;
499 memcpy(dst->slice_offset, src->slice_offset,
500 src->slice_count * sizeof(*dst->slice_offset));
502 dst->slice_count = src->slice_count;
507 static void free_progress(AVFrame *f)
509 PerThreadContext *p = f->owner->thread_opaque;
510 volatile int *progress = f->thread_opaque;
512 p->progress_used[(progress - p->progress[0]) / 2] = 0;
515 /// Releases the buffers that this decoding thread was the last user of.
516 static void release_delayed_buffers(PerThreadContext *p)
518 FrameThreadContext *fctx = p->parent;
520 while (p->num_released_buffers > 0) {
523 pthread_mutex_lock(&fctx->buffer_mutex);
524 f = &p->released_buffers[--p->num_released_buffers];
526 f->thread_opaque = NULL;
528 f->owner->release_buffer(f->owner, f);
529 pthread_mutex_unlock(&fctx->buffer_mutex);
533 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
535 FrameThreadContext *fctx = p->parent;
536 PerThreadContext *prev_thread = fctx->prev_thread;
537 const AVCodec *codec = p->avctx->codec;
538 uint8_t *buf = p->avpkt.data;
540 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
542 pthread_mutex_lock(&p->mutex);
544 release_delayed_buffers(p);
548 if (prev_thread->state == STATE_SETTING_UP) {
549 pthread_mutex_lock(&prev_thread->progress_mutex);
550 while (prev_thread->state == STATE_SETTING_UP)
551 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
552 pthread_mutex_unlock(&prev_thread->progress_mutex);
555 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
557 pthread_mutex_unlock(&p->mutex);
562 av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
565 memcpy(buf, avpkt->data, avpkt->size);
566 memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
568 p->state = STATE_SETTING_UP;
569 pthread_cond_signal(&p->input_cond);
570 pthread_mutex_unlock(&p->mutex);
573 * If the client doesn't have a thread-safe get_buffer(),
574 * then decoding threads call back to the main thread,
575 * and it calls back to the client here.
578 if (!p->avctx->thread_safe_callbacks &&
579 p->avctx->get_buffer != avcodec_default_get_buffer) {
580 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
581 pthread_mutex_lock(&p->progress_mutex);
582 while (p->state == STATE_SETTING_UP)
583 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
585 if (p->state == STATE_GET_BUFFER) {
586 p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
587 p->state = STATE_SETTING_UP;
588 pthread_cond_signal(&p->progress_cond);
590 pthread_mutex_unlock(&p->progress_mutex);
594 fctx->prev_thread = p;
595 fctx->next_decoding++;
600 int ff_thread_decode_frame(AVCodecContext *avctx,
601 AVFrame *picture, int *got_picture_ptr,
604 FrameThreadContext *fctx = avctx->thread_opaque;
605 int finished = fctx->next_finished;
610 * Submit a packet to the next decoding thread.
613 p = &fctx->threads[fctx->next_decoding];
614 err = update_context_from_user(p->avctx, avctx);
616 err = submit_packet(p, avpkt);
620 * If we're still receiving the initial packets, don't return a frame.
623 if (fctx->delaying) {
624 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
632 * Return the next available frame from the oldest thread.
633 * If we're at the end of the stream, then we have to skip threads that
634 * didn't output a frame, because we don't want to accidentally signal
635 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
639 p = &fctx->threads[finished++];
641 if (p->state != STATE_INPUT_READY) {
642 pthread_mutex_lock(&p->progress_mutex);
643 while (p->state != STATE_INPUT_READY)
644 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
645 pthread_mutex_unlock(&p->progress_mutex);
649 *got_picture_ptr = p->got_frame;
650 picture->pkt_dts = p->avpkt.dts;
653 * A later call with avkpt->size == 0 may loop over all threads,
654 * including this one, searching for a frame to return before being
655 * stopped by the "finished != fctx->next_finished" condition.
656 * Make sure we don't mistakenly return the same frame again.
660 if (finished >= avctx->thread_count) finished = 0;
661 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
663 update_context_from_thread(avctx, p->avctx, 1);
665 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
667 fctx->next_finished = finished;
669 /* return the size of the consumed packet if no error occurred */
670 return (p->result >= 0) ? avpkt->size : p->result;
673 void ff_thread_report_progress(AVFrame *f, int n, int field)
676 volatile int *progress = f->thread_opaque;
678 if (!progress || progress[field] >= n) return;
680 p = f->owner->thread_opaque;
682 if (f->owner->debug&FF_DEBUG_THREADS)
683 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
685 pthread_mutex_lock(&p->progress_mutex);
687 pthread_cond_broadcast(&p->progress_cond);
688 pthread_mutex_unlock(&p->progress_mutex);
691 void ff_thread_await_progress(AVFrame *f, int n, int field)
694 volatile int *progress = f->thread_opaque;
696 if (!progress || progress[field] >= n) return;
698 p = f->owner->thread_opaque;
700 if (f->owner->debug&FF_DEBUG_THREADS)
701 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
703 pthread_mutex_lock(&p->progress_mutex);
704 while (progress[field] < n)
705 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
706 pthread_mutex_unlock(&p->progress_mutex);
709 void ff_thread_finish_setup(AVCodecContext *avctx) {
710 PerThreadContext *p = avctx->thread_opaque;
712 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
714 if(p->state == STATE_SETUP_FINISHED){
715 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
718 pthread_mutex_lock(&p->progress_mutex);
719 p->state = STATE_SETUP_FINISHED;
720 pthread_cond_broadcast(&p->progress_cond);
721 pthread_mutex_unlock(&p->progress_mutex);
724 /// Waits for all threads to finish.
725 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
729 for (i = 0; i < thread_count; i++) {
730 PerThreadContext *p = &fctx->threads[i];
732 if (p->state != STATE_INPUT_READY) {
733 pthread_mutex_lock(&p->progress_mutex);
734 while (p->state != STATE_INPUT_READY)
735 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
736 pthread_mutex_unlock(&p->progress_mutex);
742 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
744 FrameThreadContext *fctx = avctx->thread_opaque;
745 const AVCodec *codec = avctx->codec;
748 park_frame_worker_threads(fctx, thread_count);
750 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
751 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
755 for (i = 0; i < thread_count; i++) {
756 PerThreadContext *p = &fctx->threads[i];
758 pthread_mutex_lock(&p->mutex);
759 pthread_cond_signal(&p->input_cond);
760 pthread_mutex_unlock(&p->mutex);
763 pthread_join(p->thread, NULL);
767 codec->close(p->avctx);
771 release_delayed_buffers(p);
774 for (i = 0; i < thread_count; i++) {
775 PerThreadContext *p = &fctx->threads[i];
777 avcodec_default_free_buffers(p->avctx);
779 pthread_mutex_destroy(&p->mutex);
780 pthread_mutex_destroy(&p->progress_mutex);
781 pthread_cond_destroy(&p->input_cond);
782 pthread_cond_destroy(&p->progress_cond);
783 pthread_cond_destroy(&p->output_cond);
784 av_freep(&p->avpkt.data);
787 av_freep(&p->avctx->priv_data);
788 av_freep(&p->avctx->internal);
789 av_freep(&p->avctx->slice_offset);
795 av_freep(&fctx->threads);
796 pthread_mutex_destroy(&fctx->buffer_mutex);
797 av_freep(&avctx->thread_opaque);
800 static int frame_thread_init(AVCodecContext *avctx)
802 int thread_count = avctx->thread_count;
803 const AVCodec *codec = avctx->codec;
804 AVCodecContext *src = avctx;
805 FrameThreadContext *fctx;
809 int nb_cpus = ff_get_logical_cpus(avctx);
810 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
812 // use number of cores + 1 as thread count if there is more than one
814 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
816 thread_count = avctx->thread_count = 1;
819 if (thread_count <= 1) {
820 avctx->active_thread_type = 0;
824 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
826 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
827 pthread_mutex_init(&fctx->buffer_mutex, NULL);
830 for (i = 0; i < thread_count; i++) {
831 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
832 PerThreadContext *p = &fctx->threads[i];
834 pthread_mutex_init(&p->mutex, NULL);
835 pthread_mutex_init(&p->progress_mutex, NULL);
836 pthread_cond_init(&p->input_cond, NULL);
837 pthread_cond_init(&p->progress_cond, NULL);
838 pthread_cond_init(&p->output_cond, NULL);
844 err = AVERROR(ENOMEM);
849 copy->thread_opaque = p;
850 copy->pkt = &p->avpkt;
856 err = codec->init(copy);
858 update_context_from_thread(avctx, copy, 1);
860 copy->priv_data = av_malloc(codec->priv_data_size);
861 if (!copy->priv_data) {
862 err = AVERROR(ENOMEM);
865 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
866 copy->internal = av_malloc(sizeof(AVCodecInternal));
867 if (!copy->internal) {
868 err = AVERROR(ENOMEM);
871 *copy->internal = *src->internal;
872 copy->internal->is_copy = 1;
874 if (codec->init_thread_copy)
875 err = codec->init_thread_copy(copy);
880 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
881 p->thread_init= !err;
889 frame_thread_free(avctx, i+1);
894 void ff_thread_flush(AVCodecContext *avctx)
897 FrameThreadContext *fctx = avctx->thread_opaque;
899 if (!avctx->thread_opaque) return;
901 park_frame_worker_threads(fctx, avctx->thread_count);
902 if (fctx->prev_thread) {
903 if (fctx->prev_thread != &fctx->threads[0])
904 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
905 if (avctx->codec->flush)
906 avctx->codec->flush(fctx->threads[0].avctx);
909 fctx->next_decoding = fctx->next_finished = 0;
911 fctx->prev_thread = NULL;
912 for (i = 0; i < avctx->thread_count; i++) {
913 PerThreadContext *p = &fctx->threads[i];
914 // Make sure decode flush calls with size=0 won't return old frames
917 release_delayed_buffers(p);
921 static volatile int *allocate_progress(PerThreadContext *p)
925 for (i = 0; i < MAX_BUFFERS; i++)
926 if (!p->progress_used[i]) break;
928 if (i == MAX_BUFFERS) {
929 av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
933 p->progress_used[i] = 1;
935 return p->progress[i];
938 int ff_thread_can_start_frame(AVCodecContext *avctx)
940 PerThreadContext *p = avctx->thread_opaque;
941 if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
942 (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&
943 avctx->get_buffer != avcodec_default_get_buffer))) {
949 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
951 PerThreadContext *p = avctx->thread_opaque;
953 volatile int *progress;
957 ff_init_buffer_info(avctx, f);
959 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
960 f->thread_opaque = NULL;
961 return avctx->get_buffer(avctx, f);
964 if (p->state != STATE_SETTING_UP &&
965 (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&
966 avctx->get_buffer != avcodec_default_get_buffer))) {
967 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
971 pthread_mutex_lock(&p->parent->buffer_mutex);
972 f->thread_opaque = (int*)(progress = allocate_progress(p));
975 pthread_mutex_unlock(&p->parent->buffer_mutex);
982 if (avctx->thread_safe_callbacks ||
983 avctx->get_buffer == avcodec_default_get_buffer) {
984 err = avctx->get_buffer(avctx, f);
986 pthread_mutex_lock(&p->progress_mutex);
987 p->requested_frame = f;
988 p->state = STATE_GET_BUFFER;
989 pthread_cond_broadcast(&p->progress_cond);
991 while (p->state != STATE_SETTING_UP)
992 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
996 pthread_mutex_unlock(&p->progress_mutex);
998 if (!avctx->codec->update_thread_context)
999 ff_thread_finish_setup(avctx);
1004 f->thread_opaque = NULL;
1006 pthread_mutex_unlock(&p->parent->buffer_mutex);
1011 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
1013 PerThreadContext *p = avctx->thread_opaque;
1014 FrameThreadContext *fctx;
1016 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
1017 avctx->release_buffer(avctx, f);
1021 if (p->num_released_buffers >= MAX_BUFFERS) {
1022 av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
1026 if(avctx->debug & FF_DEBUG_BUFFERS)
1027 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1030 pthread_mutex_lock(&fctx->buffer_mutex);
1031 p->released_buffers[p->num_released_buffers++] = *f;
1032 pthread_mutex_unlock(&fctx->buffer_mutex);
1033 memset(f->data, 0, sizeof(f->data));
1037 * Set the threading algorithms used.
1039 * Threading requires more than one thread.
1040 * Frame threading requires entire frames to be passed to the codec,
1041 * and introduces extra decoding delay, so is incompatible with low_delay.
1043 * @param avctx The context.
1045 static void validate_thread_parameters(AVCodecContext *avctx)
1047 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1048 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1049 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1050 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1051 if (avctx->thread_count == 1) {
1052 avctx->active_thread_type = 0;
1053 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1054 avctx->active_thread_type = FF_THREAD_FRAME;
1055 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1056 avctx->thread_type & FF_THREAD_SLICE) {
1057 avctx->active_thread_type = FF_THREAD_SLICE;
1058 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1059 avctx->thread_count = 1;
1060 avctx->active_thread_type = 0;
1063 if (avctx->thread_count > MAX_AUTO_THREADS)
1064 av_log(avctx, AV_LOG_WARNING,
1065 "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1066 avctx->thread_count, MAX_AUTO_THREADS);
1069 int ff_thread_init(AVCodecContext *avctx)
1071 if (avctx->thread_opaque) {
1072 av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
1081 validate_thread_parameters(avctx);
1083 if (avctx->active_thread_type&FF_THREAD_SLICE)
1084 return thread_init(avctx);
1085 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1086 return frame_thread_init(avctx);
1092 void ff_thread_free(AVCodecContext *avctx)
1094 if (avctx->active_thread_type&FF_THREAD_FRAME)
1095 frame_thread_free(avctx, avctx->thread_count);