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"
40 #include "libavutil/internal.h"
45 #include "compat/w32pthreads.h"
47 #include "compat/os2threads.h"
50 typedef int (action_func)(AVCodecContext *c, void *arg);
51 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
53 typedef struct ThreadContext {
63 pthread_cond_t last_job_cond;
64 pthread_cond_t current_job_cond;
65 pthread_mutex_t current_job_lock;
66 unsigned current_execute;
73 pthread_cond_t *progress_cond;
74 pthread_mutex_t *progress_mutex;
78 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
80 typedef struct PerThreadContext {
81 struct FrameThreadContext *parent;
85 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
86 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
87 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
89 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
90 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
92 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
94 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
95 uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
96 int allocated_buf_size; ///< Size allocated for buf
98 AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
99 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
100 int result; ///< The result of the last codec decode/encode() call.
103 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
104 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
105 STATE_GET_BUFFER, /**<
106 * Set when the codec calls get_buffer().
107 * State is returned to STATE_SETTING_UP afterwards.
109 STATE_GET_FORMAT, /**<
110 * Set when the codec calls get_format().
111 * State is returned to STATE_SETTING_UP afterwards.
113 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
117 * Array of frames passed to ff_thread_release_buffer().
118 * Frames are released after all threads referencing them are finished.
120 AVFrame *released_buffers;
121 int num_released_buffers;
122 int released_buffers_allocated;
124 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
125 int requested_flags; ///< flags passed to get_buffer() for requested_frame
127 const enum AVPixelFormat *available_formats; ///< Format array for get_format()
128 enum AVPixelFormat result_format; ///< get_format() result
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 void* attribute_align_arg worker(void *v)
158 AVCodecContext *avctx = v;
159 ThreadContext *c = avctx->thread_opaque;
160 unsigned last_execute = 0;
161 int our_job = c->job_count;
162 int thread_count = avctx->thread_count;
165 pthread_mutex_lock(&c->current_job_lock);
166 self_id = c->current_job++;
168 while (our_job >= c->job_count) {
169 if (c->current_job == thread_count + c->job_count)
170 pthread_cond_signal(&c->last_job_cond);
172 while (last_execute == c->current_execute && !c->done)
173 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
174 last_execute = c->current_execute;
178 pthread_mutex_unlock(&c->current_job_lock);
182 pthread_mutex_unlock(&c->current_job_lock);
184 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
185 c->func2(avctx, c->args, our_job, self_id);
187 pthread_mutex_lock(&c->current_job_lock);
188 our_job = c->current_job++;
192 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
194 while (c->current_job != thread_count + c->job_count)
195 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
196 pthread_mutex_unlock(&c->current_job_lock);
199 static void thread_free(AVCodecContext *avctx)
201 ThreadContext *c = avctx->thread_opaque;
204 pthread_mutex_lock(&c->current_job_lock);
206 pthread_cond_broadcast(&c->current_job_cond);
207 pthread_mutex_unlock(&c->current_job_lock);
209 for (i=0; i<avctx->thread_count; i++)
210 pthread_join(c->workers[i], NULL);
212 pthread_mutex_destroy(&c->current_job_lock);
213 pthread_cond_destroy(&c->current_job_cond);
214 pthread_cond_destroy(&c->last_job_cond);
216 av_freep(&avctx->thread_opaque);
219 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
221 ThreadContext *c= avctx->thread_opaque;
224 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
225 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
230 pthread_mutex_lock(&c->current_job_lock);
232 c->current_job = avctx->thread_count;
233 c->job_count = job_count;
234 c->job_size = job_size;
239 c->rets_count = job_count;
241 c->rets = &dummy_ret;
244 c->current_execute++;
245 pthread_cond_broadcast(&c->current_job_cond);
247 avcodec_thread_park_workers(c, avctx->thread_count);
252 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
254 ThreadContext *c= avctx->thread_opaque;
256 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
259 static int thread_init_internal(AVCodecContext *avctx)
263 int thread_count = avctx->thread_count;
266 int nb_cpus = av_cpu_count();
268 nb_cpus = FFMIN(nb_cpus, (avctx->height+15)/16);
269 // use number of cores + 1 as thread count if there is more than one
271 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
273 thread_count = avctx->thread_count = 1;
276 if (thread_count <= 1) {
277 avctx->active_thread_type = 0;
281 c = av_mallocz(sizeof(ThreadContext));
285 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
291 avctx->thread_opaque = c;
296 pthread_cond_init(&c->current_job_cond, NULL);
297 pthread_cond_init(&c->last_job_cond, NULL);
298 pthread_mutex_init(&c->current_job_lock, NULL);
299 pthread_mutex_lock(&c->current_job_lock);
300 for (i=0; i<thread_count; i++) {
301 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
302 avctx->thread_count = i;
303 pthread_mutex_unlock(&c->current_job_lock);
304 ff_thread_free(avctx);
309 avcodec_thread_park_workers(c, thread_count);
311 avctx->execute = avcodec_thread_execute;
312 avctx->execute2 = avcodec_thread_execute2;
316 #define THREAD_SAFE_CALLBACKS(avctx) \
317 ((avctx)->thread_safe_callbacks || (!(avctx)->get_buffer && (avctx)->get_buffer2 == avcodec_default_get_buffer2))
320 * Codec worker thread.
322 * Automatically calls ff_thread_finish_setup() if the codec does
323 * not provide an update_thread_context method, or if the codec returns
326 static attribute_align_arg void *frame_worker_thread(void *arg)
328 PerThreadContext *p = arg;
329 FrameThreadContext *fctx = p->parent;
330 AVCodecContext *avctx = p->avctx;
331 const AVCodec *codec = avctx->codec;
333 pthread_mutex_lock(&p->mutex);
335 while (p->state == STATE_INPUT_READY && !fctx->die)
336 pthread_cond_wait(&p->input_cond, &p->mutex);
338 if (fctx->die) break;
340 if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
341 ff_thread_finish_setup(avctx);
343 avcodec_get_frame_defaults(&p->frame);
345 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
347 /* many decoders assign whole AVFrames, thus overwriting extended_data;
348 * make sure it's set correctly */
349 p->frame.extended_data = p->frame.data;
351 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
353 pthread_mutex_lock(&p->progress_mutex);
355 for (i = 0; i < MAX_BUFFERS; i++)
356 if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
357 p->progress[i][0] = INT_MAX;
358 p->progress[i][1] = INT_MAX;
361 p->state = STATE_INPUT_READY;
363 pthread_cond_broadcast(&p->progress_cond);
364 pthread_cond_signal(&p->output_cond);
365 pthread_mutex_unlock(&p->progress_mutex);
367 pthread_mutex_unlock(&p->mutex);
373 * Update the next thread's AVCodecContext with values from the reference thread's context.
375 * @param dst The destination context.
376 * @param src The source context.
377 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
379 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
384 dst->time_base = src->time_base;
385 dst->width = src->width;
386 dst->height = src->height;
387 dst->pix_fmt = src->pix_fmt;
389 dst->coded_width = src->coded_width;
390 dst->coded_height = src->coded_height;
392 dst->has_b_frames = src->has_b_frames;
393 dst->idct_algo = src->idct_algo;
395 dst->bits_per_coded_sample = src->bits_per_coded_sample;
396 dst->sample_aspect_ratio = src->sample_aspect_ratio;
397 dst->dtg_active_format = src->dtg_active_format;
399 dst->profile = src->profile;
400 dst->level = src->level;
402 dst->bits_per_raw_sample = src->bits_per_raw_sample;
403 dst->ticks_per_frame = src->ticks_per_frame;
404 dst->color_primaries = src->color_primaries;
406 dst->color_trc = src->color_trc;
407 dst->colorspace = src->colorspace;
408 dst->color_range = src->color_range;
409 dst->chroma_sample_location = src->chroma_sample_location;
411 dst->hwaccel = src->hwaccel;
412 dst->hwaccel_context = src->hwaccel_context;
414 dst->channels = src->channels;
415 dst->sample_rate = src->sample_rate;
416 dst->sample_fmt = src->sample_fmt;
417 dst->channel_layout = src->channel_layout;
421 dst->delay = src->thread_count - 1;
422 dst->coded_frame = src->coded_frame;
424 if (dst->codec->update_thread_context)
425 err = dst->codec->update_thread_context(dst, src);
432 * Update the next thread's AVCodecContext with values set by the user.
434 * @param dst The destination context.
435 * @param src The source context.
436 * @return 0 on success, negative error code on failure
438 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
440 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
441 dst->flags = src->flags;
443 dst->draw_horiz_band= src->draw_horiz_band;
444 dst->get_buffer2 = src->get_buffer2;
445 #if FF_API_GET_BUFFER
446 FF_DISABLE_DEPRECATION_WARNINGS
447 dst->get_buffer = src->get_buffer;
448 dst->release_buffer = src->release_buffer;
449 FF_ENABLE_DEPRECATION_WARNINGS
452 dst->opaque = src->opaque;
453 dst->debug = src->debug;
454 dst->debug_mv = src->debug_mv;
456 dst->slice_flags = src->slice_flags;
457 dst->flags2 = src->flags2;
459 copy_fields(skip_loop_filter, subtitle_header);
461 dst->frame_number = src->frame_number;
462 dst->reordered_opaque = src->reordered_opaque;
463 dst->thread_safe_callbacks = src->thread_safe_callbacks;
465 if (src->slice_count && src->slice_offset) {
466 if (dst->slice_count < src->slice_count) {
467 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
468 sizeof(*dst->slice_offset));
470 av_free(dst->slice_offset);
471 return AVERROR(ENOMEM);
473 dst->slice_offset = tmp;
475 memcpy(dst->slice_offset, src->slice_offset,
476 src->slice_count * sizeof(*dst->slice_offset));
478 dst->slice_count = src->slice_count;
483 /// Releases the buffers that this decoding thread was the last user of.
484 static void release_delayed_buffers(PerThreadContext *p)
486 FrameThreadContext *fctx = p->parent;
488 while (p->num_released_buffers > 0) {
491 pthread_mutex_lock(&fctx->buffer_mutex);
493 // fix extended data in case the caller screwed it up
494 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
495 p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
496 f = &p->released_buffers[--p->num_released_buffers];
497 f->extended_data = f->data;
500 pthread_mutex_unlock(&fctx->buffer_mutex);
504 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
506 FrameThreadContext *fctx = p->parent;
507 PerThreadContext *prev_thread = fctx->prev_thread;
508 const AVCodec *codec = p->avctx->codec;
510 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
512 pthread_mutex_lock(&p->mutex);
514 release_delayed_buffers(p);
518 if (prev_thread->state == STATE_SETTING_UP) {
519 pthread_mutex_lock(&prev_thread->progress_mutex);
520 while (prev_thread->state == STATE_SETTING_UP)
521 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
522 pthread_mutex_unlock(&prev_thread->progress_mutex);
525 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
527 pthread_mutex_unlock(&p->mutex);
532 av_buffer_unref(&p->avpkt.buf);
535 p->avpkt.buf = av_buffer_ref(avpkt->buf);
537 av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
538 p->avpkt.data = p->buf;
539 memcpy(p->buf, avpkt->data, avpkt->size);
540 memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
543 p->state = STATE_SETTING_UP;
544 pthread_cond_signal(&p->input_cond);
545 pthread_mutex_unlock(&p->mutex);
548 * If the client doesn't have a thread-safe get_buffer(),
549 * then decoding threads call back to the main thread,
550 * and it calls back to the client here.
553 FF_DISABLE_DEPRECATION_WARNINGS
554 if (!p->avctx->thread_safe_callbacks && (
555 p->avctx->get_format != avcodec_default_get_format ||
556 #if FF_API_GET_BUFFER
557 p->avctx->get_buffer ||
559 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
560 FF_ENABLE_DEPRECATION_WARNINGS
561 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
563 pthread_mutex_lock(&p->progress_mutex);
564 while (p->state == STATE_SETTING_UP)
565 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
568 case STATE_GET_BUFFER:
569 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
571 case STATE_GET_FORMAT:
572 p->result_format = p->avctx->get_format(p->avctx, p->available_formats);
579 p->state = STATE_SETTING_UP;
580 pthread_cond_signal(&p->progress_cond);
582 pthread_mutex_unlock(&p->progress_mutex);
586 fctx->prev_thread = p;
587 fctx->next_decoding++;
592 int ff_thread_decode_frame(AVCodecContext *avctx,
593 AVFrame *picture, int *got_picture_ptr,
596 FrameThreadContext *fctx = avctx->thread_opaque;
597 int finished = fctx->next_finished;
602 * Submit a packet to the next decoding thread.
605 p = &fctx->threads[fctx->next_decoding];
606 err = update_context_from_user(p->avctx, avctx);
608 err = submit_packet(p, avpkt);
612 * If we're still receiving the initial packets, don't return a frame.
615 if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
618 if (fctx->delaying) {
625 * Return the next available frame from the oldest thread.
626 * If we're at the end of the stream, then we have to skip threads that
627 * didn't output a frame, because we don't want to accidentally signal
628 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
632 p = &fctx->threads[finished++];
634 if (p->state != STATE_INPUT_READY) {
635 pthread_mutex_lock(&p->progress_mutex);
636 while (p->state != STATE_INPUT_READY)
637 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
638 pthread_mutex_unlock(&p->progress_mutex);
641 av_frame_move_ref(picture, &p->frame);
642 *got_picture_ptr = p->got_frame;
643 picture->pkt_dts = p->avpkt.dts;
646 * A later call with avkpt->size == 0 may loop over all threads,
647 * including this one, searching for a frame to return before being
648 * stopped by the "finished != fctx->next_finished" condition.
649 * Make sure we don't mistakenly return the same frame again.
653 if (finished >= avctx->thread_count) finished = 0;
654 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
656 update_context_from_thread(avctx, p->avctx, 1);
658 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
660 fctx->next_finished = finished;
662 /* return the size of the consumed packet if no error occurred */
663 return (p->result >= 0) ? avpkt->size : p->result;
666 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
669 volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
671 if (!progress || progress[field] >= n) return;
673 p = f->owner->thread_opaque;
675 if (f->owner->debug&FF_DEBUG_THREADS)
676 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
678 pthread_mutex_lock(&p->progress_mutex);
680 pthread_cond_broadcast(&p->progress_cond);
681 pthread_mutex_unlock(&p->progress_mutex);
684 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
687 volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
689 if (!progress || progress[field] >= n) return;
691 p = f->owner->thread_opaque;
693 if (f->owner->debug&FF_DEBUG_THREADS)
694 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
696 pthread_mutex_lock(&p->progress_mutex);
697 while (progress[field] < n)
698 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
699 pthread_mutex_unlock(&p->progress_mutex);
702 void ff_thread_finish_setup(AVCodecContext *avctx) {
703 PerThreadContext *p = avctx->thread_opaque;
705 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
707 if(p->state == STATE_SETUP_FINISHED){
708 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
711 pthread_mutex_lock(&p->progress_mutex);
712 p->state = STATE_SETUP_FINISHED;
713 pthread_cond_broadcast(&p->progress_cond);
714 pthread_mutex_unlock(&p->progress_mutex);
717 /// Waits for all threads to finish.
718 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
722 for (i = 0; i < thread_count; i++) {
723 PerThreadContext *p = &fctx->threads[i];
725 if (p->state != STATE_INPUT_READY) {
726 pthread_mutex_lock(&p->progress_mutex);
727 while (p->state != STATE_INPUT_READY)
728 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
729 pthread_mutex_unlock(&p->progress_mutex);
735 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
737 FrameThreadContext *fctx = avctx->thread_opaque;
738 const AVCodec *codec = avctx->codec;
741 park_frame_worker_threads(fctx, thread_count);
743 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
744 if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
745 av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
746 fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
747 fctx->threads->avctx->internal->is_copy = 1;
752 for (i = 0; i < thread_count; i++) {
753 PerThreadContext *p = &fctx->threads[i];
755 pthread_mutex_lock(&p->mutex);
756 pthread_cond_signal(&p->input_cond);
757 pthread_mutex_unlock(&p->mutex);
760 pthread_join(p->thread, NULL);
764 codec->close(p->avctx);
768 release_delayed_buffers(p);
769 av_frame_unref(&p->frame);
772 for (i = 0; i < thread_count; i++) {
773 PerThreadContext *p = &fctx->threads[i];
775 pthread_mutex_destroy(&p->mutex);
776 pthread_mutex_destroy(&p->progress_mutex);
777 pthread_cond_destroy(&p->input_cond);
778 pthread_cond_destroy(&p->progress_cond);
779 pthread_cond_destroy(&p->output_cond);
780 av_buffer_unref(&p->avpkt.buf);
782 av_freep(&p->released_buffers);
785 av_freep(&p->avctx->priv_data);
786 av_freep(&p->avctx->internal);
787 av_freep(&p->avctx->slice_offset);
793 av_freep(&fctx->threads);
794 pthread_mutex_destroy(&fctx->buffer_mutex);
795 av_freep(&avctx->thread_opaque);
798 static int frame_thread_init(AVCodecContext *avctx)
800 int thread_count = avctx->thread_count;
801 const AVCodec *codec = avctx->codec;
802 AVCodecContext *src = avctx;
803 FrameThreadContext *fctx;
807 int nb_cpus = av_cpu_count();
808 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
810 // use number of cores + 1 as thread count if there is more than one
812 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
814 thread_count = avctx->thread_count = 1;
817 if (thread_count <= 1) {
818 avctx->active_thread_type = 0;
822 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
824 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
825 pthread_mutex_init(&fctx->buffer_mutex, NULL);
828 for (i = 0; i < thread_count; i++) {
829 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
830 PerThreadContext *p = &fctx->threads[i];
832 pthread_mutex_init(&p->mutex, NULL);
833 pthread_mutex_init(&p->progress_mutex, NULL);
834 pthread_cond_init(&p->input_cond, NULL);
835 pthread_cond_init(&p->progress_cond, NULL);
836 pthread_cond_init(&p->output_cond, NULL);
842 err = AVERROR(ENOMEM);
847 copy->thread_opaque = p;
848 copy->pkt = &p->avpkt;
854 err = codec->init(copy);
856 update_context_from_thread(avctx, copy, 1);
858 copy->priv_data = av_malloc(codec->priv_data_size);
859 if (!copy->priv_data) {
860 err = AVERROR(ENOMEM);
863 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
864 copy->internal = av_malloc(sizeof(AVCodecInternal));
865 if (!copy->internal) {
866 err = AVERROR(ENOMEM);
869 *copy->internal = *src->internal;
870 copy->internal->is_copy = 1;
872 if (codec->init_thread_copy)
873 err = codec->init_thread_copy(copy);
878 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
879 p->thread_init= !err;
887 frame_thread_free(avctx, i+1);
892 void ff_thread_flush(AVCodecContext *avctx)
895 FrameThreadContext *fctx = avctx->thread_opaque;
897 if (!avctx->thread_opaque) return;
899 park_frame_worker_threads(fctx, avctx->thread_count);
900 if (fctx->prev_thread) {
901 if (fctx->prev_thread != &fctx->threads[0])
902 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
903 if (avctx->codec->flush)
904 avctx->codec->flush(fctx->threads[0].avctx);
907 fctx->next_decoding = fctx->next_finished = 0;
909 fctx->prev_thread = NULL;
910 for (i = 0; i < avctx->thread_count; i++) {
911 PerThreadContext *p = &fctx->threads[i];
912 // Make sure decode flush calls with size=0 won't return old frames
914 av_frame_unref(&p->frame);
916 release_delayed_buffers(p);
920 int ff_thread_can_start_frame(AVCodecContext *avctx)
922 PerThreadContext *p = avctx->thread_opaque;
923 if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
924 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
930 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
932 PerThreadContext *p = avctx->thread_opaque;
937 ff_init_buffer_info(avctx, f->f);
939 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
940 return ff_get_buffer(avctx, f->f, flags);
942 if (p->state != STATE_SETTING_UP &&
943 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
944 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
948 if (avctx->internal->allocate_progress) {
950 f->progress = av_buffer_alloc(2 * sizeof(int));
952 return AVERROR(ENOMEM);
954 progress = (int*)f->progress->data;
956 progress[0] = progress[1] = -1;
959 pthread_mutex_lock(&p->parent->buffer_mutex);
961 FF_DISABLE_DEPRECATION_WARNINGS
962 if (avctx->thread_safe_callbacks || (
963 #if FF_API_GET_BUFFER
964 !avctx->get_buffer &&
966 avctx->get_buffer2 == avcodec_default_get_buffer2)) {
967 FF_ENABLE_DEPRECATION_WARNINGS
968 err = ff_get_buffer(avctx, f->f, flags);
970 pthread_mutex_lock(&p->progress_mutex);
971 p->requested_frame = f->f;
972 p->requested_flags = flags;
973 p->state = STATE_GET_BUFFER;
974 pthread_cond_broadcast(&p->progress_cond);
976 while (p->state != STATE_SETTING_UP)
977 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
981 pthread_mutex_unlock(&p->progress_mutex);
984 if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
985 ff_thread_finish_setup(avctx);
988 av_buffer_unref(&f->progress);
990 pthread_mutex_unlock(&p->parent->buffer_mutex);
995 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
997 enum AVPixelFormat res;
998 PerThreadContext *p = avctx->thread_opaque;
999 if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
1000 avctx->get_format == avcodec_default_get_format)
1001 return avctx->get_format(avctx, fmt);
1002 if (p->state != STATE_SETTING_UP) {
1003 av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
1006 pthread_mutex_lock(&p->progress_mutex);
1007 p->available_formats = fmt;
1008 p->state = STATE_GET_FORMAT;
1009 pthread_cond_broadcast(&p->progress_cond);
1011 while (p->state != STATE_SETTING_UP)
1012 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
1014 res = p->result_format;
1016 pthread_mutex_unlock(&p->progress_mutex);
1021 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1023 int ret = thread_get_buffer_internal(avctx, f, flags);
1025 av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1029 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1031 PerThreadContext *p = avctx->thread_opaque;
1032 FrameThreadContext *fctx;
1034 FF_DISABLE_DEPRECATION_WARNINGS
1035 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1036 avctx->thread_safe_callbacks ||
1038 #if FF_API_GET_BUFFER
1039 !avctx->get_buffer &&
1041 avctx->get_buffer2 == avcodec_default_get_buffer2);
1042 FF_ENABLE_DEPRECATION_WARNINGS
1047 if (avctx->debug & FF_DEBUG_BUFFERS)
1048 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1050 av_buffer_unref(&f->progress);
1053 if (can_direct_free) {
1054 av_frame_unref(f->f);
1059 pthread_mutex_lock(&fctx->buffer_mutex);
1061 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
1063 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
1064 (p->num_released_buffers + 1) *
1065 sizeof(*p->released_buffers));
1068 p->released_buffers = tmp;
1070 dst = &p->released_buffers[p->num_released_buffers];
1071 av_frame_move_ref(dst, f->f);
1073 p->num_released_buffers++;
1076 pthread_mutex_unlock(&fctx->buffer_mutex);
1080 * Set the threading algorithms used.
1082 * Threading requires more than one thread.
1083 * Frame threading requires entire frames to be passed to the codec,
1084 * and introduces extra decoding delay, so is incompatible with low_delay.
1086 * @param avctx The context.
1088 static void validate_thread_parameters(AVCodecContext *avctx)
1090 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1091 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1092 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1093 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1094 if (avctx->thread_count == 1) {
1095 avctx->active_thread_type = 0;
1096 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1097 avctx->active_thread_type = FF_THREAD_FRAME;
1098 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1099 avctx->thread_type & FF_THREAD_SLICE) {
1100 avctx->active_thread_type = FF_THREAD_SLICE;
1101 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1102 avctx->thread_count = 1;
1103 avctx->active_thread_type = 0;
1106 if (avctx->thread_count > MAX_AUTO_THREADS)
1107 av_log(avctx, AV_LOG_WARNING,
1108 "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1109 avctx->thread_count, MAX_AUTO_THREADS);
1112 int ff_thread_init(AVCodecContext *avctx)
1118 validate_thread_parameters(avctx);
1120 if (avctx->active_thread_type&FF_THREAD_SLICE)
1121 return thread_init_internal(avctx);
1122 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1123 return frame_thread_init(avctx);
1128 void ff_thread_free(AVCodecContext *avctx)
1130 if (avctx->active_thread_type&FF_THREAD_FRAME)
1131 frame_thread_free(avctx, avctx->thread_count);
1136 void ff_thread_report_progress2(AVCodecContext *avctx, int field, int thread, int n)
1138 ThreadContext *p = avctx->thread_opaque;
1139 int *entries = p->entries;
1141 pthread_mutex_lock(&p->progress_mutex[thread]);
1143 pthread_cond_signal(&p->progress_cond[thread]);
1144 pthread_mutex_unlock(&p->progress_mutex[thread]);
1147 void ff_thread_await_progress2(AVCodecContext *avctx, int field, int thread, int shift)
1149 ThreadContext *p = avctx->thread_opaque;
1150 int *entries = p->entries;
1152 if (!entries || !field) return;
1154 thread = thread ? thread - 1 : p->thread_count - 1;
1156 pthread_mutex_lock(&p->progress_mutex[thread]);
1157 while ((entries[field - 1] - entries[field]) < shift){
1158 pthread_cond_wait(&p->progress_cond[thread], &p->progress_mutex[thread]);
1160 pthread_mutex_unlock(&p->progress_mutex[thread]);
1163 int ff_alloc_entries(AVCodecContext *avctx, int count)
1167 if (avctx->active_thread_type & FF_THREAD_SLICE) {
1168 ThreadContext *p = avctx->thread_opaque;
1169 p->thread_count = avctx->thread_count;
1170 p->entries = av_mallocz(count * sizeof(int));
1173 return AVERROR(ENOMEM);
1176 p->entries_count = count;
1177 p->progress_mutex = av_malloc(p->thread_count * sizeof(pthread_mutex_t));
1178 p->progress_cond = av_malloc(p->thread_count * sizeof(pthread_cond_t));
1180 for (i = 0; i < p->thread_count; i++) {
1181 pthread_mutex_init(&p->progress_mutex[i], NULL);
1182 pthread_cond_init(&p->progress_cond[i], NULL);
1189 void ff_reset_entries(AVCodecContext *avctx)
1191 ThreadContext *p = avctx->thread_opaque;
1192 memset(p->entries, 0, p->entries_count * sizeof(int));