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 Libav.
11 * Libav 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 * Libav 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 Libav; 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/sysctl.h>
59 #include "w32pthreads.h"
62 typedef int (action_func)(AVCodecContext *c, void *arg);
63 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
65 typedef struct ThreadContext {
75 pthread_cond_t last_job_cond;
76 pthread_cond_t current_job_cond;
77 pthread_mutex_t current_job_lock;
82 /// Max number of frame buffers that can be allocated when using frame threads.
83 #define MAX_BUFFERS (32+1)
86 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
88 typedef struct PerThreadContext {
89 struct FrameThreadContext *parent;
93 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
94 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
95 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
97 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
98 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
100 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
102 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
103 int allocated_buf_size; ///< Size allocated for avpkt.data
105 AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
106 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
107 int result; ///< The result of the last codec decode/encode() call.
110 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
111 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
112 STATE_GET_BUFFER, /**<
113 * Set when the codec calls get_buffer().
114 * State is returned to STATE_SETTING_UP afterwards.
116 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
120 * Array of frames passed to ff_thread_release_buffer().
121 * Frames are released after all threads referencing them are finished.
123 AVFrame released_buffers[MAX_BUFFERS];
124 int num_released_buffers;
127 * Array of progress values used by ff_thread_get_buffer().
129 int progress[MAX_BUFFERS][2];
130 uint8_t progress_used[MAX_BUFFERS];
132 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
136 * Context stored in the client AVCodecContext thread_opaque.
138 typedef struct FrameThreadContext {
139 PerThreadContext *threads; ///< The contexts for each thread.
140 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
142 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
144 int next_decoding; ///< The next context to submit a packet to.
145 int next_finished; ///< The next context to return output from.
148 * Set for the first N packets, where N is the number of threads.
149 * While it is set, ff_thread_en/decode_frame won't return any results.
152 int die; ///< Set when threads should exit.
153 } FrameThreadContext;
156 /* H264 slice threading seems to be buggy with more than 16 threads,
157 * limit the number of threads to 16 for automatic detection */
158 #define MAX_AUTO_THREADS 16
160 static int get_logical_cpus(AVCodecContext *avctx)
162 int ret, nb_cpus = 1;
163 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
168 ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
170 nb_cpus = CPU_COUNT(&cpuset);
172 #elif HAVE_GETPROCESSAFFINITYMASK
173 DWORD_PTR proc_aff, sys_aff;
174 ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
176 nb_cpus = av_popcount64(proc_aff);
177 #elif HAVE_SYSCTL && defined(HW_NCPU)
178 int mib[2] = { CTL_HW, HW_NCPU };
179 size_t len = sizeof(nb_cpus);
181 ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
184 #elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
185 nb_cpus = sysconf(_SC_NPROC_ONLN);
186 #elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
187 nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
189 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
194 static void* attribute_align_arg worker(void *v)
196 AVCodecContext *avctx = v;
197 ThreadContext *c = avctx->thread_opaque;
198 int our_job = c->job_count;
199 int thread_count = avctx->thread_count;
202 pthread_mutex_lock(&c->current_job_lock);
203 self_id = c->current_job++;
205 while (our_job >= c->job_count) {
206 if (c->current_job == thread_count + c->job_count)
207 pthread_cond_signal(&c->last_job_cond);
209 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
213 pthread_mutex_unlock(&c->current_job_lock);
217 pthread_mutex_unlock(&c->current_job_lock);
219 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
220 c->func2(avctx, c->args, our_job, self_id);
222 pthread_mutex_lock(&c->current_job_lock);
223 our_job = c->current_job++;
227 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
229 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
230 pthread_mutex_unlock(&c->current_job_lock);
233 static void thread_free(AVCodecContext *avctx)
235 ThreadContext *c = avctx->thread_opaque;
238 pthread_mutex_lock(&c->current_job_lock);
240 pthread_cond_broadcast(&c->current_job_cond);
241 pthread_mutex_unlock(&c->current_job_lock);
243 for (i=0; i<avctx->thread_count; i++)
244 pthread_join(c->workers[i], NULL);
246 pthread_mutex_destroy(&c->current_job_lock);
247 pthread_cond_destroy(&c->current_job_cond);
248 pthread_cond_destroy(&c->last_job_cond);
250 av_freep(&avctx->thread_opaque);
253 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
255 ThreadContext *c= avctx->thread_opaque;
258 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
259 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
264 pthread_mutex_lock(&c->current_job_lock);
266 c->current_job = avctx->thread_count;
267 c->job_count = job_count;
268 c->job_size = job_size;
273 c->rets_count = job_count;
275 c->rets = &dummy_ret;
278 pthread_cond_broadcast(&c->current_job_cond);
280 avcodec_thread_park_workers(c, avctx->thread_count);
285 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
287 ThreadContext *c= avctx->thread_opaque;
289 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
292 static int thread_init(AVCodecContext *avctx)
296 int thread_count = avctx->thread_count;
299 int nb_cpus = get_logical_cpus(avctx);
300 // use number of cores + 1 as thread count if there is more than one
302 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
304 thread_count = avctx->thread_count = 1;
307 if (thread_count <= 1) {
308 avctx->active_thread_type = 0;
312 c = av_mallocz(sizeof(ThreadContext));
316 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
322 avctx->thread_opaque = c;
327 pthread_cond_init(&c->current_job_cond, NULL);
328 pthread_cond_init(&c->last_job_cond, NULL);
329 pthread_mutex_init(&c->current_job_lock, NULL);
330 pthread_mutex_lock(&c->current_job_lock);
331 for (i=0; i<thread_count; i++) {
332 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
333 avctx->thread_count = i;
334 pthread_mutex_unlock(&c->current_job_lock);
335 ff_thread_free(avctx);
340 avcodec_thread_park_workers(c, thread_count);
342 avctx->execute = avcodec_thread_execute;
343 avctx->execute2 = avcodec_thread_execute2;
348 * Codec worker thread.
350 * Automatically calls ff_thread_finish_setup() if the codec does
351 * not provide an update_thread_context method, or if the codec returns
354 static attribute_align_arg void *frame_worker_thread(void *arg)
356 PerThreadContext *p = arg;
357 FrameThreadContext *fctx = p->parent;
358 AVCodecContext *avctx = p->avctx;
359 AVCodec *codec = avctx->codec;
362 if (p->state == STATE_INPUT_READY && !fctx->die) {
363 pthread_mutex_lock(&p->mutex);
364 while (p->state == STATE_INPUT_READY && !fctx->die)
365 pthread_cond_wait(&p->input_cond, &p->mutex);
366 pthread_mutex_unlock(&p->mutex);
369 if (fctx->die) break;
371 if (!codec->update_thread_context && avctx->thread_safe_callbacks)
372 ff_thread_finish_setup(avctx);
374 pthread_mutex_lock(&p->mutex);
375 avcodec_get_frame_defaults(&p->frame);
377 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
379 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
381 p->state = STATE_INPUT_READY;
383 pthread_mutex_lock(&p->progress_mutex);
384 pthread_cond_signal(&p->output_cond);
385 pthread_mutex_unlock(&p->progress_mutex);
387 pthread_mutex_unlock(&p->mutex);
394 * Update the next thread's AVCodecContext with values from the reference thread's context.
396 * @param dst The destination context.
397 * @param src The source context.
398 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
400 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
405 dst->sub_id = src->sub_id;
406 dst->time_base = src->time_base;
407 dst->width = src->width;
408 dst->height = src->height;
409 dst->pix_fmt = src->pix_fmt;
411 dst->coded_width = src->coded_width;
412 dst->coded_height = src->coded_height;
414 dst->has_b_frames = src->has_b_frames;
415 dst->idct_algo = src->idct_algo;
416 dst->slice_count = src->slice_count;
418 dst->bits_per_coded_sample = src->bits_per_coded_sample;
419 dst->sample_aspect_ratio = src->sample_aspect_ratio;
420 dst->dtg_active_format = src->dtg_active_format;
422 dst->profile = src->profile;
423 dst->level = src->level;
425 dst->bits_per_raw_sample = src->bits_per_raw_sample;
426 dst->ticks_per_frame = src->ticks_per_frame;
427 dst->color_primaries = src->color_primaries;
429 dst->color_trc = src->color_trc;
430 dst->colorspace = src->colorspace;
431 dst->color_range = src->color_range;
432 dst->chroma_sample_location = src->chroma_sample_location;
436 dst->coded_frame = src->coded_frame;
438 if (dst->codec->update_thread_context)
439 err = dst->codec->update_thread_context(dst, src);
446 * Update the next thread's AVCodecContext with values set by the user.
448 * @param dst The destination context.
449 * @param src The source context.
451 static void update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
453 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
454 dst->flags = src->flags;
456 dst->draw_horiz_band= src->draw_horiz_band;
457 dst->get_buffer = src->get_buffer;
458 dst->release_buffer = src->release_buffer;
460 dst->opaque = src->opaque;
461 dst->dsp_mask = src->dsp_mask;
462 dst->debug = src->debug;
463 dst->debug_mv = src->debug_mv;
465 dst->slice_flags = src->slice_flags;
466 dst->flags2 = src->flags2;
468 copy_fields(skip_loop_filter, bidir_refine);
470 dst->frame_number = src->frame_number;
471 dst->reordered_opaque = src->reordered_opaque;
475 static void free_progress(AVFrame *f)
477 PerThreadContext *p = f->owner->thread_opaque;
478 int *progress = f->thread_opaque;
480 p->progress_used[(progress - p->progress[0]) / 2] = 0;
483 /// Releases the buffers that this decoding thread was the last user of.
484 static void release_delayed_buffers(PerThreadContext *p)
486 FrameThreadContext *fctx = p->parent;
488 while (p->num_released_buffers > 0) {
491 pthread_mutex_lock(&fctx->buffer_mutex);
492 f = &p->released_buffers[--p->num_released_buffers];
494 f->thread_opaque = NULL;
496 f->owner->release_buffer(f->owner, f);
497 pthread_mutex_unlock(&fctx->buffer_mutex);
501 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
503 FrameThreadContext *fctx = p->parent;
504 PerThreadContext *prev_thread = fctx->prev_thread;
505 AVCodec *codec = p->avctx->codec;
506 uint8_t *buf = p->avpkt.data;
508 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
510 pthread_mutex_lock(&p->mutex);
512 release_delayed_buffers(p);
516 if (prev_thread->state == STATE_SETTING_UP) {
517 pthread_mutex_lock(&prev_thread->progress_mutex);
518 while (prev_thread->state == STATE_SETTING_UP)
519 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
520 pthread_mutex_unlock(&prev_thread->progress_mutex);
523 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
525 pthread_mutex_unlock(&p->mutex);
530 av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
533 memcpy(buf, avpkt->data, avpkt->size);
534 memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
536 p->state = STATE_SETTING_UP;
537 pthread_cond_signal(&p->input_cond);
538 pthread_mutex_unlock(&p->mutex);
541 * If the client doesn't have a thread-safe get_buffer(),
542 * then decoding threads call back to the main thread,
543 * and it calls back to the client here.
546 if (!p->avctx->thread_safe_callbacks &&
547 p->avctx->get_buffer != avcodec_default_get_buffer) {
548 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
549 pthread_mutex_lock(&p->progress_mutex);
550 while (p->state == STATE_SETTING_UP)
551 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
553 if (p->state == STATE_GET_BUFFER) {
554 p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
555 p->state = STATE_SETTING_UP;
556 pthread_cond_signal(&p->progress_cond);
558 pthread_mutex_unlock(&p->progress_mutex);
562 fctx->prev_thread = p;
563 fctx->next_decoding++;
568 int ff_thread_decode_frame(AVCodecContext *avctx,
569 AVFrame *picture, int *got_picture_ptr,
572 FrameThreadContext *fctx = avctx->thread_opaque;
573 int finished = fctx->next_finished;
578 * Submit a packet to the next decoding thread.
581 p = &fctx->threads[fctx->next_decoding];
582 update_context_from_user(p->avctx, avctx);
583 err = submit_packet(p, avpkt);
587 * If we're still receiving the initial packets, don't return a frame.
590 if (fctx->delaying && avpkt->size) {
591 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
598 * Return the next available frame from the oldest thread.
599 * If we're at the end of the stream, then we have to skip threads that
600 * didn't output a frame, because we don't want to accidentally signal
601 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
605 p = &fctx->threads[finished++];
607 if (p->state != STATE_INPUT_READY) {
608 pthread_mutex_lock(&p->progress_mutex);
609 while (p->state != STATE_INPUT_READY)
610 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
611 pthread_mutex_unlock(&p->progress_mutex);
615 *got_picture_ptr = p->got_frame;
616 picture->pkt_dts = p->avpkt.dts;
617 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
618 picture->width = avctx->width;
619 picture->height = avctx->height;
620 picture->format = avctx->pix_fmt;
623 * A later call with avkpt->size == 0 may loop over all threads,
624 * including this one, searching for a frame to return before being
625 * stopped by the "finished != fctx->next_finished" condition.
626 * Make sure we don't mistakenly return the same frame again.
630 if (finished >= avctx->thread_count) finished = 0;
631 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
633 update_context_from_thread(avctx, p->avctx, 1);
635 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
637 fctx->next_finished = finished;
639 /* return the size of the consumed packet if no error occurred */
640 return (p->result >= 0) ? avpkt->size : p->result;
643 void ff_thread_report_progress(AVFrame *f, int n, int field)
646 int *progress = f->thread_opaque;
648 if (!progress || progress[field] >= n) return;
650 p = f->owner->thread_opaque;
652 if (f->owner->debug&FF_DEBUG_THREADS)
653 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
655 pthread_mutex_lock(&p->progress_mutex);
657 pthread_cond_broadcast(&p->progress_cond);
658 pthread_mutex_unlock(&p->progress_mutex);
661 void ff_thread_await_progress(AVFrame *f, int n, int field)
664 int *progress = f->thread_opaque;
666 if (!progress || progress[field] >= n) return;
668 p = f->owner->thread_opaque;
670 if (f->owner->debug&FF_DEBUG_THREADS)
671 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
673 pthread_mutex_lock(&p->progress_mutex);
674 while (progress[field] < n)
675 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
676 pthread_mutex_unlock(&p->progress_mutex);
679 void ff_thread_finish_setup(AVCodecContext *avctx) {
680 PerThreadContext *p = avctx->thread_opaque;
682 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
684 pthread_mutex_lock(&p->progress_mutex);
685 p->state = STATE_SETUP_FINISHED;
686 pthread_cond_broadcast(&p->progress_cond);
687 pthread_mutex_unlock(&p->progress_mutex);
690 /// Waits for all threads to finish.
691 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
695 for (i = 0; i < thread_count; i++) {
696 PerThreadContext *p = &fctx->threads[i];
698 if (p->state != STATE_INPUT_READY) {
699 pthread_mutex_lock(&p->progress_mutex);
700 while (p->state != STATE_INPUT_READY)
701 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
702 pthread_mutex_unlock(&p->progress_mutex);
707 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
709 FrameThreadContext *fctx = avctx->thread_opaque;
710 AVCodec *codec = avctx->codec;
713 park_frame_worker_threads(fctx, thread_count);
715 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
716 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
720 for (i = 0; i < thread_count; i++) {
721 PerThreadContext *p = &fctx->threads[i];
723 pthread_mutex_lock(&p->mutex);
724 pthread_cond_signal(&p->input_cond);
725 pthread_mutex_unlock(&p->mutex);
728 pthread_join(p->thread, NULL);
731 codec->close(p->avctx);
735 release_delayed_buffers(p);
738 for (i = 0; i < thread_count; i++) {
739 PerThreadContext *p = &fctx->threads[i];
741 avcodec_default_free_buffers(p->avctx);
743 pthread_mutex_destroy(&p->mutex);
744 pthread_mutex_destroy(&p->progress_mutex);
745 pthread_cond_destroy(&p->input_cond);
746 pthread_cond_destroy(&p->progress_cond);
747 pthread_cond_destroy(&p->output_cond);
748 av_freep(&p->avpkt.data);
751 av_freep(&p->avctx->priv_data);
752 av_freep(&p->avctx->internal);
758 av_freep(&fctx->threads);
759 pthread_mutex_destroy(&fctx->buffer_mutex);
760 av_freep(&avctx->thread_opaque);
763 static int frame_thread_init(AVCodecContext *avctx)
765 int thread_count = avctx->thread_count;
766 AVCodec *codec = avctx->codec;
767 AVCodecContext *src = avctx;
768 FrameThreadContext *fctx;
772 int nb_cpus = get_logical_cpus(avctx);
773 // use number of cores + 1 as thread count if there is more than one
775 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
777 thread_count = avctx->thread_count = 1;
780 if (thread_count <= 1) {
781 avctx->active_thread_type = 0;
785 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
787 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
788 pthread_mutex_init(&fctx->buffer_mutex, NULL);
791 for (i = 0; i < thread_count; i++) {
792 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
793 PerThreadContext *p = &fctx->threads[i];
795 pthread_mutex_init(&p->mutex, NULL);
796 pthread_mutex_init(&p->progress_mutex, NULL);
797 pthread_cond_init(&p->input_cond, NULL);
798 pthread_cond_init(&p->progress_cond, NULL);
799 pthread_cond_init(&p->output_cond, NULL);
805 err = AVERROR(ENOMEM);
810 copy->thread_opaque = p;
811 copy->pkt = &p->avpkt;
817 err = codec->init(copy);
819 update_context_from_thread(avctx, copy, 1);
821 copy->priv_data = av_malloc(codec->priv_data_size);
822 if (!copy->priv_data) {
823 err = AVERROR(ENOMEM);
826 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
827 copy->internal = av_malloc(sizeof(AVCodecInternal));
828 if (!copy->internal) {
829 err = AVERROR(ENOMEM);
832 *copy->internal = *src->internal;
833 copy->internal->is_copy = 1;
835 if (codec->init_thread_copy)
836 err = codec->init_thread_copy(copy);
841 if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
848 frame_thread_free(avctx, i+1);
853 void ff_thread_flush(AVCodecContext *avctx)
855 FrameThreadContext *fctx = avctx->thread_opaque;
857 if (!avctx->thread_opaque) return;
859 park_frame_worker_threads(fctx, avctx->thread_count);
860 if (fctx->prev_thread) {
861 if (fctx->prev_thread != &fctx->threads[0])
862 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
863 if (avctx->codec->flush)
864 avctx->codec->flush(fctx->threads[0].avctx);
867 fctx->next_decoding = fctx->next_finished = 0;
869 fctx->prev_thread = NULL;
872 static int *allocate_progress(PerThreadContext *p)
876 for (i = 0; i < MAX_BUFFERS; i++)
877 if (!p->progress_used[i]) break;
879 if (i == MAX_BUFFERS) {
880 av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
884 p->progress_used[i] = 1;
886 return p->progress[i];
889 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
891 PerThreadContext *p = avctx->thread_opaque;
896 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
897 f->thread_opaque = NULL;
898 return avctx->get_buffer(avctx, f);
901 if (p->state != STATE_SETTING_UP &&
902 (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
903 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
907 pthread_mutex_lock(&p->parent->buffer_mutex);
908 f->thread_opaque = progress = allocate_progress(p);
911 pthread_mutex_unlock(&p->parent->buffer_mutex);
918 if (avctx->thread_safe_callbacks ||
919 avctx->get_buffer == avcodec_default_get_buffer) {
920 err = avctx->get_buffer(avctx, f);
922 p->requested_frame = f;
923 p->state = STATE_GET_BUFFER;
924 pthread_mutex_lock(&p->progress_mutex);
925 pthread_cond_signal(&p->progress_cond);
927 while (p->state != STATE_SETTING_UP)
928 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
932 pthread_mutex_unlock(&p->progress_mutex);
934 if (!avctx->codec->update_thread_context)
935 ff_thread_finish_setup(avctx);
938 pthread_mutex_unlock(&p->parent->buffer_mutex);
943 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
945 PerThreadContext *p = avctx->thread_opaque;
946 FrameThreadContext *fctx;
948 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
949 avctx->release_buffer(avctx, f);
953 if (p->num_released_buffers >= MAX_BUFFERS) {
954 av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
958 if(avctx->debug & FF_DEBUG_BUFFERS)
959 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
962 pthread_mutex_lock(&fctx->buffer_mutex);
963 p->released_buffers[p->num_released_buffers++] = *f;
964 pthread_mutex_unlock(&fctx->buffer_mutex);
965 memset(f->data, 0, sizeof(f->data));
969 * Set the threading algorithms used.
971 * Threading requires more than one thread.
972 * Frame threading requires entire frames to be passed to the codec,
973 * and introduces extra decoding delay, so is incompatible with low_delay.
975 * @param avctx The context.
977 static void validate_thread_parameters(AVCodecContext *avctx)
979 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
980 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
981 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
982 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
983 if (avctx->thread_count == 1) {
984 avctx->active_thread_type = 0;
985 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
986 avctx->active_thread_type = FF_THREAD_FRAME;
987 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
988 avctx->thread_type & FF_THREAD_SLICE) {
989 avctx->active_thread_type = FF_THREAD_SLICE;
990 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
991 avctx->thread_count = 1;
992 avctx->active_thread_type = 0;
996 int ff_thread_init(AVCodecContext *avctx)
998 if (avctx->thread_opaque) {
999 av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
1008 validate_thread_parameters(avctx);
1010 if (avctx->active_thread_type&FF_THREAD_SLICE)
1011 return thread_init(avctx);
1012 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1013 return frame_thread_init(avctx);
1019 void ff_thread_free(AVCodecContext *avctx)
1021 if (avctx->active_thread_type&FF_THREAD_FRAME)
1022 frame_thread_free(avctx, avctx->thread_count);