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
37 #include "libavutil/avassert.h"
38 #include "libavutil/common.h"
39 #include "libavutil/cpu.h"
44 #include "compat/w32pthreads.h"
46 #include "compat/os2threads.h"
49 typedef int (action_func)(AVCodecContext *c, void *arg);
50 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
52 typedef struct ThreadContext {
62 pthread_cond_t last_job_cond;
63 pthread_cond_t current_job_cond;
64 pthread_mutex_t current_job_lock;
66 unsigned int current_execute;
71 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
73 typedef struct PerThreadContext {
74 struct FrameThreadContext *parent;
78 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
79 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
80 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
82 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
83 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
85 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
87 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
88 uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
89 int allocated_buf_size; ///< Size allocated for buf
91 AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
92 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
93 int result; ///< The result of the last codec decode/encode() call.
96 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
97 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
98 STATE_GET_BUFFER, /**<
99 * Set when the codec calls get_buffer().
100 * State is returned to STATE_SETTING_UP afterwards.
102 STATE_GET_FORMAT, /**<
103 * Set when the codec calls get_format().
104 * State is returned to STATE_SETTING_UP afterwards.
106 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
110 * Array of frames passed to ff_thread_release_buffer().
111 * Frames are released after all threads referencing them are finished.
113 AVFrame *released_buffers;
114 int num_released_buffers;
115 int released_buffers_allocated;
117 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
118 int requested_flags; ///< flags passed to get_buffer() for requested_frame
120 const enum AVPixelFormat *available_formats; ///< Format array for get_format()
121 enum AVPixelFormat result_format; ///< get_format() result
125 * Context stored in the client AVCodecContext thread_opaque.
127 typedef struct FrameThreadContext {
128 PerThreadContext *threads; ///< The contexts for each thread.
129 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
131 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
133 int next_decoding; ///< The next context to submit a packet to.
134 int next_finished; ///< The next context to return output from.
137 * Set for the first N packets, where N is the number of threads.
138 * While it is set, ff_thread_en/decode_frame won't return any results.
141 int die; ///< Set when threads should exit.
142 } FrameThreadContext;
145 /* H264 slice threading seems to be buggy with more than 16 threads,
146 * limit the number of threads to 16 for automatic detection */
147 #define MAX_AUTO_THREADS 16
149 static void* attribute_align_arg worker(void *v)
151 AVCodecContext *avctx = v;
152 ThreadContext *c = avctx->thread_opaque;
153 int our_job = c->job_count;
154 int last_execute = 0;
155 int thread_count = avctx->thread_count;
158 pthread_mutex_lock(&c->current_job_lock);
159 self_id = c->current_job++;
161 while (our_job >= c->job_count) {
162 if (c->current_job == thread_count + c->job_count)
163 pthread_cond_signal(&c->last_job_cond);
165 while (last_execute == c->current_execute && !c->done)
166 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
167 last_execute = c->current_execute;
171 pthread_mutex_unlock(&c->current_job_lock);
175 pthread_mutex_unlock(&c->current_job_lock);
177 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
178 c->func2(avctx, c->args, our_job, self_id);
180 pthread_mutex_lock(&c->current_job_lock);
181 our_job = c->current_job++;
185 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
187 while (c->current_job != thread_count + c->job_count)
188 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
189 pthread_mutex_unlock(&c->current_job_lock);
192 static void thread_free(AVCodecContext *avctx)
194 ThreadContext *c = avctx->thread_opaque;
197 pthread_mutex_lock(&c->current_job_lock);
199 pthread_cond_broadcast(&c->current_job_cond);
200 pthread_mutex_unlock(&c->current_job_lock);
202 for (i=0; i<avctx->thread_count; i++)
203 pthread_join(c->workers[i], NULL);
205 pthread_mutex_destroy(&c->current_job_lock);
206 pthread_cond_destroy(&c->current_job_cond);
207 pthread_cond_destroy(&c->last_job_cond);
209 av_freep(&avctx->thread_opaque);
212 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
214 ThreadContext *c= avctx->thread_opaque;
217 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
218 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
223 pthread_mutex_lock(&c->current_job_lock);
225 c->current_job = avctx->thread_count;
226 c->job_count = job_count;
227 c->job_size = job_size;
232 c->rets_count = job_count;
234 c->rets = &dummy_ret;
237 c->current_execute++;
238 pthread_cond_broadcast(&c->current_job_cond);
240 avcodec_thread_park_workers(c, avctx->thread_count);
245 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
247 ThreadContext *c= avctx->thread_opaque;
249 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
252 static int thread_init(AVCodecContext *avctx)
256 int thread_count = avctx->thread_count;
259 int nb_cpus = av_cpu_count();
261 nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
262 // use number of cores + 1 as thread count if there is more than one
264 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
266 thread_count = avctx->thread_count = 1;
269 if (thread_count <= 1) {
270 avctx->active_thread_type = 0;
274 c = av_mallocz(sizeof(ThreadContext));
278 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
284 avctx->thread_opaque = c;
289 pthread_cond_init(&c->current_job_cond, NULL);
290 pthread_cond_init(&c->last_job_cond, NULL);
291 pthread_mutex_init(&c->current_job_lock, NULL);
292 pthread_mutex_lock(&c->current_job_lock);
293 for (i=0; i<thread_count; i++) {
294 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
295 avctx->thread_count = i;
296 pthread_mutex_unlock(&c->current_job_lock);
297 ff_thread_free(avctx);
302 avcodec_thread_park_workers(c, thread_count);
304 avctx->execute = avcodec_thread_execute;
305 avctx->execute2 = avcodec_thread_execute2;
309 #define THREAD_SAFE_CALLBACKS(avctx) \
310 ((avctx)->thread_safe_callbacks || (!(avctx)->get_buffer && (avctx)->get_buffer2 == avcodec_default_get_buffer2))
313 * Codec worker thread.
315 * Automatically calls ff_thread_finish_setup() if the codec does
316 * not provide an update_thread_context method, or if the codec returns
319 static attribute_align_arg void *frame_worker_thread(void *arg)
321 PerThreadContext *p = arg;
322 FrameThreadContext *fctx = p->parent;
323 AVCodecContext *avctx = p->avctx;
324 const AVCodec *codec = avctx->codec;
326 pthread_mutex_lock(&p->mutex);
328 while (p->state == STATE_INPUT_READY && !fctx->die)
329 pthread_cond_wait(&p->input_cond, &p->mutex);
331 if (fctx->die) break;
333 if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
334 ff_thread_finish_setup(avctx);
336 avcodec_get_frame_defaults(&p->frame);
338 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
340 /* many decoders assign whole AVFrames, thus overwriting extended_data;
341 * make sure it's set correctly */
342 p->frame.extended_data = p->frame.data;
344 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
346 pthread_mutex_lock(&p->progress_mutex);
348 for (i = 0; i < MAX_BUFFERS; i++)
349 if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
350 p->progress[i][0] = INT_MAX;
351 p->progress[i][1] = INT_MAX;
354 p->state = STATE_INPUT_READY;
356 pthread_cond_broadcast(&p->progress_cond);
357 pthread_cond_signal(&p->output_cond);
358 pthread_mutex_unlock(&p->progress_mutex);
360 pthread_mutex_unlock(&p->mutex);
366 * Update the next thread's AVCodecContext with values from the reference thread's context.
368 * @param dst The destination context.
369 * @param src The source context.
370 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
372 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
377 dst->time_base = src->time_base;
378 dst->width = src->width;
379 dst->height = src->height;
380 dst->pix_fmt = src->pix_fmt;
382 dst->coded_width = src->coded_width;
383 dst->coded_height = src->coded_height;
385 dst->has_b_frames = src->has_b_frames;
386 dst->idct_algo = src->idct_algo;
388 dst->bits_per_coded_sample = src->bits_per_coded_sample;
389 dst->sample_aspect_ratio = src->sample_aspect_ratio;
390 dst->dtg_active_format = src->dtg_active_format;
392 dst->profile = src->profile;
393 dst->level = src->level;
395 dst->bits_per_raw_sample = src->bits_per_raw_sample;
396 dst->ticks_per_frame = src->ticks_per_frame;
397 dst->color_primaries = src->color_primaries;
399 dst->color_trc = src->color_trc;
400 dst->colorspace = src->colorspace;
401 dst->color_range = src->color_range;
402 dst->chroma_sample_location = src->chroma_sample_location;
404 dst->hwaccel = src->hwaccel;
405 dst->hwaccel_context = src->hwaccel_context;
407 dst->channels = src->channels;
408 dst->sample_rate = src->sample_rate;
409 dst->sample_fmt = src->sample_fmt;
410 dst->channel_layout = src->channel_layout;
414 dst->delay = src->thread_count - 1;
415 dst->coded_frame = src->coded_frame;
417 if (dst->codec->update_thread_context)
418 err = dst->codec->update_thread_context(dst, src);
425 * Update the next thread's AVCodecContext with values set by the user.
427 * @param dst The destination context.
428 * @param src The source context.
429 * @return 0 on success, negative error code on failure
431 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
433 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
434 dst->flags = src->flags;
436 dst->draw_horiz_band= src->draw_horiz_band;
437 dst->get_buffer2 = src->get_buffer2;
438 #if FF_API_GET_BUFFER
439 dst->get_buffer = src->get_buffer;
440 dst->release_buffer = src->release_buffer;
443 dst->opaque = src->opaque;
444 dst->debug = src->debug;
445 dst->debug_mv = src->debug_mv;
447 dst->slice_flags = src->slice_flags;
448 dst->flags2 = src->flags2;
450 copy_fields(skip_loop_filter, subtitle_header);
452 dst->frame_number = src->frame_number;
453 dst->reordered_opaque = src->reordered_opaque;
454 dst->thread_safe_callbacks = src->thread_safe_callbacks;
456 if (src->slice_count && src->slice_offset) {
457 if (dst->slice_count < src->slice_count) {
458 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
459 sizeof(*dst->slice_offset));
461 av_free(dst->slice_offset);
462 return AVERROR(ENOMEM);
464 dst->slice_offset = tmp;
466 memcpy(dst->slice_offset, src->slice_offset,
467 src->slice_count * sizeof(*dst->slice_offset));
469 dst->slice_count = src->slice_count;
474 /// Releases the buffers that this decoding thread was the last user of.
475 static void release_delayed_buffers(PerThreadContext *p)
477 FrameThreadContext *fctx = p->parent;
479 while (p->num_released_buffers > 0) {
482 pthread_mutex_lock(&fctx->buffer_mutex);
484 // fix extended data in case the caller screwed it up
485 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
486 p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
487 f = &p->released_buffers[--p->num_released_buffers];
488 f->extended_data = f->data;
491 pthread_mutex_unlock(&fctx->buffer_mutex);
495 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
497 FrameThreadContext *fctx = p->parent;
498 PerThreadContext *prev_thread = fctx->prev_thread;
499 const AVCodec *codec = p->avctx->codec;
501 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
503 pthread_mutex_lock(&p->mutex);
505 release_delayed_buffers(p);
509 if (prev_thread->state == STATE_SETTING_UP) {
510 pthread_mutex_lock(&prev_thread->progress_mutex);
511 while (prev_thread->state == STATE_SETTING_UP)
512 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
513 pthread_mutex_unlock(&prev_thread->progress_mutex);
516 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
518 pthread_mutex_unlock(&p->mutex);
523 av_buffer_unref(&p->avpkt.buf);
526 p->avpkt.buf = av_buffer_ref(avpkt->buf);
528 av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
529 p->avpkt.data = p->buf;
530 memcpy(p->buf, avpkt->data, avpkt->size);
531 memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
534 p->state = STATE_SETTING_UP;
535 pthread_cond_signal(&p->input_cond);
536 pthread_mutex_unlock(&p->mutex);
539 * If the client doesn't have a thread-safe get_buffer(),
540 * then decoding threads call back to the main thread,
541 * and it calls back to the client here.
544 if (!p->avctx->thread_safe_callbacks && (
545 p->avctx->get_format != avcodec_default_get_format ||
546 #if FF_API_GET_BUFFER
547 p->avctx->get_buffer ||
549 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
550 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
552 pthread_mutex_lock(&p->progress_mutex);
553 while (p->state == STATE_SETTING_UP)
554 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
557 case STATE_GET_BUFFER:
558 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
560 case STATE_GET_FORMAT:
561 p->result_format = p->avctx->get_format(p->avctx, p->available_formats);
568 p->state = STATE_SETTING_UP;
569 pthread_cond_signal(&p->progress_cond);
571 pthread_mutex_unlock(&p->progress_mutex);
575 fctx->prev_thread = p;
576 fctx->next_decoding++;
581 int ff_thread_decode_frame(AVCodecContext *avctx,
582 AVFrame *picture, int *got_picture_ptr,
585 FrameThreadContext *fctx = avctx->thread_opaque;
586 int finished = fctx->next_finished;
591 * Submit a packet to the next decoding thread.
594 p = &fctx->threads[fctx->next_decoding];
595 err = update_context_from_user(p->avctx, avctx);
597 err = submit_packet(p, avpkt);
601 * If we're still receiving the initial packets, don't return a frame.
604 if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
607 if (fctx->delaying) {
614 * Return the next available frame from the oldest thread.
615 * If we're at the end of the stream, then we have to skip threads that
616 * didn't output a frame, because we don't want to accidentally signal
617 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
621 p = &fctx->threads[finished++];
623 if (p->state != STATE_INPUT_READY) {
624 pthread_mutex_lock(&p->progress_mutex);
625 while (p->state != STATE_INPUT_READY)
626 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
627 pthread_mutex_unlock(&p->progress_mutex);
630 av_frame_move_ref(picture, &p->frame);
631 *got_picture_ptr = p->got_frame;
632 picture->pkt_dts = p->avpkt.dts;
635 * A later call with avkpt->size == 0 may loop over all threads,
636 * including this one, searching for a frame to return before being
637 * stopped by the "finished != fctx->next_finished" condition.
638 * Make sure we don't mistakenly return the same frame again.
642 if (finished >= avctx->thread_count) finished = 0;
643 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
645 update_context_from_thread(avctx, p->avctx, 1);
647 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
649 fctx->next_finished = finished;
651 /* return the size of the consumed packet if no error occurred */
652 return (p->result >= 0) ? avpkt->size : p->result;
655 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
658 volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
660 if (!progress || progress[field] >= n) return;
662 p = f->owner->thread_opaque;
664 if (f->owner->debug&FF_DEBUG_THREADS)
665 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
667 pthread_mutex_lock(&p->progress_mutex);
669 pthread_cond_broadcast(&p->progress_cond);
670 pthread_mutex_unlock(&p->progress_mutex);
673 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
676 volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
678 if (!progress || progress[field] >= n) return;
680 p = f->owner->thread_opaque;
682 if (f->owner->debug&FF_DEBUG_THREADS)
683 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
685 pthread_mutex_lock(&p->progress_mutex);
686 while (progress[field] < n)
687 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
688 pthread_mutex_unlock(&p->progress_mutex);
691 void ff_thread_finish_setup(AVCodecContext *avctx) {
692 PerThreadContext *p = avctx->thread_opaque;
694 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
696 if(p->state == STATE_SETUP_FINISHED){
697 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
700 pthread_mutex_lock(&p->progress_mutex);
701 p->state = STATE_SETUP_FINISHED;
702 pthread_cond_broadcast(&p->progress_cond);
703 pthread_mutex_unlock(&p->progress_mutex);
706 /// Waits for all threads to finish.
707 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
711 for (i = 0; i < thread_count; i++) {
712 PerThreadContext *p = &fctx->threads[i];
714 if (p->state != STATE_INPUT_READY) {
715 pthread_mutex_lock(&p->progress_mutex);
716 while (p->state != STATE_INPUT_READY)
717 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
718 pthread_mutex_unlock(&p->progress_mutex);
724 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
726 FrameThreadContext *fctx = avctx->thread_opaque;
727 const AVCodec *codec = avctx->codec;
730 park_frame_worker_threads(fctx, thread_count);
732 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
733 if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
734 av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
735 fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
736 fctx->threads->avctx->internal->is_copy = 1;
741 for (i = 0; i < thread_count; i++) {
742 PerThreadContext *p = &fctx->threads[i];
744 pthread_mutex_lock(&p->mutex);
745 pthread_cond_signal(&p->input_cond);
746 pthread_mutex_unlock(&p->mutex);
749 pthread_join(p->thread, NULL);
753 codec->close(p->avctx);
757 release_delayed_buffers(p);
758 av_frame_unref(&p->frame);
761 for (i = 0; i < thread_count; i++) {
762 PerThreadContext *p = &fctx->threads[i];
764 pthread_mutex_destroy(&p->mutex);
765 pthread_mutex_destroy(&p->progress_mutex);
766 pthread_cond_destroy(&p->input_cond);
767 pthread_cond_destroy(&p->progress_cond);
768 pthread_cond_destroy(&p->output_cond);
769 av_buffer_unref(&p->avpkt.buf);
771 av_freep(&p->released_buffers);
774 av_freep(&p->avctx->priv_data);
775 av_freep(&p->avctx->internal);
776 av_freep(&p->avctx->slice_offset);
782 av_freep(&fctx->threads);
783 pthread_mutex_destroy(&fctx->buffer_mutex);
784 av_freep(&avctx->thread_opaque);
787 static int frame_thread_init(AVCodecContext *avctx)
789 int thread_count = avctx->thread_count;
790 const AVCodec *codec = avctx->codec;
791 AVCodecContext *src = avctx;
792 FrameThreadContext *fctx;
796 int nb_cpus = av_cpu_count();
797 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
799 // use number of cores + 1 as thread count if there is more than one
801 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
803 thread_count = avctx->thread_count = 1;
806 if (thread_count <= 1) {
807 avctx->active_thread_type = 0;
811 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
813 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
814 pthread_mutex_init(&fctx->buffer_mutex, NULL);
817 for (i = 0; i < thread_count; i++) {
818 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
819 PerThreadContext *p = &fctx->threads[i];
821 pthread_mutex_init(&p->mutex, NULL);
822 pthread_mutex_init(&p->progress_mutex, NULL);
823 pthread_cond_init(&p->input_cond, NULL);
824 pthread_cond_init(&p->progress_cond, NULL);
825 pthread_cond_init(&p->output_cond, NULL);
831 err = AVERROR(ENOMEM);
836 copy->thread_opaque = p;
837 copy->pkt = &p->avpkt;
843 err = codec->init(copy);
845 update_context_from_thread(avctx, copy, 1);
847 copy->priv_data = av_malloc(codec->priv_data_size);
848 if (!copy->priv_data) {
849 err = AVERROR(ENOMEM);
852 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
853 copy->internal = av_malloc(sizeof(AVCodecInternal));
854 if (!copy->internal) {
855 err = AVERROR(ENOMEM);
858 *copy->internal = *src->internal;
859 copy->internal->is_copy = 1;
861 if (codec->init_thread_copy)
862 err = codec->init_thread_copy(copy);
867 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
868 p->thread_init= !err;
876 frame_thread_free(avctx, i+1);
881 void ff_thread_flush(AVCodecContext *avctx)
884 FrameThreadContext *fctx = avctx->thread_opaque;
886 if (!avctx->thread_opaque) return;
888 park_frame_worker_threads(fctx, avctx->thread_count);
889 if (fctx->prev_thread) {
890 if (fctx->prev_thread != &fctx->threads[0])
891 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
892 if (avctx->codec->flush)
893 avctx->codec->flush(fctx->threads[0].avctx);
896 fctx->next_decoding = fctx->next_finished = 0;
898 fctx->prev_thread = NULL;
899 for (i = 0; i < avctx->thread_count; i++) {
900 PerThreadContext *p = &fctx->threads[i];
901 // Make sure decode flush calls with size=0 won't return old frames
903 av_frame_unref(&p->frame);
905 release_delayed_buffers(p);
909 int ff_thread_can_start_frame(AVCodecContext *avctx)
911 PerThreadContext *p = avctx->thread_opaque;
912 if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
913 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
919 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
921 PerThreadContext *p = avctx->thread_opaque;
926 ff_init_buffer_info(avctx, f->f);
928 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
929 return ff_get_buffer(avctx, f->f, flags);
931 if (p->state != STATE_SETTING_UP &&
932 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
933 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
937 if (avctx->internal->allocate_progress) {
939 f->progress = av_buffer_alloc(2 * sizeof(int));
941 return AVERROR(ENOMEM);
943 progress = (int*)f->progress->data;
945 progress[0] = progress[1] = -1;
948 pthread_mutex_lock(&p->parent->buffer_mutex);
950 if (avctx->thread_safe_callbacks || (
951 #if FF_API_GET_BUFFER
952 !avctx->get_buffer &&
954 avctx->get_buffer2 == avcodec_default_get_buffer2)) {
955 err = ff_get_buffer(avctx, f->f, flags);
957 pthread_mutex_lock(&p->progress_mutex);
958 p->requested_frame = f->f;
959 p->requested_flags = flags;
960 p->state = STATE_GET_BUFFER;
961 pthread_cond_broadcast(&p->progress_cond);
963 while (p->state != STATE_SETTING_UP)
964 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
968 pthread_mutex_unlock(&p->progress_mutex);
971 if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
972 ff_thread_finish_setup(avctx);
975 av_buffer_unref(&f->progress);
977 pthread_mutex_unlock(&p->parent->buffer_mutex);
982 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
984 enum AVPixelFormat res;
985 PerThreadContext *p = avctx->thread_opaque;
986 if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
987 avctx->get_format == avcodec_default_get_format)
988 return avctx->get_format(avctx, fmt);
989 if (p->state != STATE_SETTING_UP) {
990 av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
993 pthread_mutex_lock(&p->progress_mutex);
994 p->available_formats = fmt;
995 p->state = STATE_GET_FORMAT;
996 pthread_cond_broadcast(&p->progress_cond);
998 while (p->state != STATE_SETTING_UP)
999 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
1001 res = p->result_format;
1003 pthread_mutex_unlock(&p->progress_mutex);
1008 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1010 int ret = thread_get_buffer_internal(avctx, f, flags);
1012 av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1016 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1018 PerThreadContext *p = avctx->thread_opaque;
1019 FrameThreadContext *fctx;
1021 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1022 avctx->thread_safe_callbacks ||
1024 #if FF_API_GET_BUFFER
1025 !avctx->get_buffer &&
1027 avctx->get_buffer2 == avcodec_default_get_buffer2);
1032 if (avctx->debug & FF_DEBUG_BUFFERS)
1033 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1035 av_buffer_unref(&f->progress);
1038 if (can_direct_free) {
1039 av_frame_unref(f->f);
1044 pthread_mutex_lock(&fctx->buffer_mutex);
1046 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
1048 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
1049 (p->num_released_buffers + 1) *
1050 sizeof(*p->released_buffers));
1053 p->released_buffers = tmp;
1055 dst = &p->released_buffers[p->num_released_buffers];
1056 av_frame_move_ref(dst, f->f);
1058 p->num_released_buffers++;
1061 pthread_mutex_unlock(&fctx->buffer_mutex);
1065 * Set the threading algorithms used.
1067 * Threading requires more than one thread.
1068 * Frame threading requires entire frames to be passed to the codec,
1069 * and introduces extra decoding delay, so is incompatible with low_delay.
1071 * @param avctx The context.
1073 static void validate_thread_parameters(AVCodecContext *avctx)
1075 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1076 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1077 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1078 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1079 if (avctx->thread_count == 1) {
1080 avctx->active_thread_type = 0;
1081 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1082 avctx->active_thread_type = FF_THREAD_FRAME;
1083 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1084 avctx->thread_type & FF_THREAD_SLICE) {
1085 avctx->active_thread_type = FF_THREAD_SLICE;
1086 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1087 avctx->thread_count = 1;
1088 avctx->active_thread_type = 0;
1091 if (avctx->thread_count > MAX_AUTO_THREADS)
1092 av_log(avctx, AV_LOG_WARNING,
1093 "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1094 avctx->thread_count, MAX_AUTO_THREADS);
1097 int ff_thread_init(AVCodecContext *avctx)
1103 validate_thread_parameters(avctx);
1105 if (avctx->active_thread_type&FF_THREAD_SLICE)
1106 return thread_init(avctx);
1107 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1108 return frame_thread_init(avctx);
1113 void ff_thread_free(AVCodecContext *avctx)
1115 if (avctx->active_thread_type&FF_THREAD_FRAME)
1116 frame_thread_free(avctx, avctx->thread_count);