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/avassert.h"
56 #include "libavutil/common.h"
61 #include "w32pthreads.h"
64 typedef int (action_func)(AVCodecContext *c, void *arg);
65 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
67 typedef struct ThreadContext {
77 pthread_cond_t last_job_cond;
78 pthread_cond_t current_job_cond;
79 pthread_mutex_t current_job_lock;
85 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
87 typedef struct PerThreadContext {
88 struct FrameThreadContext *parent;
92 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
93 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
94 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
96 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
97 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
99 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
101 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
102 uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
103 int allocated_buf_size; ///< Size allocated for buf
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;
124 int num_released_buffers;
125 int released_buffers_allocated;
127 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
128 int requested_flags; ///< flags passed to get_buffer() for requested_frame
132 * Context stored in the client AVCodecContext thread_opaque.
134 typedef struct FrameThreadContext {
135 PerThreadContext *threads; ///< The contexts for each thread.
136 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
138 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
140 int next_decoding; ///< The next context to submit a packet to.
141 int next_finished; ///< The next context to return output from.
144 * Set for the first N packets, where N is the number of threads.
145 * While it is set, ff_thread_en/decode_frame won't return any results.
148 int die; ///< Set when threads should exit.
149 } FrameThreadContext;
152 /* H264 slice threading seems to be buggy with more than 16 threads,
153 * limit the number of threads to 16 for automatic detection */
154 #define MAX_AUTO_THREADS 16
156 static int get_logical_cpus(AVCodecContext *avctx)
158 int ret, nb_cpus = 1;
159 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
164 ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
166 nb_cpus = CPU_COUNT(&cpuset);
168 #elif HAVE_GETPROCESSAFFINITYMASK
169 DWORD_PTR proc_aff, sys_aff;
170 ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
172 nb_cpus = av_popcount64(proc_aff);
173 #elif HAVE_SYSCTL && defined(HW_NCPU)
174 int mib[2] = { CTL_HW, HW_NCPU };
175 size_t len = sizeof(nb_cpus);
177 ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
180 #elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
181 nb_cpus = sysconf(_SC_NPROC_ONLN);
182 #elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
183 nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
185 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
190 static void* attribute_align_arg worker(void *v)
192 AVCodecContext *avctx = v;
193 ThreadContext *c = avctx->thread_opaque;
194 int our_job = c->job_count;
195 int thread_count = avctx->thread_count;
198 pthread_mutex_lock(&c->current_job_lock);
199 self_id = c->current_job++;
201 while (our_job >= c->job_count) {
202 if (c->current_job == thread_count + c->job_count)
203 pthread_cond_signal(&c->last_job_cond);
205 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
209 pthread_mutex_unlock(&c->current_job_lock);
213 pthread_mutex_unlock(&c->current_job_lock);
215 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
216 c->func2(avctx, c->args, our_job, self_id);
218 pthread_mutex_lock(&c->current_job_lock);
219 our_job = c->current_job++;
223 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
225 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
226 pthread_mutex_unlock(&c->current_job_lock);
229 static void thread_free(AVCodecContext *avctx)
231 ThreadContext *c = avctx->thread_opaque;
234 pthread_mutex_lock(&c->current_job_lock);
236 pthread_cond_broadcast(&c->current_job_cond);
237 pthread_mutex_unlock(&c->current_job_lock);
239 for (i=0; i<avctx->thread_count; i++)
240 pthread_join(c->workers[i], NULL);
242 pthread_mutex_destroy(&c->current_job_lock);
243 pthread_cond_destroy(&c->current_job_cond);
244 pthread_cond_destroy(&c->last_job_cond);
246 av_freep(&avctx->thread_opaque);
249 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
251 ThreadContext *c= avctx->thread_opaque;
254 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
255 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
260 pthread_mutex_lock(&c->current_job_lock);
262 c->current_job = avctx->thread_count;
263 c->job_count = job_count;
264 c->job_size = job_size;
269 c->rets_count = job_count;
271 c->rets = &dummy_ret;
274 pthread_cond_broadcast(&c->current_job_cond);
276 avcodec_thread_park_workers(c, avctx->thread_count);
281 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
283 ThreadContext *c= avctx->thread_opaque;
285 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
288 static int thread_init(AVCodecContext *avctx)
292 int thread_count = avctx->thread_count;
295 int nb_cpus = get_logical_cpus(avctx);
296 // use number of cores + 1 as thread count if there is more than one
298 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
300 thread_count = avctx->thread_count = 1;
303 if (thread_count <= 1) {
304 avctx->active_thread_type = 0;
308 c = av_mallocz(sizeof(ThreadContext));
312 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
318 avctx->thread_opaque = c;
323 pthread_cond_init(&c->current_job_cond, NULL);
324 pthread_cond_init(&c->last_job_cond, NULL);
325 pthread_mutex_init(&c->current_job_lock, NULL);
326 pthread_mutex_lock(&c->current_job_lock);
327 for (i=0; i<thread_count; i++) {
328 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
329 avctx->thread_count = i;
330 pthread_mutex_unlock(&c->current_job_lock);
331 ff_thread_free(avctx);
336 avcodec_thread_park_workers(c, thread_count);
338 avctx->execute = avcodec_thread_execute;
339 avctx->execute2 = avcodec_thread_execute2;
344 * Codec worker thread.
346 * Automatically calls ff_thread_finish_setup() if the codec does
347 * not provide an update_thread_context method, or if the codec returns
350 static attribute_align_arg void *frame_worker_thread(void *arg)
352 PerThreadContext *p = arg;
353 FrameThreadContext *fctx = p->parent;
354 AVCodecContext *avctx = p->avctx;
355 const AVCodec *codec = avctx->codec;
358 if (p->state == STATE_INPUT_READY && !fctx->die) {
359 pthread_mutex_lock(&p->mutex);
360 while (p->state == STATE_INPUT_READY && !fctx->die)
361 pthread_cond_wait(&p->input_cond, &p->mutex);
362 pthread_mutex_unlock(&p->mutex);
365 if (fctx->die) break;
367 if (!codec->update_thread_context && avctx->thread_safe_callbacks)
368 ff_thread_finish_setup(avctx);
370 pthread_mutex_lock(&p->mutex);
371 avcodec_get_frame_defaults(&p->frame);
373 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
375 /* many decoders assign whole AVFrames, thus overwriting extended_data;
376 * make sure it's set correctly */
377 p->frame.extended_data = p->frame.data;
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->time_base = src->time_base;
406 dst->width = src->width;
407 dst->height = src->height;
408 dst->pix_fmt = src->pix_fmt;
410 dst->coded_width = src->coded_width;
411 dst->coded_height = src->coded_height;
413 dst->has_b_frames = src->has_b_frames;
414 dst->idct_algo = src->idct_algo;
416 dst->bits_per_coded_sample = src->bits_per_coded_sample;
417 dst->sample_aspect_ratio = src->sample_aspect_ratio;
418 dst->dtg_active_format = src->dtg_active_format;
420 dst->profile = src->profile;
421 dst->level = src->level;
423 dst->bits_per_raw_sample = src->bits_per_raw_sample;
424 dst->ticks_per_frame = src->ticks_per_frame;
425 dst->color_primaries = src->color_primaries;
427 dst->color_trc = src->color_trc;
428 dst->colorspace = src->colorspace;
429 dst->color_range = src->color_range;
430 dst->chroma_sample_location = src->chroma_sample_location;
432 dst->hwaccel = src->hwaccel;
433 dst->hwaccel_context = src->hwaccel_context;
437 dst->coded_frame = src->coded_frame;
439 if (dst->codec->update_thread_context)
440 err = dst->codec->update_thread_context(dst, src);
447 * Update the next thread's AVCodecContext with values set by the user.
449 * @param dst The destination context.
450 * @param src The source context.
451 * @return 0 on success, negative error code on failure
453 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
455 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
456 dst->flags = src->flags;
458 dst->draw_horiz_band= src->draw_horiz_band;
459 dst->get_buffer2 = src->get_buffer2;
460 #if FF_API_GET_BUFFER
461 dst->get_buffer = src->get_buffer;
462 dst->release_buffer = src->release_buffer;
465 dst->opaque = src->opaque;
466 dst->debug = src->debug;
467 dst->debug_mv = src->debug_mv;
469 dst->slice_flags = src->slice_flags;
470 dst->flags2 = src->flags2;
472 copy_fields(skip_loop_filter, subtitle_header);
474 dst->frame_number = src->frame_number;
475 dst->reordered_opaque = src->reordered_opaque;
477 if (src->slice_count && src->slice_offset) {
478 if (dst->slice_count < src->slice_count) {
479 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
480 sizeof(*dst->slice_offset));
482 av_free(dst->slice_offset);
483 return AVERROR(ENOMEM);
485 dst->slice_offset = tmp;
487 memcpy(dst->slice_offset, src->slice_offset,
488 src->slice_count * sizeof(*dst->slice_offset));
490 dst->slice_count = src->slice_count;
495 /// Releases the buffers that this decoding thread was the last user of.
496 static void release_delayed_buffers(PerThreadContext *p)
498 FrameThreadContext *fctx = p->parent;
500 while (p->num_released_buffers > 0) {
503 pthread_mutex_lock(&fctx->buffer_mutex);
505 // fix extended data in case the caller screwed it up
506 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
507 f = &p->released_buffers[--p->num_released_buffers];
508 f->extended_data = f->data;
511 pthread_mutex_unlock(&fctx->buffer_mutex);
515 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
517 FrameThreadContext *fctx = p->parent;
518 PerThreadContext *prev_thread = fctx->prev_thread;
519 const AVCodec *codec = p->avctx->codec;
521 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
523 pthread_mutex_lock(&p->mutex);
525 release_delayed_buffers(p);
529 if (prev_thread->state == STATE_SETTING_UP) {
530 pthread_mutex_lock(&prev_thread->progress_mutex);
531 while (prev_thread->state == STATE_SETTING_UP)
532 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
533 pthread_mutex_unlock(&prev_thread->progress_mutex);
536 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
538 pthread_mutex_unlock(&p->mutex);
543 av_buffer_unref(&p->avpkt.buf);
546 p->avpkt.buf = av_buffer_ref(avpkt->buf);
548 av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
549 p->avpkt.data = p->buf;
550 memcpy(p->buf, avpkt->data, avpkt->size);
551 memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
554 p->state = STATE_SETTING_UP;
555 pthread_cond_signal(&p->input_cond);
556 pthread_mutex_unlock(&p->mutex);
559 * If the client doesn't have a thread-safe get_buffer(),
560 * then decoding threads call back to the main thread,
561 * and it calls back to the client here.
564 if (!p->avctx->thread_safe_callbacks && (
565 #if FF_API_GET_BUFFER
566 p->avctx->get_buffer ||
568 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
569 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
570 pthread_mutex_lock(&p->progress_mutex);
571 while (p->state == STATE_SETTING_UP)
572 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
574 if (p->state == STATE_GET_BUFFER) {
575 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
576 p->state = STATE_SETTING_UP;
577 pthread_cond_signal(&p->progress_cond);
579 pthread_mutex_unlock(&p->progress_mutex);
583 fctx->prev_thread = p;
584 fctx->next_decoding++;
589 int ff_thread_decode_frame(AVCodecContext *avctx,
590 AVFrame *picture, int *got_picture_ptr,
593 FrameThreadContext *fctx = avctx->thread_opaque;
594 int finished = fctx->next_finished;
599 * Submit a packet to the next decoding thread.
602 p = &fctx->threads[fctx->next_decoding];
603 err = update_context_from_user(p->avctx, avctx);
605 err = submit_packet(p, avpkt);
609 * If we're still receiving the initial packets, don't return a frame.
612 if (fctx->delaying) {
613 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
621 * Return the next available frame from the oldest thread.
622 * If we're at the end of the stream, then we have to skip threads that
623 * didn't output a frame, because we don't want to accidentally signal
624 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
628 p = &fctx->threads[finished++];
630 if (p->state != STATE_INPUT_READY) {
631 pthread_mutex_lock(&p->progress_mutex);
632 while (p->state != STATE_INPUT_READY)
633 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
634 pthread_mutex_unlock(&p->progress_mutex);
637 av_frame_move_ref(picture, &p->frame);
638 *got_picture_ptr = p->got_frame;
639 picture->pkt_dts = p->avpkt.dts;
642 * A later call with avkpt->size == 0 may loop over all threads,
643 * including this one, searching for a frame to return before being
644 * stopped by the "finished != fctx->next_finished" condition.
645 * Make sure we don't mistakenly return the same frame again.
649 if (finished >= avctx->thread_count) finished = 0;
650 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
652 update_context_from_thread(avctx, p->avctx, 1);
654 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
656 fctx->next_finished = finished;
658 /* return the size of the consumed packet if no error occurred */
659 return (p->result >= 0) ? avpkt->size : p->result;
662 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
665 int *progress = f->progress ? (int*)f->progress->data : NULL;
667 if (!progress || progress[field] >= n) return;
669 p = f->owner->thread_opaque;
671 if (f->owner->debug&FF_DEBUG_THREADS)
672 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
674 pthread_mutex_lock(&p->progress_mutex);
676 pthread_cond_broadcast(&p->progress_cond);
677 pthread_mutex_unlock(&p->progress_mutex);
680 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
683 int *progress = f->progress ? (int*)f->progress->data : NULL;
685 if (!progress || progress[field] >= n) return;
687 p = f->owner->thread_opaque;
689 if (f->owner->debug&FF_DEBUG_THREADS)
690 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
692 pthread_mutex_lock(&p->progress_mutex);
693 while (progress[field] < n)
694 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
695 pthread_mutex_unlock(&p->progress_mutex);
698 void ff_thread_finish_setup(AVCodecContext *avctx) {
699 PerThreadContext *p = avctx->thread_opaque;
701 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
703 pthread_mutex_lock(&p->progress_mutex);
704 p->state = STATE_SETUP_FINISHED;
705 pthread_cond_broadcast(&p->progress_cond);
706 pthread_mutex_unlock(&p->progress_mutex);
709 /// Waits for all threads to finish.
710 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
714 for (i = 0; i < thread_count; i++) {
715 PerThreadContext *p = &fctx->threads[i];
717 if (p->state != STATE_INPUT_READY) {
718 pthread_mutex_lock(&p->progress_mutex);
719 while (p->state != STATE_INPUT_READY)
720 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
721 pthread_mutex_unlock(&p->progress_mutex);
726 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
728 FrameThreadContext *fctx = avctx->thread_opaque;
729 const AVCodec *codec = avctx->codec;
732 park_frame_worker_threads(fctx, thread_count);
734 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
735 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
739 for (i = 0; i < thread_count; i++) {
740 PerThreadContext *p = &fctx->threads[i];
742 pthread_mutex_lock(&p->mutex);
743 pthread_cond_signal(&p->input_cond);
744 pthread_mutex_unlock(&p->mutex);
747 pthread_join(p->thread, NULL);
750 codec->close(p->avctx);
754 release_delayed_buffers(p);
755 av_frame_unref(&p->frame);
758 for (i = 0; i < thread_count; i++) {
759 PerThreadContext *p = &fctx->threads[i];
761 pthread_mutex_destroy(&p->mutex);
762 pthread_mutex_destroy(&p->progress_mutex);
763 pthread_cond_destroy(&p->input_cond);
764 pthread_cond_destroy(&p->progress_cond);
765 pthread_cond_destroy(&p->output_cond);
766 av_buffer_unref(&p->avpkt.buf);
768 av_freep(&p->released_buffers);
771 av_freep(&p->avctx->priv_data);
772 av_freep(&p->avctx->internal);
773 av_freep(&p->avctx->slice_offset);
779 av_freep(&fctx->threads);
780 pthread_mutex_destroy(&fctx->buffer_mutex);
781 av_freep(&avctx->thread_opaque);
784 static int frame_thread_init(AVCodecContext *avctx)
786 int thread_count = avctx->thread_count;
787 const AVCodec *codec = avctx->codec;
788 AVCodecContext *src = avctx;
789 FrameThreadContext *fctx;
793 int nb_cpus = get_logical_cpus(avctx);
794 // use number of cores + 1 as thread count if there is more than one
796 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
798 thread_count = avctx->thread_count = 1;
801 if (thread_count <= 1) {
802 avctx->active_thread_type = 0;
806 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
808 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
809 pthread_mutex_init(&fctx->buffer_mutex, NULL);
812 for (i = 0; i < thread_count; i++) {
813 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
814 PerThreadContext *p = &fctx->threads[i];
816 pthread_mutex_init(&p->mutex, NULL);
817 pthread_mutex_init(&p->progress_mutex, NULL);
818 pthread_cond_init(&p->input_cond, NULL);
819 pthread_cond_init(&p->progress_cond, NULL);
820 pthread_cond_init(&p->output_cond, NULL);
826 err = AVERROR(ENOMEM);
831 copy->thread_opaque = p;
832 copy->pkt = &p->avpkt;
838 err = codec->init(copy);
840 update_context_from_thread(avctx, copy, 1);
842 copy->priv_data = av_malloc(codec->priv_data_size);
843 if (!copy->priv_data) {
844 err = AVERROR(ENOMEM);
847 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
848 copy->internal = av_malloc(sizeof(AVCodecInternal));
849 if (!copy->internal) {
850 err = AVERROR(ENOMEM);
853 *copy->internal = *src->internal;
854 copy->internal->is_copy = 1;
856 if (codec->init_thread_copy)
857 err = codec->init_thread_copy(copy);
862 if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
869 frame_thread_free(avctx, i+1);
874 void ff_thread_flush(AVCodecContext *avctx)
877 FrameThreadContext *fctx = avctx->thread_opaque;
879 if (!avctx->thread_opaque) return;
881 park_frame_worker_threads(fctx, avctx->thread_count);
882 if (fctx->prev_thread) {
883 if (fctx->prev_thread != &fctx->threads[0])
884 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
885 if (avctx->codec->flush)
886 avctx->codec->flush(fctx->threads[0].avctx);
889 fctx->next_decoding = fctx->next_finished = 0;
891 fctx->prev_thread = NULL;
892 for (i = 0; i < avctx->thread_count; i++) {
893 PerThreadContext *p = &fctx->threads[i];
894 // Make sure decode flush calls with size=0 won't return old frames
896 av_frame_unref(&p->frame);
898 release_delayed_buffers(p);
902 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
904 PerThreadContext *p = avctx->thread_opaque;
909 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
910 return ff_get_buffer(avctx, f->f, flags);
912 if (p->state != STATE_SETTING_UP &&
913 (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
914 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
918 if (avctx->internal->allocate_progress) {
920 f->progress = av_buffer_alloc(2 * sizeof(int));
922 return AVERROR(ENOMEM);
924 progress = (int*)f->progress->data;
926 progress[0] = progress[1] = -1;
929 pthread_mutex_lock(&p->parent->buffer_mutex);
930 if (avctx->thread_safe_callbacks || (
931 #if FF_API_GET_BUFFER
932 !avctx->get_buffer &&
934 avctx->get_buffer2 == avcodec_default_get_buffer2)) {
935 err = ff_get_buffer(avctx, f->f, flags);
937 p->requested_frame = f->f;
938 p->requested_flags = flags;
939 p->state = STATE_GET_BUFFER;
940 pthread_mutex_lock(&p->progress_mutex);
941 pthread_cond_signal(&p->progress_cond);
943 while (p->state != STATE_SETTING_UP)
944 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
948 pthread_mutex_unlock(&p->progress_mutex);
951 if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
952 ff_thread_finish_setup(avctx);
955 av_buffer_unref(&f->progress);
957 pthread_mutex_unlock(&p->parent->buffer_mutex);
962 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
964 PerThreadContext *p = avctx->thread_opaque;
965 FrameThreadContext *fctx;
967 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
968 avctx->thread_safe_callbacks ||
970 #if FF_API_GET_BUFFER
971 !avctx->get_buffer &&
973 avctx->get_buffer2 == avcodec_default_get_buffer2);
978 if (avctx->debug & FF_DEBUG_BUFFERS)
979 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
981 av_buffer_unref(&f->progress);
984 if (can_direct_free) {
985 av_frame_unref(f->f);
990 pthread_mutex_lock(&fctx->buffer_mutex);
992 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
994 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
995 (p->num_released_buffers + 1) *
996 sizeof(*p->released_buffers));
999 p->released_buffers = tmp;
1001 dst = &p->released_buffers[p->num_released_buffers];
1002 av_frame_move_ref(dst, f->f);
1004 p->num_released_buffers++;
1007 pthread_mutex_unlock(&fctx->buffer_mutex);
1011 * Set the threading algorithms used.
1013 * Threading requires more than one thread.
1014 * Frame threading requires entire frames to be passed to the codec,
1015 * and introduces extra decoding delay, so is incompatible with low_delay.
1017 * @param avctx The context.
1019 static void validate_thread_parameters(AVCodecContext *avctx)
1021 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1022 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1023 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1024 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1025 if (avctx->thread_count == 1) {
1026 avctx->active_thread_type = 0;
1027 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1028 avctx->active_thread_type = FF_THREAD_FRAME;
1029 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1030 avctx->thread_type & FF_THREAD_SLICE) {
1031 avctx->active_thread_type = FF_THREAD_SLICE;
1032 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1033 avctx->thread_count = 1;
1034 avctx->active_thread_type = 0;
1037 if (avctx->thread_count > MAX_AUTO_THREADS)
1038 av_log(avctx, AV_LOG_WARNING,
1039 "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1040 avctx->thread_count, MAX_AUTO_THREADS);
1043 int ff_thread_init(AVCodecContext *avctx)
1045 if (avctx->thread_opaque) {
1046 av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
1055 validate_thread_parameters(avctx);
1057 if (avctx->active_thread_type&FF_THREAD_SLICE)
1058 return thread_init(avctx);
1059 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1060 return frame_thread_init(avctx);
1066 void ff_thread_free(AVCodecContext *avctx)
1068 if (avctx->active_thread_type&FF_THREAD_FRAME)
1069 frame_thread_free(avctx, avctx->thread_count);