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
37 #elif HAVE_GETSYSTEMINFO
41 #include <sys/param.h>
43 #include <sys/types.h>
44 #include <sys/sysctl.h>
54 #include "w32pthreads.h"
57 typedef int (action_func)(AVCodecContext *c, void *arg);
58 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
60 typedef struct ThreadContext {
70 pthread_cond_t last_job_cond;
71 pthread_cond_t current_job_cond;
72 pthread_mutex_t current_job_lock;
77 /// Max number of frame buffers that can be allocated when using frame threads.
78 #define MAX_BUFFERS (32+1)
81 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
83 typedef struct PerThreadContext {
84 struct FrameThreadContext *parent;
88 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
89 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
90 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
92 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
93 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
95 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
97 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
98 int allocated_buf_size; ///< Size allocated for avpkt.data
100 AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
101 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
102 int result; ///< The result of the last codec decode/encode() call.
105 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
106 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
107 STATE_GET_BUFFER, /**<
108 * Set when the codec calls get_buffer().
109 * State is returned to STATE_SETTING_UP afterwards.
111 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
115 * Array of frames passed to ff_thread_release_buffer().
116 * Frames are released after all threads referencing them are finished.
118 AVFrame released_buffers[MAX_BUFFERS];
119 int num_released_buffers;
122 * Array of progress values used by ff_thread_get_buffer().
124 int progress[MAX_BUFFERS][2];
125 uint8_t progress_used[MAX_BUFFERS];
127 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
131 * Context stored in the client AVCodecContext thread_opaque.
133 typedef struct FrameThreadContext {
134 PerThreadContext *threads; ///< The contexts for each thread.
135 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
137 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
139 int next_decoding; ///< The next context to submit a packet to.
140 int next_finished; ///< The next context to return output from.
143 * Set for the first N packets, where N is the number of threads.
144 * While it is set, ff_thread_en/decode_frame won't return any results.
147 int die; ///< Set when threads should exit.
148 } FrameThreadContext;
151 /* H264 slice threading seems to be buggy with more than 16 threads,
152 * limit the number of threads to 16 for automatic detection */
153 #define MAX_AUTO_THREADS 16
155 static int get_logical_cpus(AVCodecContext *avctx)
157 int ret, nb_cpus = 1;
158 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
163 ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
165 nb_cpus = CPU_COUNT(&cpuset);
167 #elif HAVE_GETSYSTEMINFO
169 GetSystemInfo(&sysinfo);
170 nb_cpus = sysinfo.dwNumberOfProcessors;
171 #elif HAVE_SYSCTL && defined(HW_NCPU)
172 int mib[2] = { CTL_HW, HW_NCPU };
173 size_t len = sizeof(nb_cpus);
175 ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
179 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
180 return FFMIN(nb_cpus, MAX_AUTO_THREADS);
184 static void* attribute_align_arg worker(void *v)
186 AVCodecContext *avctx = v;
187 ThreadContext *c = avctx->thread_opaque;
188 int our_job = c->job_count;
189 int thread_count = avctx->thread_count;
192 pthread_mutex_lock(&c->current_job_lock);
193 self_id = c->current_job++;
195 while (our_job >= c->job_count) {
196 if (c->current_job == thread_count + c->job_count)
197 pthread_cond_signal(&c->last_job_cond);
199 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
203 pthread_mutex_unlock(&c->current_job_lock);
207 pthread_mutex_unlock(&c->current_job_lock);
209 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
210 c->func2(avctx, c->args, our_job, self_id);
212 pthread_mutex_lock(&c->current_job_lock);
213 our_job = c->current_job++;
217 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
219 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
220 pthread_mutex_unlock(&c->current_job_lock);
223 static void thread_free(AVCodecContext *avctx)
225 ThreadContext *c = avctx->thread_opaque;
228 pthread_mutex_lock(&c->current_job_lock);
230 pthread_cond_broadcast(&c->current_job_cond);
231 pthread_mutex_unlock(&c->current_job_lock);
233 for (i=0; i<avctx->thread_count; i++)
234 pthread_join(c->workers[i], NULL);
236 pthread_mutex_destroy(&c->current_job_lock);
237 pthread_cond_destroy(&c->current_job_cond);
238 pthread_cond_destroy(&c->last_job_cond);
240 av_freep(&avctx->thread_opaque);
243 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
245 ThreadContext *c= avctx->thread_opaque;
248 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
249 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
254 pthread_mutex_lock(&c->current_job_lock);
256 c->current_job = avctx->thread_count;
257 c->job_count = job_count;
258 c->job_size = job_size;
263 c->rets_count = job_count;
265 c->rets = &dummy_ret;
268 pthread_cond_broadcast(&c->current_job_cond);
270 avcodec_thread_park_workers(c, avctx->thread_count);
275 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
277 ThreadContext *c= avctx->thread_opaque;
279 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
282 static int thread_init(AVCodecContext *avctx)
286 int thread_count = avctx->thread_count;
289 int nb_cpus = get_logical_cpus(avctx);
290 // use number of cores + 1 as thread count if there is motre than one
292 thread_count = avctx->thread_count = nb_cpus + 1;
295 if (thread_count <= 1) {
296 avctx->active_thread_type = 0;
300 c = av_mallocz(sizeof(ThreadContext));
304 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
310 avctx->thread_opaque = c;
315 pthread_cond_init(&c->current_job_cond, NULL);
316 pthread_cond_init(&c->last_job_cond, NULL);
317 pthread_mutex_init(&c->current_job_lock, NULL);
318 pthread_mutex_lock(&c->current_job_lock);
319 for (i=0; i<thread_count; i++) {
320 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
321 avctx->thread_count = i;
322 pthread_mutex_unlock(&c->current_job_lock);
323 ff_thread_free(avctx);
328 avcodec_thread_park_workers(c, thread_count);
330 avctx->execute = avcodec_thread_execute;
331 avctx->execute2 = avcodec_thread_execute2;
336 * Codec worker thread.
338 * Automatically calls ff_thread_finish_setup() if the codec does
339 * not provide an update_thread_context method, or if the codec returns
342 static attribute_align_arg void *frame_worker_thread(void *arg)
344 PerThreadContext *p = arg;
345 FrameThreadContext *fctx = p->parent;
346 AVCodecContext *avctx = p->avctx;
347 AVCodec *codec = avctx->codec;
350 if (p->state == STATE_INPUT_READY && !fctx->die) {
351 pthread_mutex_lock(&p->mutex);
352 while (p->state == STATE_INPUT_READY && !fctx->die)
353 pthread_cond_wait(&p->input_cond, &p->mutex);
354 pthread_mutex_unlock(&p->mutex);
357 if (fctx->die) break;
359 if (!codec->update_thread_context && avctx->thread_safe_callbacks)
360 ff_thread_finish_setup(avctx);
362 pthread_mutex_lock(&p->mutex);
363 avcodec_get_frame_defaults(&p->frame);
365 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
367 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
369 p->state = STATE_INPUT_READY;
371 pthread_mutex_lock(&p->progress_mutex);
372 pthread_cond_signal(&p->output_cond);
373 pthread_mutex_unlock(&p->progress_mutex);
375 pthread_mutex_unlock(&p->mutex);
382 * Update the next thread's AVCodecContext with values from the reference thread's context.
384 * @param dst The destination context.
385 * @param src The source context.
386 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
388 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
393 dst->sub_id = src->sub_id;
394 dst->time_base = src->time_base;
395 dst->width = src->width;
396 dst->height = src->height;
397 dst->pix_fmt = src->pix_fmt;
399 dst->coded_width = src->coded_width;
400 dst->coded_height = src->coded_height;
402 dst->has_b_frames = src->has_b_frames;
403 dst->idct_algo = src->idct_algo;
404 dst->slice_count = src->slice_count;
406 dst->bits_per_coded_sample = src->bits_per_coded_sample;
407 dst->sample_aspect_ratio = src->sample_aspect_ratio;
408 dst->dtg_active_format = src->dtg_active_format;
410 dst->profile = src->profile;
411 dst->level = src->level;
413 dst->bits_per_raw_sample = src->bits_per_raw_sample;
414 dst->ticks_per_frame = src->ticks_per_frame;
415 dst->color_primaries = src->color_primaries;
417 dst->color_trc = src->color_trc;
418 dst->colorspace = src->colorspace;
419 dst->color_range = src->color_range;
420 dst->chroma_sample_location = src->chroma_sample_location;
424 dst->coded_frame = src->coded_frame;
426 if (dst->codec->update_thread_context)
427 err = dst->codec->update_thread_context(dst, src);
434 * Update the next thread's AVCodecContext with values set by the user.
436 * @param dst The destination context.
437 * @param src The source context.
439 static void update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
441 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
442 dst->flags = src->flags;
444 dst->draw_horiz_band= src->draw_horiz_band;
445 dst->get_buffer = src->get_buffer;
446 dst->release_buffer = src->release_buffer;
448 dst->opaque = src->opaque;
449 dst->dsp_mask = src->dsp_mask;
450 dst->debug = src->debug;
451 dst->debug_mv = src->debug_mv;
453 dst->slice_flags = src->slice_flags;
454 dst->flags2 = src->flags2;
456 copy_fields(skip_loop_filter, bidir_refine);
458 dst->frame_number = src->frame_number;
459 dst->reordered_opaque = src->reordered_opaque;
463 static void free_progress(AVFrame *f)
465 PerThreadContext *p = f->owner->thread_opaque;
466 int *progress = f->thread_opaque;
468 p->progress_used[(progress - p->progress[0]) / 2] = 0;
471 /// Releases the buffers that this decoding thread was the last user of.
472 static void release_delayed_buffers(PerThreadContext *p)
474 FrameThreadContext *fctx = p->parent;
476 while (p->num_released_buffers > 0) {
479 pthread_mutex_lock(&fctx->buffer_mutex);
480 f = &p->released_buffers[--p->num_released_buffers];
482 f->thread_opaque = NULL;
484 f->owner->release_buffer(f->owner, f);
485 pthread_mutex_unlock(&fctx->buffer_mutex);
489 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
491 FrameThreadContext *fctx = p->parent;
492 PerThreadContext *prev_thread = fctx->prev_thread;
493 AVCodec *codec = p->avctx->codec;
494 uint8_t *buf = p->avpkt.data;
496 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
498 pthread_mutex_lock(&p->mutex);
500 release_delayed_buffers(p);
504 if (prev_thread->state == STATE_SETTING_UP) {
505 pthread_mutex_lock(&prev_thread->progress_mutex);
506 while (prev_thread->state == STATE_SETTING_UP)
507 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
508 pthread_mutex_unlock(&prev_thread->progress_mutex);
511 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
513 pthread_mutex_unlock(&p->mutex);
518 av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
521 memcpy(buf, avpkt->data, avpkt->size);
522 memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
524 p->state = STATE_SETTING_UP;
525 pthread_cond_signal(&p->input_cond);
526 pthread_mutex_unlock(&p->mutex);
529 * If the client doesn't have a thread-safe get_buffer(),
530 * then decoding threads call back to the main thread,
531 * and it calls back to the client here.
534 if (!p->avctx->thread_safe_callbacks &&
535 p->avctx->get_buffer != avcodec_default_get_buffer) {
536 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
537 pthread_mutex_lock(&p->progress_mutex);
538 while (p->state == STATE_SETTING_UP)
539 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
541 if (p->state == STATE_GET_BUFFER) {
542 p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
543 p->state = STATE_SETTING_UP;
544 pthread_cond_signal(&p->progress_cond);
546 pthread_mutex_unlock(&p->progress_mutex);
550 fctx->prev_thread = p;
551 fctx->next_decoding++;
556 int ff_thread_decode_frame(AVCodecContext *avctx,
557 AVFrame *picture, int *got_picture_ptr,
560 FrameThreadContext *fctx = avctx->thread_opaque;
561 int finished = fctx->next_finished;
566 * Submit a packet to the next decoding thread.
569 p = &fctx->threads[fctx->next_decoding];
570 update_context_from_user(p->avctx, avctx);
571 err = submit_packet(p, avpkt);
575 * If we're still receiving the initial packets, don't return a frame.
578 if (fctx->delaying && avpkt->size) {
579 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
586 * Return the next available frame from the oldest thread.
587 * If we're at the end of the stream, then we have to skip threads that
588 * didn't output a frame, because we don't want to accidentally signal
589 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
593 p = &fctx->threads[finished++];
595 if (p->state != STATE_INPUT_READY) {
596 pthread_mutex_lock(&p->progress_mutex);
597 while (p->state != STATE_INPUT_READY)
598 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
599 pthread_mutex_unlock(&p->progress_mutex);
603 *got_picture_ptr = p->got_frame;
604 picture->pkt_dts = p->avpkt.dts;
605 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
606 picture->width = avctx->width;
607 picture->height = avctx->height;
608 picture->format = avctx->pix_fmt;
611 * A later call with avkpt->size == 0 may loop over all threads,
612 * including this one, searching for a frame to return before being
613 * stopped by the "finished != fctx->next_finished" condition.
614 * Make sure we don't mistakenly return the same frame again.
618 if (finished >= avctx->thread_count) finished = 0;
619 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
621 update_context_from_thread(avctx, p->avctx, 1);
623 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
625 fctx->next_finished = finished;
627 /* return the size of the consumed packet if no error occurred */
628 return (p->result >= 0) ? avpkt->size : p->result;
631 void ff_thread_report_progress(AVFrame *f, int n, int field)
634 int *progress = f->thread_opaque;
636 if (!progress || progress[field] >= n) return;
638 p = f->owner->thread_opaque;
640 if (f->owner->debug&FF_DEBUG_THREADS)
641 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
643 pthread_mutex_lock(&p->progress_mutex);
645 pthread_cond_broadcast(&p->progress_cond);
646 pthread_mutex_unlock(&p->progress_mutex);
649 void ff_thread_await_progress(AVFrame *f, int n, int field)
652 int *progress = f->thread_opaque;
654 if (!progress || progress[field] >= n) return;
656 p = f->owner->thread_opaque;
658 if (f->owner->debug&FF_DEBUG_THREADS)
659 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
661 pthread_mutex_lock(&p->progress_mutex);
662 while (progress[field] < n)
663 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
664 pthread_mutex_unlock(&p->progress_mutex);
667 void ff_thread_finish_setup(AVCodecContext *avctx) {
668 PerThreadContext *p = avctx->thread_opaque;
670 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
672 pthread_mutex_lock(&p->progress_mutex);
673 p->state = STATE_SETUP_FINISHED;
674 pthread_cond_broadcast(&p->progress_cond);
675 pthread_mutex_unlock(&p->progress_mutex);
678 /// Waits for all threads to finish.
679 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
683 for (i = 0; i < thread_count; i++) {
684 PerThreadContext *p = &fctx->threads[i];
686 if (p->state != STATE_INPUT_READY) {
687 pthread_mutex_lock(&p->progress_mutex);
688 while (p->state != STATE_INPUT_READY)
689 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
690 pthread_mutex_unlock(&p->progress_mutex);
695 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
697 FrameThreadContext *fctx = avctx->thread_opaque;
698 AVCodec *codec = avctx->codec;
701 park_frame_worker_threads(fctx, thread_count);
703 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
704 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
708 for (i = 0; i < thread_count; i++) {
709 PerThreadContext *p = &fctx->threads[i];
711 pthread_mutex_lock(&p->mutex);
712 pthread_cond_signal(&p->input_cond);
713 pthread_mutex_unlock(&p->mutex);
716 pthread_join(p->thread, NULL);
719 codec->close(p->avctx);
723 release_delayed_buffers(p);
726 for (i = 0; i < thread_count; i++) {
727 PerThreadContext *p = &fctx->threads[i];
729 avcodec_default_free_buffers(p->avctx);
731 pthread_mutex_destroy(&p->mutex);
732 pthread_mutex_destroy(&p->progress_mutex);
733 pthread_cond_destroy(&p->input_cond);
734 pthread_cond_destroy(&p->progress_cond);
735 pthread_cond_destroy(&p->output_cond);
736 av_freep(&p->avpkt.data);
739 av_freep(&p->avctx->priv_data);
740 av_freep(&p->avctx->internal);
746 av_freep(&fctx->threads);
747 pthread_mutex_destroy(&fctx->buffer_mutex);
748 av_freep(&avctx->thread_opaque);
751 static int frame_thread_init(AVCodecContext *avctx)
753 int thread_count = avctx->thread_count;
754 AVCodec *codec = avctx->codec;
755 AVCodecContext *src = avctx;
756 FrameThreadContext *fctx;
760 int nb_cpus = get_logical_cpus(avctx);
761 // use number of cores + 1 as thread count if there is motre than one
763 thread_count = avctx->thread_count = nb_cpus + 1;
766 if (thread_count <= 1) {
767 avctx->active_thread_type = 0;
771 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
773 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
774 pthread_mutex_init(&fctx->buffer_mutex, NULL);
777 for (i = 0; i < thread_count; i++) {
778 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
779 PerThreadContext *p = &fctx->threads[i];
781 pthread_mutex_init(&p->mutex, NULL);
782 pthread_mutex_init(&p->progress_mutex, NULL);
783 pthread_cond_init(&p->input_cond, NULL);
784 pthread_cond_init(&p->progress_cond, NULL);
785 pthread_cond_init(&p->output_cond, NULL);
791 err = AVERROR(ENOMEM);
796 copy->thread_opaque = p;
797 copy->pkt = &p->avpkt;
803 err = codec->init(copy);
805 update_context_from_thread(avctx, copy, 1);
807 copy->priv_data = av_malloc(codec->priv_data_size);
808 if (!copy->priv_data) {
809 err = AVERROR(ENOMEM);
812 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
813 copy->internal = av_malloc(sizeof(AVCodecInternal));
814 if (!copy->internal) {
815 err = AVERROR(ENOMEM);
818 *(copy->internal) = *(src->internal);
819 copy->internal->is_copy = 1;
821 if (codec->init_thread_copy)
822 err = codec->init_thread_copy(copy);
827 if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
834 frame_thread_free(avctx, i+1);
839 void ff_thread_flush(AVCodecContext *avctx)
841 FrameThreadContext *fctx = avctx->thread_opaque;
843 if (!avctx->thread_opaque) return;
845 park_frame_worker_threads(fctx, avctx->thread_count);
846 if (fctx->prev_thread) {
847 if (fctx->prev_thread != &fctx->threads[0])
848 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
849 if (avctx->codec->flush)
850 avctx->codec->flush(fctx->threads[0].avctx);
853 fctx->next_decoding = fctx->next_finished = 0;
855 fctx->prev_thread = NULL;
858 static int *allocate_progress(PerThreadContext *p)
862 for (i = 0; i < MAX_BUFFERS; i++)
863 if (!p->progress_used[i]) break;
865 if (i == MAX_BUFFERS) {
866 av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
870 p->progress_used[i] = 1;
872 return p->progress[i];
875 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
877 PerThreadContext *p = avctx->thread_opaque;
882 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
883 f->thread_opaque = NULL;
884 return avctx->get_buffer(avctx, f);
887 if (p->state != STATE_SETTING_UP &&
888 (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
889 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
893 pthread_mutex_lock(&p->parent->buffer_mutex);
894 f->thread_opaque = progress = allocate_progress(p);
897 pthread_mutex_unlock(&p->parent->buffer_mutex);
904 if (avctx->thread_safe_callbacks ||
905 avctx->get_buffer == avcodec_default_get_buffer) {
906 err = avctx->get_buffer(avctx, f);
908 p->requested_frame = f;
909 p->state = STATE_GET_BUFFER;
910 pthread_mutex_lock(&p->progress_mutex);
911 pthread_cond_signal(&p->progress_cond);
913 while (p->state != STATE_SETTING_UP)
914 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
918 pthread_mutex_unlock(&p->progress_mutex);
920 if (!avctx->codec->update_thread_context)
921 ff_thread_finish_setup(avctx);
924 pthread_mutex_unlock(&p->parent->buffer_mutex);
929 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
931 PerThreadContext *p = avctx->thread_opaque;
932 FrameThreadContext *fctx;
934 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
935 avctx->release_buffer(avctx, f);
939 if (p->num_released_buffers >= MAX_BUFFERS) {
940 av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
944 if(avctx->debug & FF_DEBUG_BUFFERS)
945 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
948 pthread_mutex_lock(&fctx->buffer_mutex);
949 p->released_buffers[p->num_released_buffers++] = *f;
950 pthread_mutex_unlock(&fctx->buffer_mutex);
951 memset(f->data, 0, sizeof(f->data));
955 * Set the threading algorithms used.
957 * Threading requires more than one thread.
958 * Frame threading requires entire frames to be passed to the codec,
959 * and introduces extra decoding delay, so is incompatible with low_delay.
961 * @param avctx The context.
963 static void validate_thread_parameters(AVCodecContext *avctx)
965 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
966 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
967 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
968 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
969 if (avctx->thread_count == 1) {
970 avctx->active_thread_type = 0;
971 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
972 avctx->active_thread_type = FF_THREAD_FRAME;
973 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
974 avctx->thread_type & FF_THREAD_SLICE) {
975 avctx->active_thread_type = FF_THREAD_SLICE;
979 int ff_thread_init(AVCodecContext *avctx)
981 if (avctx->thread_opaque) {
982 av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
991 validate_thread_parameters(avctx);
993 if (avctx->active_thread_type&FF_THREAD_SLICE)
994 return thread_init(avctx);
995 else if (avctx->active_thread_type&FF_THREAD_FRAME)
996 return frame_thread_init(avctx);
1002 void ff_thread_free(AVCodecContext *avctx)
1004 if (avctx->active_thread_type&FF_THREAD_FRAME)
1005 frame_thread_free(avctx, avctx->thread_count);