2 * Copyright (c) 2004 Roman Shaposhnik
3 * Copyright (c) 2008 Alexander Strange (astrange@ithinksw.com)
5 * Many thanks to Steven M. Schultz for providing clever ideas and
6 * to Michael Niedermayer <michaelni@gmx.at> for writing initial
9 * This file is part of FFmpeg.
11 * FFmpeg is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * FFmpeg is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with FFmpeg; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 * Multithreading support functions
29 * @see doc/multithreading.txt
34 #if HAVE_SCHED_GETAFFINITY
40 #if HAVE_GETPROCESSAFFINITYMASK
45 #include <sys/param.h>
47 #include <sys/types.h>
48 #include <sys/param.h>
49 #include <sys/sysctl.h>
58 #include "libavutil/avassert.h"
59 #include "libavutil/common.h"
64 #include "w32pthreads.h"
66 #include "os2threads.h"
69 typedef int (action_func)(AVCodecContext *c, void *arg);
70 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
72 typedef struct ThreadContext {
82 pthread_cond_t last_job_cond;
83 pthread_cond_t current_job_cond;
84 pthread_mutex_t current_job_lock;
86 unsigned int current_execute;
91 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
93 typedef struct PerThreadContext {
94 struct FrameThreadContext *parent;
98 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
99 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
100 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
102 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
103 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
105 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
107 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
108 uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
109 int allocated_buf_size; ///< Size allocated for buf
111 AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
112 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
113 int result; ///< The result of the last codec decode/encode() call.
116 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
117 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
118 STATE_GET_BUFFER, /**<
119 * Set when the codec calls get_buffer().
120 * State is returned to STATE_SETTING_UP afterwards.
122 STATE_GET_FORMAT, /**<
123 * Set when the codec calls get_format().
124 * State is returned to STATE_SETTING_UP afterwards.
126 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
130 * Array of frames passed to ff_thread_release_buffer().
131 * Frames are released after all threads referencing them are finished.
133 AVFrame *released_buffers;
134 int num_released_buffers;
135 int released_buffers_allocated;
137 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
138 int requested_flags; ///< flags passed to get_buffer() for requested_frame
140 const enum AVPixelFormat *available_formats; ///< Format array for get_format()
141 enum AVPixelFormat result_format; ///< get_format() result
145 * Context stored in the client AVCodecContext thread_opaque.
147 typedef struct FrameThreadContext {
148 PerThreadContext *threads; ///< The contexts for each thread.
149 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
151 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
153 int next_decoding; ///< The next context to submit a packet to.
154 int next_finished; ///< The next context to return output from.
157 * Set for the first N packets, where N is the number of threads.
158 * While it is set, ff_thread_en/decode_frame won't return any results.
161 int die; ///< Set when threads should exit.
162 } FrameThreadContext;
165 /* H264 slice threading seems to be buggy with more than 16 threads,
166 * limit the number of threads to 16 for automatic detection */
167 #define MAX_AUTO_THREADS 16
169 int ff_get_logical_cpus(AVCodecContext *avctx)
171 int ret, nb_cpus = 1;
172 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
177 ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
179 nb_cpus = CPU_COUNT(&cpuset);
181 #elif HAVE_GETPROCESSAFFINITYMASK
182 DWORD_PTR proc_aff, sys_aff;
183 ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
185 nb_cpus = av_popcount64(proc_aff);
186 #elif HAVE_SYSCTL && defined(HW_NCPU)
187 int mib[2] = { CTL_HW, HW_NCPU };
188 size_t len = sizeof(nb_cpus);
190 ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
193 #elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
194 nb_cpus = sysconf(_SC_NPROC_ONLN);
195 #elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
196 nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
198 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
201 nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
207 static void* attribute_align_arg worker(void *v)
209 AVCodecContext *avctx = v;
210 ThreadContext *c = avctx->thread_opaque;
211 int our_job = c->job_count;
212 int last_execute = 0;
213 int thread_count = avctx->thread_count;
216 pthread_mutex_lock(&c->current_job_lock);
217 self_id = c->current_job++;
219 while (our_job >= c->job_count) {
220 if (c->current_job == thread_count + c->job_count)
221 pthread_cond_signal(&c->last_job_cond);
223 while (last_execute == c->current_execute && !c->done)
224 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
225 last_execute = c->current_execute;
229 pthread_mutex_unlock(&c->current_job_lock);
233 pthread_mutex_unlock(&c->current_job_lock);
235 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
236 c->func2(avctx, c->args, our_job, self_id);
238 pthread_mutex_lock(&c->current_job_lock);
239 our_job = c->current_job++;
243 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
245 while (c->current_job != thread_count + c->job_count)
246 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
247 pthread_mutex_unlock(&c->current_job_lock);
250 static void thread_free(AVCodecContext *avctx)
252 ThreadContext *c = avctx->thread_opaque;
255 pthread_mutex_lock(&c->current_job_lock);
257 pthread_cond_broadcast(&c->current_job_cond);
258 pthread_mutex_unlock(&c->current_job_lock);
260 for (i=0; i<avctx->thread_count; i++)
261 pthread_join(c->workers[i], NULL);
263 pthread_mutex_destroy(&c->current_job_lock);
264 pthread_cond_destroy(&c->current_job_cond);
265 pthread_cond_destroy(&c->last_job_cond);
267 av_freep(&avctx->thread_opaque);
270 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
272 ThreadContext *c= avctx->thread_opaque;
275 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
276 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
281 pthread_mutex_lock(&c->current_job_lock);
283 c->current_job = avctx->thread_count;
284 c->job_count = job_count;
285 c->job_size = job_size;
290 c->rets_count = job_count;
292 c->rets = &dummy_ret;
295 c->current_execute++;
296 pthread_cond_broadcast(&c->current_job_cond);
298 avcodec_thread_park_workers(c, avctx->thread_count);
303 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
305 ThreadContext *c= avctx->thread_opaque;
307 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
310 static int thread_init(AVCodecContext *avctx)
314 int thread_count = avctx->thread_count;
317 int nb_cpus = ff_get_logical_cpus(avctx);
318 // use number of cores + 1 as thread count if there is more than one
320 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
322 thread_count = avctx->thread_count = 1;
325 if (thread_count <= 1) {
326 avctx->active_thread_type = 0;
330 c = av_mallocz(sizeof(ThreadContext));
334 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
340 avctx->thread_opaque = c;
345 pthread_cond_init(&c->current_job_cond, NULL);
346 pthread_cond_init(&c->last_job_cond, NULL);
347 pthread_mutex_init(&c->current_job_lock, NULL);
348 pthread_mutex_lock(&c->current_job_lock);
349 for (i=0; i<thread_count; i++) {
350 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
351 avctx->thread_count = i;
352 pthread_mutex_unlock(&c->current_job_lock);
353 ff_thread_free(avctx);
358 avcodec_thread_park_workers(c, thread_count);
360 avctx->execute = avcodec_thread_execute;
361 avctx->execute2 = avcodec_thread_execute2;
366 * Codec worker thread.
368 * Automatically calls ff_thread_finish_setup() if the codec does
369 * not provide an update_thread_context method, or if the codec returns
372 static attribute_align_arg void *frame_worker_thread(void *arg)
374 PerThreadContext *p = arg;
375 FrameThreadContext *fctx = p->parent;
376 AVCodecContext *avctx = p->avctx;
377 const AVCodec *codec = avctx->codec;
379 pthread_mutex_lock(&p->mutex);
381 while (p->state == STATE_INPUT_READY && !fctx->die)
382 pthread_cond_wait(&p->input_cond, &p->mutex);
384 if (fctx->die) break;
386 if (!codec->update_thread_context && (avctx->thread_safe_callbacks || (
387 #if FF_API_GET_BUFFER
388 !avctx->get_buffer &&
390 avctx->get_buffer2 == avcodec_default_get_buffer2)))
391 ff_thread_finish_setup(avctx);
393 avcodec_get_frame_defaults(&p->frame);
395 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
397 /* many decoders assign whole AVFrames, thus overwriting extended_data;
398 * make sure it's set correctly */
399 p->frame.extended_data = p->frame.data;
401 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
403 pthread_mutex_lock(&p->progress_mutex);
405 for (i = 0; i < MAX_BUFFERS; i++)
406 if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
407 p->progress[i][0] = INT_MAX;
408 p->progress[i][1] = INT_MAX;
411 p->state = STATE_INPUT_READY;
413 pthread_cond_broadcast(&p->progress_cond);
414 pthread_cond_signal(&p->output_cond);
415 pthread_mutex_unlock(&p->progress_mutex);
417 pthread_mutex_unlock(&p->mutex);
423 * Update the next thread's AVCodecContext with values from the reference thread's context.
425 * @param dst The destination context.
426 * @param src The source context.
427 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
429 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
434 dst->time_base = src->time_base;
435 dst->width = src->width;
436 dst->height = src->height;
437 dst->pix_fmt = src->pix_fmt;
439 dst->coded_width = src->coded_width;
440 dst->coded_height = src->coded_height;
442 dst->has_b_frames = src->has_b_frames;
443 dst->idct_algo = src->idct_algo;
445 dst->bits_per_coded_sample = src->bits_per_coded_sample;
446 dst->sample_aspect_ratio = src->sample_aspect_ratio;
447 dst->dtg_active_format = src->dtg_active_format;
449 dst->profile = src->profile;
450 dst->level = src->level;
452 dst->bits_per_raw_sample = src->bits_per_raw_sample;
453 dst->ticks_per_frame = src->ticks_per_frame;
454 dst->color_primaries = src->color_primaries;
456 dst->color_trc = src->color_trc;
457 dst->colorspace = src->colorspace;
458 dst->color_range = src->color_range;
459 dst->chroma_sample_location = src->chroma_sample_location;
461 dst->hwaccel = src->hwaccel;
462 dst->hwaccel_context = src->hwaccel_context;
466 dst->delay = src->thread_count - 1;
467 dst->coded_frame = src->coded_frame;
469 if (dst->codec->update_thread_context)
470 err = dst->codec->update_thread_context(dst, src);
477 * Update the next thread's AVCodecContext with values set by the user.
479 * @param dst The destination context.
480 * @param src The source context.
481 * @return 0 on success, negative error code on failure
483 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
485 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
486 dst->flags = src->flags;
488 dst->draw_horiz_band= src->draw_horiz_band;
489 dst->get_buffer2 = src->get_buffer2;
490 #if FF_API_GET_BUFFER
491 dst->get_buffer = src->get_buffer;
492 dst->release_buffer = src->release_buffer;
495 dst->opaque = src->opaque;
496 dst->debug = src->debug;
497 dst->debug_mv = src->debug_mv;
499 dst->slice_flags = src->slice_flags;
500 dst->flags2 = src->flags2;
502 copy_fields(skip_loop_filter, subtitle_header);
504 dst->frame_number = src->frame_number;
505 dst->reordered_opaque = src->reordered_opaque;
506 dst->thread_safe_callbacks = src->thread_safe_callbacks;
508 if (src->slice_count && src->slice_offset) {
509 if (dst->slice_count < src->slice_count) {
510 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
511 sizeof(*dst->slice_offset));
513 av_free(dst->slice_offset);
514 return AVERROR(ENOMEM);
516 dst->slice_offset = tmp;
518 memcpy(dst->slice_offset, src->slice_offset,
519 src->slice_count * sizeof(*dst->slice_offset));
521 dst->slice_count = src->slice_count;
526 /// Releases the buffers that this decoding thread was the last user of.
527 static void release_delayed_buffers(PerThreadContext *p)
529 FrameThreadContext *fctx = p->parent;
531 while (p->num_released_buffers > 0) {
534 pthread_mutex_lock(&fctx->buffer_mutex);
536 // fix extended data in case the caller screwed it up
537 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
538 f = &p->released_buffers[--p->num_released_buffers];
539 f->extended_data = f->data;
542 pthread_mutex_unlock(&fctx->buffer_mutex);
546 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
548 FrameThreadContext *fctx = p->parent;
549 PerThreadContext *prev_thread = fctx->prev_thread;
550 const AVCodec *codec = p->avctx->codec;
552 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
554 pthread_mutex_lock(&p->mutex);
556 release_delayed_buffers(p);
560 if (prev_thread->state == STATE_SETTING_UP) {
561 pthread_mutex_lock(&prev_thread->progress_mutex);
562 while (prev_thread->state == STATE_SETTING_UP)
563 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
564 pthread_mutex_unlock(&prev_thread->progress_mutex);
567 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
569 pthread_mutex_unlock(&p->mutex);
574 av_buffer_unref(&p->avpkt.buf);
577 p->avpkt.buf = av_buffer_ref(avpkt->buf);
579 av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
580 p->avpkt.data = p->buf;
581 memcpy(p->buf, avpkt->data, avpkt->size);
582 memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
585 p->state = STATE_SETTING_UP;
586 pthread_cond_signal(&p->input_cond);
587 pthread_mutex_unlock(&p->mutex);
590 * If the client doesn't have a thread-safe get_buffer(),
591 * then decoding threads call back to the main thread,
592 * and it calls back to the client here.
595 if (!p->avctx->thread_safe_callbacks && (
596 p->avctx->get_format != avcodec_default_get_format ||
597 #if FF_API_GET_BUFFER
598 p->avctx->get_buffer ||
600 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
601 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
603 pthread_mutex_lock(&p->progress_mutex);
604 while (p->state == STATE_SETTING_UP)
605 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
608 case STATE_GET_BUFFER:
609 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
611 case STATE_GET_FORMAT:
612 p->result_format = p->avctx->get_format(p->avctx, p->available_formats);
619 p->state = STATE_SETTING_UP;
620 pthread_cond_signal(&p->progress_cond);
622 pthread_mutex_unlock(&p->progress_mutex);
626 fctx->prev_thread = p;
627 fctx->next_decoding++;
632 int ff_thread_decode_frame(AVCodecContext *avctx,
633 AVFrame *picture, int *got_picture_ptr,
636 FrameThreadContext *fctx = avctx->thread_opaque;
637 int finished = fctx->next_finished;
642 * Submit a packet to the next decoding thread.
645 p = &fctx->threads[fctx->next_decoding];
646 err = update_context_from_user(p->avctx, avctx);
648 err = submit_packet(p, avpkt);
652 * If we're still receiving the initial packets, don't return a frame.
655 if (fctx->delaying) {
656 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
664 * Return the next available frame from the oldest thread.
665 * If we're at the end of the stream, then we have to skip threads that
666 * didn't output a frame, because we don't want to accidentally signal
667 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
671 p = &fctx->threads[finished++];
673 if (p->state != STATE_INPUT_READY) {
674 pthread_mutex_lock(&p->progress_mutex);
675 while (p->state != STATE_INPUT_READY)
676 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
677 pthread_mutex_unlock(&p->progress_mutex);
680 av_frame_move_ref(picture, &p->frame);
681 *got_picture_ptr = p->got_frame;
682 picture->pkt_dts = p->avpkt.dts;
685 * A later call with avkpt->size == 0 may loop over all threads,
686 * including this one, searching for a frame to return before being
687 * stopped by the "finished != fctx->next_finished" condition.
688 * Make sure we don't mistakenly return the same frame again.
692 if (finished >= avctx->thread_count) finished = 0;
693 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
695 update_context_from_thread(avctx, p->avctx, 1);
697 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
699 fctx->next_finished = finished;
701 /* return the size of the consumed packet if no error occurred */
702 return (p->result >= 0) ? avpkt->size : p->result;
705 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
708 volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
710 if (!progress || progress[field] >= n) return;
712 p = f->owner->thread_opaque;
714 if (f->owner->debug&FF_DEBUG_THREADS)
715 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
717 pthread_mutex_lock(&p->progress_mutex);
719 pthread_cond_broadcast(&p->progress_cond);
720 pthread_mutex_unlock(&p->progress_mutex);
723 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
726 volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
728 if (!progress || progress[field] >= n) return;
730 p = f->owner->thread_opaque;
732 if (f->owner->debug&FF_DEBUG_THREADS)
733 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
735 pthread_mutex_lock(&p->progress_mutex);
736 while (progress[field] < n)
737 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
738 pthread_mutex_unlock(&p->progress_mutex);
741 void ff_thread_finish_setup(AVCodecContext *avctx) {
742 PerThreadContext *p = avctx->thread_opaque;
744 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
746 if(p->state == STATE_SETUP_FINISHED){
747 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
750 pthread_mutex_lock(&p->progress_mutex);
751 p->state = STATE_SETUP_FINISHED;
752 pthread_cond_broadcast(&p->progress_cond);
753 pthread_mutex_unlock(&p->progress_mutex);
756 /// Waits for all threads to finish.
757 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
761 for (i = 0; i < thread_count; i++) {
762 PerThreadContext *p = &fctx->threads[i];
764 if (p->state != STATE_INPUT_READY) {
765 pthread_mutex_lock(&p->progress_mutex);
766 while (p->state != STATE_INPUT_READY)
767 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
768 pthread_mutex_unlock(&p->progress_mutex);
774 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
776 FrameThreadContext *fctx = avctx->thread_opaque;
777 const AVCodec *codec = avctx->codec;
780 park_frame_worker_threads(fctx, thread_count);
782 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
783 if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
784 av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
785 fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
786 fctx->threads->avctx->internal->is_copy = 1;
791 for (i = 0; i < thread_count; i++) {
792 PerThreadContext *p = &fctx->threads[i];
794 pthread_mutex_lock(&p->mutex);
795 pthread_cond_signal(&p->input_cond);
796 pthread_mutex_unlock(&p->mutex);
799 pthread_join(p->thread, NULL);
803 codec->close(p->avctx);
807 release_delayed_buffers(p);
808 av_frame_unref(&p->frame);
811 for (i = 0; i < thread_count; i++) {
812 PerThreadContext *p = &fctx->threads[i];
814 pthread_mutex_destroy(&p->mutex);
815 pthread_mutex_destroy(&p->progress_mutex);
816 pthread_cond_destroy(&p->input_cond);
817 pthread_cond_destroy(&p->progress_cond);
818 pthread_cond_destroy(&p->output_cond);
819 av_buffer_unref(&p->avpkt.buf);
821 av_freep(&p->released_buffers);
824 av_freep(&p->avctx->priv_data);
825 av_freep(&p->avctx->internal);
826 av_freep(&p->avctx->slice_offset);
832 av_freep(&fctx->threads);
833 pthread_mutex_destroy(&fctx->buffer_mutex);
834 av_freep(&avctx->thread_opaque);
837 static int frame_thread_init(AVCodecContext *avctx)
839 int thread_count = avctx->thread_count;
840 const AVCodec *codec = avctx->codec;
841 AVCodecContext *src = avctx;
842 FrameThreadContext *fctx;
846 int nb_cpus = ff_get_logical_cpus(avctx);
847 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
849 // use number of cores + 1 as thread count if there is more than one
851 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
853 thread_count = avctx->thread_count = 1;
856 if (thread_count <= 1) {
857 avctx->active_thread_type = 0;
861 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
863 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
864 pthread_mutex_init(&fctx->buffer_mutex, NULL);
867 for (i = 0; i < thread_count; i++) {
868 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
869 PerThreadContext *p = &fctx->threads[i];
871 pthread_mutex_init(&p->mutex, NULL);
872 pthread_mutex_init(&p->progress_mutex, NULL);
873 pthread_cond_init(&p->input_cond, NULL);
874 pthread_cond_init(&p->progress_cond, NULL);
875 pthread_cond_init(&p->output_cond, NULL);
881 err = AVERROR(ENOMEM);
886 copy->thread_opaque = p;
887 copy->pkt = &p->avpkt;
893 err = codec->init(copy);
895 update_context_from_thread(avctx, copy, 1);
897 copy->priv_data = av_malloc(codec->priv_data_size);
898 if (!copy->priv_data) {
899 err = AVERROR(ENOMEM);
902 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
903 copy->internal = av_malloc(sizeof(AVCodecInternal));
904 if (!copy->internal) {
905 err = AVERROR(ENOMEM);
908 *copy->internal = *src->internal;
909 copy->internal->is_copy = 1;
911 if (codec->init_thread_copy)
912 err = codec->init_thread_copy(copy);
917 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
918 p->thread_init= !err;
926 frame_thread_free(avctx, i+1);
931 void ff_thread_flush(AVCodecContext *avctx)
934 FrameThreadContext *fctx = avctx->thread_opaque;
936 if (!avctx->thread_opaque) return;
938 park_frame_worker_threads(fctx, avctx->thread_count);
939 if (fctx->prev_thread) {
940 if (fctx->prev_thread != &fctx->threads[0])
941 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
942 if (avctx->codec->flush)
943 avctx->codec->flush(fctx->threads[0].avctx);
946 fctx->next_decoding = fctx->next_finished = 0;
948 fctx->prev_thread = NULL;
949 for (i = 0; i < avctx->thread_count; i++) {
950 PerThreadContext *p = &fctx->threads[i];
951 // Make sure decode flush calls with size=0 won't return old frames
953 av_frame_unref(&p->frame);
955 release_delayed_buffers(p);
959 int ff_thread_can_start_frame(AVCodecContext *avctx)
961 PerThreadContext *p = avctx->thread_opaque;
962 if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
963 (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks && (
964 #if FF_API_GET_BUFFER
967 avctx->get_buffer2 != avcodec_default_get_buffer2)))) {
973 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
975 PerThreadContext *p = avctx->thread_opaque;
980 ff_init_buffer_info(avctx, f->f);
982 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
983 return ff_get_buffer(avctx, f->f, flags);
985 if (p->state != STATE_SETTING_UP &&
986 (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks && (
987 #if FF_API_GET_BUFFER
990 avctx->get_buffer2 != avcodec_default_get_buffer2)))) {
991 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
995 if (avctx->internal->allocate_progress) {
997 f->progress = av_buffer_alloc(2 * sizeof(int));
999 return AVERROR(ENOMEM);
1001 progress = (int*)f->progress->data;
1003 progress[0] = progress[1] = -1;
1006 pthread_mutex_lock(&p->parent->buffer_mutex);
1008 if (avctx->thread_safe_callbacks || (
1009 #if FF_API_GET_BUFFER
1010 !avctx->get_buffer &&
1012 avctx->get_buffer2 == avcodec_default_get_buffer2)) {
1013 err = ff_get_buffer(avctx, f->f, flags);
1015 pthread_mutex_lock(&p->progress_mutex);
1016 p->requested_frame = f->f;
1017 p->requested_flags = flags;
1018 p->state = STATE_GET_BUFFER;
1019 pthread_cond_broadcast(&p->progress_cond);
1021 while (p->state != STATE_SETTING_UP)
1022 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
1026 pthread_mutex_unlock(&p->progress_mutex);
1029 if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
1030 ff_thread_finish_setup(avctx);
1033 av_buffer_unref(&f->progress);
1035 pthread_mutex_unlock(&p->parent->buffer_mutex);
1040 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1042 enum AVPixelFormat res;
1043 PerThreadContext *p = avctx->thread_opaque;
1044 if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
1045 avctx->get_format == avcodec_default_get_format)
1046 return avctx->get_format(avctx, fmt);
1047 if (p->state != STATE_SETTING_UP) {
1048 av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
1051 pthread_mutex_lock(&p->progress_mutex);
1052 p->available_formats = fmt;
1053 p->state = STATE_GET_FORMAT;
1054 pthread_cond_broadcast(&p->progress_cond);
1056 while (p->state != STATE_SETTING_UP)
1057 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
1059 res = p->result_format;
1061 pthread_mutex_unlock(&p->progress_mutex);
1066 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1068 int ret = thread_get_buffer_internal(avctx, f, flags);
1070 av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1074 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1076 PerThreadContext *p = avctx->thread_opaque;
1077 FrameThreadContext *fctx;
1079 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1080 avctx->thread_safe_callbacks ||
1082 #if FF_API_GET_BUFFER
1083 !avctx->get_buffer &&
1085 avctx->get_buffer2 == avcodec_default_get_buffer2);
1090 if (avctx->debug & FF_DEBUG_BUFFERS)
1091 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1093 av_buffer_unref(&f->progress);
1096 if (can_direct_free) {
1097 av_frame_unref(f->f);
1102 pthread_mutex_lock(&fctx->buffer_mutex);
1104 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
1106 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
1107 (p->num_released_buffers + 1) *
1108 sizeof(*p->released_buffers));
1111 p->released_buffers = tmp;
1113 dst = &p->released_buffers[p->num_released_buffers];
1114 av_frame_move_ref(dst, f->f);
1116 p->num_released_buffers++;
1119 pthread_mutex_unlock(&fctx->buffer_mutex);
1123 * Set the threading algorithms used.
1125 * Threading requires more than one thread.
1126 * Frame threading requires entire frames to be passed to the codec,
1127 * and introduces extra decoding delay, so is incompatible with low_delay.
1129 * @param avctx The context.
1131 static void validate_thread_parameters(AVCodecContext *avctx)
1133 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1134 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1135 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1136 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1137 if (avctx->thread_count == 1) {
1138 avctx->active_thread_type = 0;
1139 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1140 avctx->active_thread_type = FF_THREAD_FRAME;
1141 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1142 avctx->thread_type & FF_THREAD_SLICE) {
1143 avctx->active_thread_type = FF_THREAD_SLICE;
1144 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1145 avctx->thread_count = 1;
1146 avctx->active_thread_type = 0;
1149 if (avctx->thread_count > MAX_AUTO_THREADS)
1150 av_log(avctx, AV_LOG_WARNING,
1151 "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1152 avctx->thread_count, MAX_AUTO_THREADS);
1155 int ff_thread_init(AVCodecContext *avctx)
1157 if (avctx->thread_opaque) {
1158 av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
1167 validate_thread_parameters(avctx);
1169 if (avctx->active_thread_type&FF_THREAD_SLICE)
1170 return thread_init(avctx);
1171 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1172 return frame_thread_init(avctx);
1178 void ff_thread_free(AVCodecContext *avctx)
1180 if (avctx->active_thread_type&FF_THREAD_FRAME)
1181 frame_thread_free(avctx, avctx->thread_count);