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>
60 #include "w32pthreads.h"
62 #include "os2threads.h"
65 typedef int (action_func)(AVCodecContext *c, void *arg);
66 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
68 typedef struct ThreadContext {
78 pthread_cond_t last_job_cond;
79 pthread_cond_t current_job_cond;
80 pthread_mutex_t current_job_lock;
85 /// Max number of frame buffers that can be allocated when using frame threads.
86 #define MAX_BUFFERS (32+1)
89 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
91 typedef struct PerThreadContext {
92 struct FrameThreadContext *parent;
96 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
97 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
98 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
100 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
101 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
103 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
105 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
106 int allocated_buf_size; ///< Size allocated for avpkt.data
108 AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
109 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
110 int result; ///< The result of the last codec decode/encode() call.
113 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
114 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
115 STATE_GET_BUFFER, /**<
116 * Set when the codec calls get_buffer().
117 * State is returned to STATE_SETTING_UP afterwards.
119 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
123 * Array of frames passed to ff_thread_release_buffer().
124 * Frames are released after all threads referencing them are finished.
126 AVFrame released_buffers[MAX_BUFFERS];
127 int num_released_buffers;
130 * Array of progress values used by ff_thread_get_buffer().
132 volatile int progress[MAX_BUFFERS][2];
133 volatile uint8_t progress_used[MAX_BUFFERS];
135 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
139 * Context stored in the client AVCodecContext thread_opaque.
141 typedef struct FrameThreadContext {
142 PerThreadContext *threads; ///< The contexts for each thread.
143 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
145 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
147 int next_decoding; ///< The next context to submit a packet to.
148 int next_finished; ///< The next context to return output from.
151 * Set for the first N packets, where N is the number of threads.
152 * While it is set, ff_thread_en/decode_frame won't return any results.
155 int die; ///< Set when threads should exit.
156 } FrameThreadContext;
159 /* H264 slice threading seems to be buggy with more than 16 threads,
160 * limit the number of threads to 16 for automatic detection */
161 #define MAX_AUTO_THREADS 16
163 int ff_get_logical_cpus(AVCodecContext *avctx)
165 int ret, nb_cpus = 1;
166 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
171 ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
173 nb_cpus = CPU_COUNT(&cpuset);
175 #elif HAVE_GETPROCESSAFFINITYMASK
176 DWORD_PTR proc_aff, sys_aff;
177 ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
179 nb_cpus = av_popcount64(proc_aff);
180 #elif HAVE_SYSCTL && defined(HW_NCPU)
181 int mib[2] = { CTL_HW, HW_NCPU };
182 size_t len = sizeof(nb_cpus);
184 ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
187 #elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
188 nb_cpus = sysconf(_SC_NPROC_ONLN);
189 #elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
190 nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
192 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
195 nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
201 static void* attribute_align_arg worker(void *v)
203 AVCodecContext *avctx = v;
204 ThreadContext *c = avctx->thread_opaque;
205 int our_job = c->job_count;
206 int thread_count = avctx->thread_count;
209 pthread_mutex_lock(&c->current_job_lock);
210 self_id = c->current_job++;
212 while (our_job >= c->job_count) {
213 if (c->current_job == thread_count + c->job_count)
214 pthread_cond_signal(&c->last_job_cond);
216 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
220 pthread_mutex_unlock(&c->current_job_lock);
224 pthread_mutex_unlock(&c->current_job_lock);
226 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
227 c->func2(avctx, c->args, our_job, self_id);
229 pthread_mutex_lock(&c->current_job_lock);
230 our_job = c->current_job++;
234 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
236 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
237 pthread_mutex_unlock(&c->current_job_lock);
240 static void thread_free(AVCodecContext *avctx)
242 ThreadContext *c = avctx->thread_opaque;
245 pthread_mutex_lock(&c->current_job_lock);
247 pthread_cond_broadcast(&c->current_job_cond);
248 pthread_mutex_unlock(&c->current_job_lock);
250 for (i=0; i<avctx->thread_count; i++)
251 pthread_join(c->workers[i], NULL);
253 pthread_mutex_destroy(&c->current_job_lock);
254 pthread_cond_destroy(&c->current_job_cond);
255 pthread_cond_destroy(&c->last_job_cond);
257 av_freep(&avctx->thread_opaque);
260 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
262 ThreadContext *c= avctx->thread_opaque;
265 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
266 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
271 pthread_mutex_lock(&c->current_job_lock);
273 c->current_job = avctx->thread_count;
274 c->job_count = job_count;
275 c->job_size = job_size;
280 c->rets_count = job_count;
282 c->rets = &dummy_ret;
285 pthread_cond_broadcast(&c->current_job_cond);
287 avcodec_thread_park_workers(c, avctx->thread_count);
292 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
294 ThreadContext *c= avctx->thread_opaque;
296 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
299 static int thread_init(AVCodecContext *avctx)
303 int thread_count = avctx->thread_count;
306 int nb_cpus = ff_get_logical_cpus(avctx);
307 // use number of cores + 1 as thread count if there is more than one
309 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
311 thread_count = avctx->thread_count = 1;
314 if (thread_count <= 1) {
315 avctx->active_thread_type = 0;
319 c = av_mallocz(sizeof(ThreadContext));
323 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
329 avctx->thread_opaque = c;
334 pthread_cond_init(&c->current_job_cond, NULL);
335 pthread_cond_init(&c->last_job_cond, NULL);
336 pthread_mutex_init(&c->current_job_lock, NULL);
337 pthread_mutex_lock(&c->current_job_lock);
338 for (i=0; i<thread_count; i++) {
339 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
340 avctx->thread_count = i;
341 pthread_mutex_unlock(&c->current_job_lock);
342 ff_thread_free(avctx);
347 avcodec_thread_park_workers(c, thread_count);
349 avctx->execute = avcodec_thread_execute;
350 avctx->execute2 = avcodec_thread_execute2;
355 * Codec worker thread.
357 * Automatically calls ff_thread_finish_setup() if the codec does
358 * not provide an update_thread_context method, or if the codec returns
361 static attribute_align_arg void *frame_worker_thread(void *arg)
363 PerThreadContext *p = arg;
364 FrameThreadContext *fctx = p->parent;
365 AVCodecContext *avctx = p->avctx;
366 AVCodec *codec = avctx->codec;
368 pthread_mutex_lock(&p->mutex);
371 while (p->state == STATE_INPUT_READY && !fctx->die)
372 pthread_cond_wait(&p->input_cond, &p->mutex);
374 if (fctx->die) break;
376 if (!codec->update_thread_context && (avctx->thread_safe_callbacks || avctx->get_buffer == avcodec_default_get_buffer))
377 ff_thread_finish_setup(avctx);
379 avcodec_get_frame_defaults(&p->frame);
381 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
383 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
385 pthread_mutex_lock(&p->progress_mutex);
386 for (i = 0; i < MAX_BUFFERS; i++)
387 if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != CODEC_ID_H264)) {
388 p->progress[i][0] = INT_MAX;
389 p->progress[i][1] = INT_MAX;
391 p->state = STATE_INPUT_READY;
393 pthread_cond_broadcast(&p->progress_cond);
394 pthread_cond_signal(&p->output_cond);
395 pthread_mutex_unlock(&p->progress_mutex);
397 pthread_mutex_unlock(&p->mutex);
403 * Update the next thread's AVCodecContext with values from the reference thread's context.
405 * @param dst The destination context.
406 * @param src The source context.
407 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
409 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
414 dst->time_base = src->time_base;
415 dst->width = src->width;
416 dst->height = src->height;
417 dst->pix_fmt = src->pix_fmt;
419 dst->coded_width = src->coded_width;
420 dst->coded_height = src->coded_height;
422 dst->has_b_frames = src->has_b_frames;
423 dst->idct_algo = src->idct_algo;
425 dst->bits_per_coded_sample = src->bits_per_coded_sample;
426 dst->sample_aspect_ratio = src->sample_aspect_ratio;
427 dst->dtg_active_format = src->dtg_active_format;
429 dst->profile = src->profile;
430 dst->level = src->level;
432 dst->bits_per_raw_sample = src->bits_per_raw_sample;
433 dst->ticks_per_frame = src->ticks_per_frame;
434 dst->color_primaries = src->color_primaries;
436 dst->color_trc = src->color_trc;
437 dst->colorspace = src->colorspace;
438 dst->color_range = src->color_range;
439 dst->chroma_sample_location = src->chroma_sample_location;
443 dst->delay = src->thread_count - 1;
444 dst->coded_frame = src->coded_frame;
446 if (dst->codec->update_thread_context)
447 err = dst->codec->update_thread_context(dst, src);
454 * Update the next thread's AVCodecContext with values set by the user.
456 * @param dst The destination context.
457 * @param src The source context.
458 * @return 0 on success, negative error code on failure
460 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
462 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
463 dst->flags = src->flags;
465 dst->draw_horiz_band= src->draw_horiz_band;
466 dst->get_buffer = src->get_buffer;
467 dst->release_buffer = src->release_buffer;
469 dst->opaque = src->opaque;
470 dst->debug = src->debug;
471 dst->debug_mv = src->debug_mv;
473 dst->slice_flags = src->slice_flags;
474 dst->flags2 = src->flags2;
476 copy_fields(skip_loop_filter, subtitle_header);
478 dst->frame_number = src->frame_number;
479 dst->reordered_opaque = src->reordered_opaque;
480 dst->thread_safe_callbacks = src->thread_safe_callbacks;
482 if (src->slice_count && src->slice_offset) {
483 if (dst->slice_count < src->slice_count) {
484 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
485 sizeof(*dst->slice_offset));
487 av_free(dst->slice_offset);
488 return AVERROR(ENOMEM);
490 dst->slice_offset = tmp;
492 memcpy(dst->slice_offset, src->slice_offset,
493 src->slice_count * sizeof(*dst->slice_offset));
495 dst->slice_count = src->slice_count;
500 static void free_progress(AVFrame *f)
502 PerThreadContext *p = f->owner->thread_opaque;
503 volatile int *progress = f->thread_opaque;
505 p->progress_used[(progress - p->progress[0]) / 2] = 0;
508 /// Releases the buffers that this decoding thread was the last user of.
509 static void release_delayed_buffers(PerThreadContext *p)
511 FrameThreadContext *fctx = p->parent;
513 while (p->num_released_buffers > 0) {
516 pthread_mutex_lock(&fctx->buffer_mutex);
517 f = &p->released_buffers[--p->num_released_buffers];
519 f->thread_opaque = NULL;
521 f->owner->release_buffer(f->owner, f);
522 pthread_mutex_unlock(&fctx->buffer_mutex);
526 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
528 FrameThreadContext *fctx = p->parent;
529 PerThreadContext *prev_thread = fctx->prev_thread;
530 AVCodec *codec = p->avctx->codec;
531 uint8_t *buf = p->avpkt.data;
533 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
535 pthread_mutex_lock(&p->mutex);
537 release_delayed_buffers(p);
541 if (prev_thread->state == STATE_SETTING_UP) {
542 pthread_mutex_lock(&prev_thread->progress_mutex);
543 while (prev_thread->state == STATE_SETTING_UP)
544 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
545 pthread_mutex_unlock(&prev_thread->progress_mutex);
548 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
550 pthread_mutex_unlock(&p->mutex);
555 av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
558 memcpy(buf, avpkt->data, avpkt->size);
559 memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
561 p->state = STATE_SETTING_UP;
562 pthread_cond_signal(&p->input_cond);
563 pthread_mutex_unlock(&p->mutex);
566 * If the client doesn't have a thread-safe get_buffer(),
567 * then decoding threads call back to the main thread,
568 * and it calls back to the client here.
571 if (!p->avctx->thread_safe_callbacks &&
572 p->avctx->get_buffer != avcodec_default_get_buffer) {
573 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
574 pthread_mutex_lock(&p->progress_mutex);
575 while (p->state == STATE_SETTING_UP)
576 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
578 if (p->state == STATE_GET_BUFFER) {
579 p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
580 p->state = STATE_SETTING_UP;
581 pthread_cond_signal(&p->progress_cond);
583 pthread_mutex_unlock(&p->progress_mutex);
587 fctx->prev_thread = p;
588 fctx->next_decoding++;
593 int ff_thread_decode_frame(AVCodecContext *avctx,
594 AVFrame *picture, int *got_picture_ptr,
597 FrameThreadContext *fctx = avctx->thread_opaque;
598 int finished = fctx->next_finished;
603 * Submit a packet to the next decoding thread.
606 p = &fctx->threads[fctx->next_decoding];
607 err = update_context_from_user(p->avctx, avctx);
609 err = submit_packet(p, avpkt);
613 * If we're still receiving the initial packets, don't return a frame.
616 if (fctx->delaying) {
617 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
625 * Return the next available frame from the oldest thread.
626 * If we're at the end of the stream, then we have to skip threads that
627 * didn't output a frame, because we don't want to accidentally signal
628 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
632 p = &fctx->threads[finished++];
634 if (p->state != STATE_INPUT_READY) {
635 pthread_mutex_lock(&p->progress_mutex);
636 while (p->state != STATE_INPUT_READY)
637 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
638 pthread_mutex_unlock(&p->progress_mutex);
642 *got_picture_ptr = p->got_frame;
643 picture->pkt_dts = p->avpkt.dts;
646 * A later call with avkpt->size == 0 may loop over all threads,
647 * including this one, searching for a frame to return before being
648 * stopped by the "finished != fctx->next_finished" condition.
649 * Make sure we don't mistakenly return the same frame again.
653 if (finished >= avctx->thread_count) finished = 0;
654 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
656 update_context_from_thread(avctx, p->avctx, 1);
658 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
660 fctx->next_finished = finished;
662 /* return the size of the consumed packet if no error occurred */
663 return (p->result >= 0) ? avpkt->size : p->result;
666 void ff_thread_report_progress(AVFrame *f, int n, int field)
669 volatile int *progress = f->thread_opaque;
671 if (!progress || progress[field] >= n) return;
673 p = f->owner->thread_opaque;
675 if (f->owner->debug&FF_DEBUG_THREADS)
676 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
678 pthread_mutex_lock(&p->progress_mutex);
680 pthread_cond_broadcast(&p->progress_cond);
681 pthread_mutex_unlock(&p->progress_mutex);
684 void ff_thread_await_progress(AVFrame *f, int n, int field)
687 volatile int *progress = f->thread_opaque;
689 if (!progress || progress[field] >= n) return;
691 p = f->owner->thread_opaque;
693 if (f->owner->debug&FF_DEBUG_THREADS)
694 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
696 pthread_mutex_lock(&p->progress_mutex);
697 while (progress[field] < n)
698 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
699 pthread_mutex_unlock(&p->progress_mutex);
702 void ff_thread_finish_setup(AVCodecContext *avctx) {
703 PerThreadContext *p = avctx->thread_opaque;
705 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
707 if(p->state == STATE_SETUP_FINISHED){
708 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
711 pthread_mutex_lock(&p->progress_mutex);
712 p->state = STATE_SETUP_FINISHED;
713 pthread_cond_broadcast(&p->progress_cond);
714 pthread_mutex_unlock(&p->progress_mutex);
717 /// Waits for all threads to finish.
718 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
722 for (i = 0; i < thread_count; i++) {
723 PerThreadContext *p = &fctx->threads[i];
725 if (p->state != STATE_INPUT_READY) {
726 pthread_mutex_lock(&p->progress_mutex);
727 while (p->state != STATE_INPUT_READY)
728 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
729 pthread_mutex_unlock(&p->progress_mutex);
735 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
737 FrameThreadContext *fctx = avctx->thread_opaque;
738 AVCodec *codec = avctx->codec;
741 park_frame_worker_threads(fctx, thread_count);
743 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
744 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
748 for (i = 0; i < thread_count; i++) {
749 PerThreadContext *p = &fctx->threads[i];
751 pthread_mutex_lock(&p->mutex);
752 pthread_cond_signal(&p->input_cond);
753 pthread_mutex_unlock(&p->mutex);
756 pthread_join(p->thread, NULL);
760 codec->close(p->avctx);
764 release_delayed_buffers(p);
767 for (i = 0; i < thread_count; i++) {
768 PerThreadContext *p = &fctx->threads[i];
770 avcodec_default_free_buffers(p->avctx);
772 pthread_mutex_destroy(&p->mutex);
773 pthread_mutex_destroy(&p->progress_mutex);
774 pthread_cond_destroy(&p->input_cond);
775 pthread_cond_destroy(&p->progress_cond);
776 pthread_cond_destroy(&p->output_cond);
777 av_freep(&p->avpkt.data);
780 av_freep(&p->avctx->priv_data);
781 av_freep(&p->avctx->internal);
782 av_freep(&p->avctx->slice_offset);
788 av_freep(&fctx->threads);
789 pthread_mutex_destroy(&fctx->buffer_mutex);
790 av_freep(&avctx->thread_opaque);
793 static int frame_thread_init(AVCodecContext *avctx)
795 int thread_count = avctx->thread_count;
796 AVCodec *codec = avctx->codec;
797 AVCodecContext *src = avctx;
798 FrameThreadContext *fctx;
802 int nb_cpus = ff_get_logical_cpus(avctx);
803 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
805 // use number of cores + 1 as thread count if there is more than one
807 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
809 thread_count = avctx->thread_count = 1;
812 if (thread_count <= 1) {
813 avctx->active_thread_type = 0;
817 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
819 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
820 pthread_mutex_init(&fctx->buffer_mutex, NULL);
823 for (i = 0; i < thread_count; i++) {
824 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
825 PerThreadContext *p = &fctx->threads[i];
827 pthread_mutex_init(&p->mutex, NULL);
828 pthread_mutex_init(&p->progress_mutex, NULL);
829 pthread_cond_init(&p->input_cond, NULL);
830 pthread_cond_init(&p->progress_cond, NULL);
831 pthread_cond_init(&p->output_cond, NULL);
837 err = AVERROR(ENOMEM);
842 copy->thread_opaque = p;
843 copy->pkt = &p->avpkt;
849 err = codec->init(copy);
851 update_context_from_thread(avctx, copy, 1);
853 copy->priv_data = av_malloc(codec->priv_data_size);
854 if (!copy->priv_data) {
855 err = AVERROR(ENOMEM);
858 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
859 copy->internal = av_malloc(sizeof(AVCodecInternal));
860 if (!copy->internal) {
861 err = AVERROR(ENOMEM);
864 *copy->internal = *src->internal;
865 copy->internal->is_copy = 1;
867 if (codec->init_thread_copy)
868 err = codec->init_thread_copy(copy);
873 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
874 p->thread_init= !err;
882 frame_thread_free(avctx, i+1);
887 void ff_thread_flush(AVCodecContext *avctx)
890 FrameThreadContext *fctx = avctx->thread_opaque;
892 if (!avctx->thread_opaque) return;
894 park_frame_worker_threads(fctx, avctx->thread_count);
895 if (fctx->prev_thread) {
896 if (fctx->prev_thread != &fctx->threads[0])
897 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
898 if (avctx->codec->flush)
899 avctx->codec->flush(fctx->threads[0].avctx);
902 fctx->next_decoding = fctx->next_finished = 0;
904 fctx->prev_thread = NULL;
905 for (i = 0; i < avctx->thread_count; i++) {
906 PerThreadContext *p = &fctx->threads[i];
907 // Make sure decode flush calls with size=0 won't return old frames
910 release_delayed_buffers(p);
914 static volatile int *allocate_progress(PerThreadContext *p)
918 for (i = 0; i < MAX_BUFFERS; i++)
919 if (!p->progress_used[i]) break;
921 if (i == MAX_BUFFERS) {
922 av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
926 p->progress_used[i] = 1;
928 return p->progress[i];
931 int ff_thread_can_start_frame(AVCodecContext *avctx)
933 PerThreadContext *p = avctx->thread_opaque;
934 if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
935 (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&
936 avctx->get_buffer != avcodec_default_get_buffer))) {
942 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
944 PerThreadContext *p = avctx->thread_opaque;
946 volatile int *progress;
950 ff_init_buffer_info(avctx, f);
952 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
953 f->thread_opaque = NULL;
954 return avctx->get_buffer(avctx, f);
957 if (p->state != STATE_SETTING_UP &&
958 (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&
959 avctx->get_buffer != avcodec_default_get_buffer))) {
960 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
964 pthread_mutex_lock(&p->parent->buffer_mutex);
965 f->thread_opaque = (int*)(progress = allocate_progress(p));
968 pthread_mutex_unlock(&p->parent->buffer_mutex);
975 if (avctx->thread_safe_callbacks ||
976 avctx->get_buffer == avcodec_default_get_buffer) {
977 err = avctx->get_buffer(avctx, f);
979 pthread_mutex_lock(&p->progress_mutex);
980 p->requested_frame = f;
981 p->state = STATE_GET_BUFFER;
982 pthread_cond_broadcast(&p->progress_cond);
984 while (p->state != STATE_SETTING_UP)
985 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
989 pthread_mutex_unlock(&p->progress_mutex);
991 if (!avctx->codec->update_thread_context)
992 ff_thread_finish_setup(avctx);
997 f->thread_opaque = NULL;
999 pthread_mutex_unlock(&p->parent->buffer_mutex);
1004 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
1006 PerThreadContext *p = avctx->thread_opaque;
1007 FrameThreadContext *fctx;
1009 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
1010 avctx->release_buffer(avctx, f);
1014 if (p->num_released_buffers >= MAX_BUFFERS) {
1015 av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
1019 if(avctx->debug & FF_DEBUG_BUFFERS)
1020 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1023 pthread_mutex_lock(&fctx->buffer_mutex);
1024 p->released_buffers[p->num_released_buffers++] = *f;
1025 pthread_mutex_unlock(&fctx->buffer_mutex);
1026 memset(f->data, 0, sizeof(f->data));
1030 * Set the threading algorithms used.
1032 * Threading requires more than one thread.
1033 * Frame threading requires entire frames to be passed to the codec,
1034 * and introduces extra decoding delay, so is incompatible with low_delay.
1036 * @param avctx The context.
1038 static void validate_thread_parameters(AVCodecContext *avctx)
1040 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1041 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1042 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1043 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1044 if (avctx->thread_count == 1) {
1045 avctx->active_thread_type = 0;
1046 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1047 avctx->active_thread_type = FF_THREAD_FRAME;
1048 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1049 avctx->thread_type & FF_THREAD_SLICE) {
1050 avctx->active_thread_type = FF_THREAD_SLICE;
1051 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1052 avctx->thread_count = 1;
1053 avctx->active_thread_type = 0;
1056 if (avctx->thread_count > MAX_AUTO_THREADS)
1057 av_log(avctx, AV_LOG_WARNING,
1058 "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1059 avctx->thread_count, MAX_AUTO_THREADS);
1062 int ff_thread_init(AVCodecContext *avctx)
1064 if (avctx->thread_opaque) {
1065 av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
1074 validate_thread_parameters(avctx);
1076 if (avctx->active_thread_type&FF_THREAD_SLICE)
1077 return thread_init(avctx);
1078 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1079 return frame_thread_init(avctx);
1085 void ff_thread_free(AVCodecContext *avctx)
1087 if (avctx->active_thread_type&FF_THREAD_FRAME)
1088 frame_thread_free(avctx, avctx->thread_count);