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>
55 #include "libavutil/common.h"
60 #include "w32pthreads.h"
63 typedef int (action_func)(AVCodecContext *c, void *arg);
64 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
66 typedef struct ThreadContext {
76 pthread_cond_t last_job_cond;
77 pthread_cond_t current_job_cond;
78 pthread_mutex_t current_job_lock;
83 /// Max number of frame buffers that can be allocated when using frame threads.
84 #define MAX_BUFFERS (32+1)
87 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
89 typedef struct PerThreadContext {
90 struct FrameThreadContext *parent;
94 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
95 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
96 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
98 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
99 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
101 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
103 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
104 int allocated_buf_size; ///< Size allocated for avpkt.data
106 AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
107 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
108 int result; ///< The result of the last codec decode/encode() call.
111 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
112 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
113 STATE_GET_BUFFER, /**<
114 * Set when the codec calls get_buffer().
115 * State is returned to STATE_SETTING_UP afterwards.
117 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
121 * Array of frames passed to ff_thread_release_buffer().
122 * Frames are released after all threads referencing them are finished.
124 AVFrame released_buffers[MAX_BUFFERS];
125 int num_released_buffers;
128 * Array of progress values used by ff_thread_get_buffer().
130 int progress[MAX_BUFFERS][2];
131 uint8_t progress_used[MAX_BUFFERS];
133 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
137 * Context stored in the client AVCodecContext thread_opaque.
139 typedef struct FrameThreadContext {
140 PerThreadContext *threads; ///< The contexts for each thread.
141 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
143 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
145 int next_decoding; ///< The next context to submit a packet to.
146 int next_finished; ///< The next context to return output from.
149 * Set for the first N packets, where N is the number of threads.
150 * While it is set, ff_thread_en/decode_frame won't return any results.
153 int die; ///< Set when threads should exit.
154 } FrameThreadContext;
157 /* H264 slice threading seems to be buggy with more than 16 threads,
158 * limit the number of threads to 16 for automatic detection */
159 #define MAX_AUTO_THREADS 16
161 static int get_logical_cpus(AVCodecContext *avctx)
163 int ret, nb_cpus = 1;
164 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
169 ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
171 nb_cpus = CPU_COUNT(&cpuset);
173 #elif HAVE_GETPROCESSAFFINITYMASK
174 DWORD_PTR proc_aff, sys_aff;
175 ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
177 nb_cpus = av_popcount64(proc_aff);
178 #elif HAVE_SYSCTL && defined(HW_NCPU)
179 int mib[2] = { CTL_HW, HW_NCPU };
180 size_t len = sizeof(nb_cpus);
182 ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
185 #elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
186 nb_cpus = sysconf(_SC_NPROC_ONLN);
187 #elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
188 nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
190 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
195 static void* attribute_align_arg worker(void *v)
197 AVCodecContext *avctx = v;
198 ThreadContext *c = avctx->thread_opaque;
199 int our_job = c->job_count;
200 int thread_count = avctx->thread_count;
203 pthread_mutex_lock(&c->current_job_lock);
204 self_id = c->current_job++;
206 while (our_job >= c->job_count) {
207 if (c->current_job == thread_count + c->job_count)
208 pthread_cond_signal(&c->last_job_cond);
210 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
214 pthread_mutex_unlock(&c->current_job_lock);
218 pthread_mutex_unlock(&c->current_job_lock);
220 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
221 c->func2(avctx, c->args, our_job, self_id);
223 pthread_mutex_lock(&c->current_job_lock);
224 our_job = c->current_job++;
228 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
230 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
231 pthread_mutex_unlock(&c->current_job_lock);
234 static void thread_free(AVCodecContext *avctx)
236 ThreadContext *c = avctx->thread_opaque;
239 pthread_mutex_lock(&c->current_job_lock);
241 pthread_cond_broadcast(&c->current_job_cond);
242 pthread_mutex_unlock(&c->current_job_lock);
244 for (i=0; i<avctx->thread_count; i++)
245 pthread_join(c->workers[i], NULL);
247 pthread_mutex_destroy(&c->current_job_lock);
248 pthread_cond_destroy(&c->current_job_cond);
249 pthread_cond_destroy(&c->last_job_cond);
251 av_freep(&avctx->thread_opaque);
254 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
256 ThreadContext *c= avctx->thread_opaque;
259 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
260 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
265 pthread_mutex_lock(&c->current_job_lock);
267 c->current_job = avctx->thread_count;
268 c->job_count = job_count;
269 c->job_size = job_size;
274 c->rets_count = job_count;
276 c->rets = &dummy_ret;
279 pthread_cond_broadcast(&c->current_job_cond);
281 avcodec_thread_park_workers(c, avctx->thread_count);
286 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
288 ThreadContext *c= avctx->thread_opaque;
290 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
293 static int thread_init(AVCodecContext *avctx)
297 int thread_count = avctx->thread_count;
300 int nb_cpus = get_logical_cpus(avctx);
301 // use number of cores + 1 as thread count if there is more than one
303 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
305 thread_count = avctx->thread_count = 1;
308 if (thread_count <= 1) {
309 avctx->active_thread_type = 0;
313 c = av_mallocz(sizeof(ThreadContext));
317 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
323 avctx->thread_opaque = c;
328 pthread_cond_init(&c->current_job_cond, NULL);
329 pthread_cond_init(&c->last_job_cond, NULL);
330 pthread_mutex_init(&c->current_job_lock, NULL);
331 pthread_mutex_lock(&c->current_job_lock);
332 for (i=0; i<thread_count; i++) {
333 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
334 avctx->thread_count = i;
335 pthread_mutex_unlock(&c->current_job_lock);
336 ff_thread_free(avctx);
341 avcodec_thread_park_workers(c, thread_count);
343 avctx->execute = avcodec_thread_execute;
344 avctx->execute2 = avcodec_thread_execute2;
349 * Codec worker thread.
351 * Automatically calls ff_thread_finish_setup() if the codec does
352 * not provide an update_thread_context method, or if the codec returns
355 static attribute_align_arg void *frame_worker_thread(void *arg)
357 PerThreadContext *p = arg;
358 FrameThreadContext *fctx = p->parent;
359 AVCodecContext *avctx = p->avctx;
360 const AVCodec *codec = avctx->codec;
363 if (p->state == STATE_INPUT_READY && !fctx->die) {
364 pthread_mutex_lock(&p->mutex);
365 while (p->state == STATE_INPUT_READY && !fctx->die)
366 pthread_cond_wait(&p->input_cond, &p->mutex);
367 pthread_mutex_unlock(&p->mutex);
370 if (fctx->die) break;
372 if (!codec->update_thread_context && avctx->thread_safe_callbacks)
373 ff_thread_finish_setup(avctx);
375 pthread_mutex_lock(&p->mutex);
376 avcodec_get_frame_defaults(&p->frame);
378 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
380 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
382 p->state = STATE_INPUT_READY;
384 pthread_mutex_lock(&p->progress_mutex);
385 pthread_cond_signal(&p->output_cond);
386 pthread_mutex_unlock(&p->progress_mutex);
388 pthread_mutex_unlock(&p->mutex);
395 * Update the next thread's AVCodecContext with values from the reference thread's context.
397 * @param dst The destination context.
398 * @param src The source context.
399 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
401 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
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;
417 dst->bits_per_coded_sample = src->bits_per_coded_sample;
418 dst->sample_aspect_ratio = src->sample_aspect_ratio;
419 dst->dtg_active_format = src->dtg_active_format;
421 dst->profile = src->profile;
422 dst->level = src->level;
424 dst->bits_per_raw_sample = src->bits_per_raw_sample;
425 dst->ticks_per_frame = src->ticks_per_frame;
426 dst->color_primaries = src->color_primaries;
428 dst->color_trc = src->color_trc;
429 dst->colorspace = src->colorspace;
430 dst->color_range = src->color_range;
431 dst->chroma_sample_location = src->chroma_sample_location;
435 dst->coded_frame = src->coded_frame;
437 if (dst->codec->update_thread_context)
438 err = dst->codec->update_thread_context(dst, src);
445 * Update the next thread's AVCodecContext with values set by the user.
447 * @param dst The destination context.
448 * @param src The source context.
449 * @return 0 on success, negative error code on failure
451 static int 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->debug = src->debug;
462 dst->debug_mv = src->debug_mv;
464 dst->slice_flags = src->slice_flags;
465 dst->flags2 = src->flags2;
467 copy_fields(skip_loop_filter, subtitle_header);
469 dst->frame_number = src->frame_number;
470 dst->reordered_opaque = src->reordered_opaque;
472 if (src->slice_count && src->slice_offset) {
473 if (dst->slice_count < src->slice_count) {
474 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
475 sizeof(*dst->slice_offset));
477 av_free(dst->slice_offset);
478 return AVERROR(ENOMEM);
480 dst->slice_offset = tmp;
482 memcpy(dst->slice_offset, src->slice_offset,
483 src->slice_count * sizeof(*dst->slice_offset));
485 dst->slice_count = src->slice_count;
490 static void free_progress(AVFrame *f)
492 PerThreadContext *p = f->owner->thread_opaque;
493 int *progress = f->thread_opaque;
495 p->progress_used[(progress - p->progress[0]) / 2] = 0;
498 /// Releases the buffers that this decoding thread was the last user of.
499 static void release_delayed_buffers(PerThreadContext *p)
501 FrameThreadContext *fctx = p->parent;
503 while (p->num_released_buffers > 0) {
506 pthread_mutex_lock(&fctx->buffer_mutex);
507 f = &p->released_buffers[--p->num_released_buffers];
509 f->thread_opaque = NULL;
511 f->owner->release_buffer(f->owner, f);
512 pthread_mutex_unlock(&fctx->buffer_mutex);
516 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
518 FrameThreadContext *fctx = p->parent;
519 PerThreadContext *prev_thread = fctx->prev_thread;
520 const AVCodec *codec = p->avctx->codec;
521 uint8_t *buf = p->avpkt.data;
523 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
525 pthread_mutex_lock(&p->mutex);
527 release_delayed_buffers(p);
531 if (prev_thread->state == STATE_SETTING_UP) {
532 pthread_mutex_lock(&prev_thread->progress_mutex);
533 while (prev_thread->state == STATE_SETTING_UP)
534 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
535 pthread_mutex_unlock(&prev_thread->progress_mutex);
538 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
540 pthread_mutex_unlock(&p->mutex);
545 av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
548 memcpy(buf, avpkt->data, avpkt->size);
549 memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
551 p->state = STATE_SETTING_UP;
552 pthread_cond_signal(&p->input_cond);
553 pthread_mutex_unlock(&p->mutex);
556 * If the client doesn't have a thread-safe get_buffer(),
557 * then decoding threads call back to the main thread,
558 * and it calls back to the client here.
561 if (!p->avctx->thread_safe_callbacks &&
562 p->avctx->get_buffer != avcodec_default_get_buffer) {
563 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
564 pthread_mutex_lock(&p->progress_mutex);
565 while (p->state == STATE_SETTING_UP)
566 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
568 if (p->state == STATE_GET_BUFFER) {
569 p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
570 p->state = STATE_SETTING_UP;
571 pthread_cond_signal(&p->progress_cond);
573 pthread_mutex_unlock(&p->progress_mutex);
577 fctx->prev_thread = p;
578 fctx->next_decoding++;
583 int ff_thread_decode_frame(AVCodecContext *avctx,
584 AVFrame *picture, int *got_picture_ptr,
587 FrameThreadContext *fctx = avctx->thread_opaque;
588 int finished = fctx->next_finished;
593 * Submit a packet to the next decoding thread.
596 p = &fctx->threads[fctx->next_decoding];
597 err = update_context_from_user(p->avctx, avctx);
599 err = submit_packet(p, avpkt);
603 * If we're still receiving the initial packets, don't return a frame.
606 if (fctx->delaying) {
607 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
615 * Return the next available frame from the oldest thread.
616 * If we're at the end of the stream, then we have to skip threads that
617 * didn't output a frame, because we don't want to accidentally signal
618 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
622 p = &fctx->threads[finished++];
624 if (p->state != STATE_INPUT_READY) {
625 pthread_mutex_lock(&p->progress_mutex);
626 while (p->state != STATE_INPUT_READY)
627 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
628 pthread_mutex_unlock(&p->progress_mutex);
632 *got_picture_ptr = p->got_frame;
633 picture->pkt_dts = p->avpkt.dts;
636 * A later call with avkpt->size == 0 may loop over all threads,
637 * including this one, searching for a frame to return before being
638 * stopped by the "finished != fctx->next_finished" condition.
639 * Make sure we don't mistakenly return the same frame again.
643 if (finished >= avctx->thread_count) finished = 0;
644 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
646 update_context_from_thread(avctx, p->avctx, 1);
648 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
650 fctx->next_finished = finished;
652 /* return the size of the consumed packet if no error occurred */
653 return (p->result >= 0) ? avpkt->size : p->result;
656 void ff_thread_report_progress(AVFrame *f, int n, int field)
659 int *progress = f->thread_opaque;
661 if (!progress || progress[field] >= n) return;
663 p = f->owner->thread_opaque;
665 if (f->owner->debug&FF_DEBUG_THREADS)
666 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
668 pthread_mutex_lock(&p->progress_mutex);
670 pthread_cond_broadcast(&p->progress_cond);
671 pthread_mutex_unlock(&p->progress_mutex);
674 void ff_thread_await_progress(AVFrame *f, int n, int field)
677 int *progress = f->thread_opaque;
679 if (!progress || progress[field] >= n) return;
681 p = f->owner->thread_opaque;
683 if (f->owner->debug&FF_DEBUG_THREADS)
684 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
686 pthread_mutex_lock(&p->progress_mutex);
687 while (progress[field] < n)
688 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
689 pthread_mutex_unlock(&p->progress_mutex);
692 void ff_thread_finish_setup(AVCodecContext *avctx) {
693 PerThreadContext *p = avctx->thread_opaque;
695 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
697 pthread_mutex_lock(&p->progress_mutex);
698 p->state = STATE_SETUP_FINISHED;
699 pthread_cond_broadcast(&p->progress_cond);
700 pthread_mutex_unlock(&p->progress_mutex);
703 /// Waits for all threads to finish.
704 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
708 for (i = 0; i < thread_count; i++) {
709 PerThreadContext *p = &fctx->threads[i];
711 if (p->state != STATE_INPUT_READY) {
712 pthread_mutex_lock(&p->progress_mutex);
713 while (p->state != STATE_INPUT_READY)
714 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
715 pthread_mutex_unlock(&p->progress_mutex);
720 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
722 FrameThreadContext *fctx = avctx->thread_opaque;
723 const AVCodec *codec = avctx->codec;
726 park_frame_worker_threads(fctx, thread_count);
728 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
729 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
733 for (i = 0; i < thread_count; i++) {
734 PerThreadContext *p = &fctx->threads[i];
736 pthread_mutex_lock(&p->mutex);
737 pthread_cond_signal(&p->input_cond);
738 pthread_mutex_unlock(&p->mutex);
741 pthread_join(p->thread, NULL);
744 codec->close(p->avctx);
748 release_delayed_buffers(p);
751 for (i = 0; i < thread_count; i++) {
752 PerThreadContext *p = &fctx->threads[i];
754 avcodec_default_free_buffers(p->avctx);
756 pthread_mutex_destroy(&p->mutex);
757 pthread_mutex_destroy(&p->progress_mutex);
758 pthread_cond_destroy(&p->input_cond);
759 pthread_cond_destroy(&p->progress_cond);
760 pthread_cond_destroy(&p->output_cond);
761 av_freep(&p->avpkt.data);
764 av_freep(&p->avctx->priv_data);
765 av_freep(&p->avctx->internal);
766 av_freep(&p->avctx->slice_offset);
772 av_freep(&fctx->threads);
773 pthread_mutex_destroy(&fctx->buffer_mutex);
774 av_freep(&avctx->thread_opaque);
777 static int frame_thread_init(AVCodecContext *avctx)
779 int thread_count = avctx->thread_count;
780 const AVCodec *codec = avctx->codec;
781 AVCodecContext *src = avctx;
782 FrameThreadContext *fctx;
786 int nb_cpus = get_logical_cpus(avctx);
787 // use number of cores + 1 as thread count if there is more than one
789 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
791 thread_count = avctx->thread_count = 1;
794 if (thread_count <= 1) {
795 avctx->active_thread_type = 0;
799 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
801 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
802 pthread_mutex_init(&fctx->buffer_mutex, NULL);
805 for (i = 0; i < thread_count; i++) {
806 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
807 PerThreadContext *p = &fctx->threads[i];
809 pthread_mutex_init(&p->mutex, NULL);
810 pthread_mutex_init(&p->progress_mutex, NULL);
811 pthread_cond_init(&p->input_cond, NULL);
812 pthread_cond_init(&p->progress_cond, NULL);
813 pthread_cond_init(&p->output_cond, NULL);
819 err = AVERROR(ENOMEM);
824 copy->thread_opaque = p;
825 copy->pkt = &p->avpkt;
831 err = codec->init(copy);
833 update_context_from_thread(avctx, copy, 1);
835 copy->priv_data = av_malloc(codec->priv_data_size);
836 if (!copy->priv_data) {
837 err = AVERROR(ENOMEM);
840 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
841 copy->internal = av_malloc(sizeof(AVCodecInternal));
842 if (!copy->internal) {
843 err = AVERROR(ENOMEM);
846 *copy->internal = *src->internal;
847 copy->internal->is_copy = 1;
849 if (codec->init_thread_copy)
850 err = codec->init_thread_copy(copy);
855 if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
862 frame_thread_free(avctx, i+1);
867 void ff_thread_flush(AVCodecContext *avctx)
870 FrameThreadContext *fctx = avctx->thread_opaque;
872 if (!avctx->thread_opaque) return;
874 park_frame_worker_threads(fctx, avctx->thread_count);
875 if (fctx->prev_thread) {
876 if (fctx->prev_thread != &fctx->threads[0])
877 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
878 if (avctx->codec->flush)
879 avctx->codec->flush(fctx->threads[0].avctx);
882 fctx->next_decoding = fctx->next_finished = 0;
884 fctx->prev_thread = NULL;
885 for (i = 0; i < avctx->thread_count; i++) {
886 PerThreadContext *p = &fctx->threads[i];
887 // Make sure decode flush calls with size=0 won't return old frames
890 release_delayed_buffers(p);
894 static int *allocate_progress(PerThreadContext *p)
898 for (i = 0; i < MAX_BUFFERS; i++)
899 if (!p->progress_used[i]) break;
901 if (i == MAX_BUFFERS) {
902 av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
906 p->progress_used[i] = 1;
908 return p->progress[i];
911 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
913 PerThreadContext *p = avctx->thread_opaque;
918 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
919 f->thread_opaque = NULL;
920 return avctx->get_buffer(avctx, f);
923 if (p->state != STATE_SETTING_UP &&
924 (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
925 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
929 pthread_mutex_lock(&p->parent->buffer_mutex);
930 f->thread_opaque = progress = allocate_progress(p);
933 pthread_mutex_unlock(&p->parent->buffer_mutex);
940 if (avctx->thread_safe_callbacks ||
941 avctx->get_buffer == avcodec_default_get_buffer) {
942 err = avctx->get_buffer(avctx, f);
944 p->requested_frame = f;
945 p->state = STATE_GET_BUFFER;
946 pthread_mutex_lock(&p->progress_mutex);
947 pthread_cond_signal(&p->progress_cond);
949 while (p->state != STATE_SETTING_UP)
950 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
954 pthread_mutex_unlock(&p->progress_mutex);
956 if (!avctx->codec->update_thread_context)
957 ff_thread_finish_setup(avctx);
962 f->thread_opaque = NULL;
964 pthread_mutex_unlock(&p->parent->buffer_mutex);
969 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
971 PerThreadContext *p = avctx->thread_opaque;
972 FrameThreadContext *fctx;
974 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
975 avctx->release_buffer(avctx, f);
979 if (p->num_released_buffers >= MAX_BUFFERS) {
980 av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
984 if(avctx->debug & FF_DEBUG_BUFFERS)
985 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
988 pthread_mutex_lock(&fctx->buffer_mutex);
989 p->released_buffers[p->num_released_buffers++] = *f;
990 pthread_mutex_unlock(&fctx->buffer_mutex);
991 memset(f->data, 0, sizeof(f->data));
995 * Set the threading algorithms used.
997 * Threading requires more than one thread.
998 * Frame threading requires entire frames to be passed to the codec,
999 * and introduces extra decoding delay, so is incompatible with low_delay.
1001 * @param avctx The context.
1003 static void validate_thread_parameters(AVCodecContext *avctx)
1005 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1006 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1007 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1008 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1009 if (avctx->thread_count == 1) {
1010 avctx->active_thread_type = 0;
1011 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1012 avctx->active_thread_type = FF_THREAD_FRAME;
1013 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1014 avctx->thread_type & FF_THREAD_SLICE) {
1015 avctx->active_thread_type = FF_THREAD_SLICE;
1016 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1017 avctx->thread_count = 1;
1018 avctx->active_thread_type = 0;
1021 if (avctx->thread_count > MAX_AUTO_THREADS)
1022 av_log(avctx, AV_LOG_WARNING,
1023 "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1024 avctx->thread_count, MAX_AUTO_THREADS);
1027 int ff_thread_init(AVCodecContext *avctx)
1029 if (avctx->thread_opaque) {
1030 av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
1039 validate_thread_parameters(avctx);
1041 if (avctx->active_thread_type&FF_THREAD_SLICE)
1042 return thread_init(avctx);
1043 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1044 return frame_thread_init(avctx);
1050 void ff_thread_free(AVCodecContext *avctx)
1052 if (avctx->active_thread_type&FF_THREAD_FRAME)
1053 frame_thread_free(avctx, avctx->thread_count);