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
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"
48 typedef int (action_func)(AVCodecContext *c, void *arg);
49 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
51 typedef struct ThreadContext {
61 pthread_cond_t last_job_cond;
62 pthread_cond_t current_job_cond;
63 pthread_mutex_t current_job_lock;
64 unsigned current_execute;
70 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
72 typedef struct PerThreadContext {
73 struct FrameThreadContext *parent;
77 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
78 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
79 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
81 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
82 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
84 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
86 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
87 uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
88 int allocated_buf_size; ///< Size allocated for buf
90 AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
91 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
92 int result; ///< The result of the last codec decode/encode() call.
95 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
96 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
97 STATE_GET_BUFFER, /**<
98 * Set when the codec calls get_buffer().
99 * State is returned to STATE_SETTING_UP afterwards.
101 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
105 * Array of frames passed to ff_thread_release_buffer().
106 * Frames are released after all threads referencing them are finished.
108 AVFrame *released_buffers;
109 int num_released_buffers;
110 int released_buffers_allocated;
112 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
113 int requested_flags; ///< flags passed to get_buffer() for requested_frame
117 * Context stored in the client AVCodecContext thread_opaque.
119 typedef struct FrameThreadContext {
120 PerThreadContext *threads; ///< The contexts for each thread.
121 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
123 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
125 int next_decoding; ///< The next context to submit a packet to.
126 int next_finished; ///< The next context to return output from.
129 * Set for the first N packets, where N is the number of threads.
130 * While it is set, ff_thread_en/decode_frame won't return any results.
133 int die; ///< Set when threads should exit.
134 } FrameThreadContext;
137 /* H264 slice threading seems to be buggy with more than 16 threads,
138 * limit the number of threads to 16 for automatic detection */
139 #define MAX_AUTO_THREADS 16
141 static void* attribute_align_arg worker(void *v)
143 AVCodecContext *avctx = v;
144 ThreadContext *c = avctx->thread_opaque;
145 unsigned last_execute = 0;
146 int our_job = c->job_count;
147 int thread_count = avctx->thread_count;
150 pthread_mutex_lock(&c->current_job_lock);
151 self_id = c->current_job++;
153 while (our_job >= c->job_count) {
154 if (c->current_job == thread_count + c->job_count)
155 pthread_cond_signal(&c->last_job_cond);
157 while (last_execute == c->current_execute && !c->done)
158 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
159 last_execute = c->current_execute;
163 pthread_mutex_unlock(&c->current_job_lock);
167 pthread_mutex_unlock(&c->current_job_lock);
169 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
170 c->func2(avctx, c->args, our_job, self_id);
172 pthread_mutex_lock(&c->current_job_lock);
173 our_job = c->current_job++;
177 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
179 while (c->current_job != thread_count + c->job_count)
180 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
181 pthread_mutex_unlock(&c->current_job_lock);
184 static void thread_free(AVCodecContext *avctx)
186 ThreadContext *c = avctx->thread_opaque;
189 pthread_mutex_lock(&c->current_job_lock);
191 pthread_cond_broadcast(&c->current_job_cond);
192 pthread_mutex_unlock(&c->current_job_lock);
194 for (i=0; i<avctx->thread_count; i++)
195 pthread_join(c->workers[i], NULL);
197 pthread_mutex_destroy(&c->current_job_lock);
198 pthread_cond_destroy(&c->current_job_cond);
199 pthread_cond_destroy(&c->last_job_cond);
201 av_freep(&avctx->thread_opaque);
204 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
206 ThreadContext *c= avctx->thread_opaque;
209 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
210 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
215 pthread_mutex_lock(&c->current_job_lock);
217 c->current_job = avctx->thread_count;
218 c->job_count = job_count;
219 c->job_size = job_size;
224 c->rets_count = job_count;
226 c->rets = &dummy_ret;
229 c->current_execute++;
230 pthread_cond_broadcast(&c->current_job_cond);
232 avcodec_thread_park_workers(c, avctx->thread_count);
237 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
239 ThreadContext *c= avctx->thread_opaque;
241 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
244 static int thread_init_internal(AVCodecContext *avctx)
248 int thread_count = avctx->thread_count;
251 int nb_cpus = av_cpu_count();
252 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
253 // use number of cores + 1 as thread count if there is more than one
255 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
257 thread_count = avctx->thread_count = 1;
260 if (thread_count <= 1) {
261 avctx->active_thread_type = 0;
265 c = av_mallocz(sizeof(ThreadContext));
269 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
275 avctx->thread_opaque = c;
280 pthread_cond_init(&c->current_job_cond, NULL);
281 pthread_cond_init(&c->last_job_cond, NULL);
282 pthread_mutex_init(&c->current_job_lock, NULL);
283 pthread_mutex_lock(&c->current_job_lock);
284 for (i=0; i<thread_count; i++) {
285 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
286 avctx->thread_count = i;
287 pthread_mutex_unlock(&c->current_job_lock);
288 ff_thread_free(avctx);
293 avcodec_thread_park_workers(c, thread_count);
295 avctx->execute = avcodec_thread_execute;
296 avctx->execute2 = avcodec_thread_execute2;
301 * Codec worker thread.
303 * Automatically calls ff_thread_finish_setup() if the codec does
304 * not provide an update_thread_context method, or if the codec returns
307 static attribute_align_arg void *frame_worker_thread(void *arg)
309 PerThreadContext *p = arg;
310 FrameThreadContext *fctx = p->parent;
311 AVCodecContext *avctx = p->avctx;
312 const AVCodec *codec = avctx->codec;
315 if (p->state == STATE_INPUT_READY && !fctx->die) {
316 pthread_mutex_lock(&p->mutex);
317 while (p->state == STATE_INPUT_READY && !fctx->die)
318 pthread_cond_wait(&p->input_cond, &p->mutex);
319 pthread_mutex_unlock(&p->mutex);
322 if (fctx->die) break;
324 if (!codec->update_thread_context && avctx->thread_safe_callbacks)
325 ff_thread_finish_setup(avctx);
327 pthread_mutex_lock(&p->mutex);
328 avcodec_get_frame_defaults(&p->frame);
330 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
332 /* many decoders assign whole AVFrames, thus overwriting extended_data;
333 * make sure it's set correctly */
334 p->frame.extended_data = p->frame.data;
336 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
338 p->state = STATE_INPUT_READY;
340 pthread_mutex_lock(&p->progress_mutex);
341 pthread_cond_signal(&p->output_cond);
342 pthread_mutex_unlock(&p->progress_mutex);
344 pthread_mutex_unlock(&p->mutex);
351 * Update the next thread's AVCodecContext with values from the reference thread's context.
353 * @param dst The destination context.
354 * @param src The source context.
355 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
357 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
362 dst->time_base = src->time_base;
363 dst->width = src->width;
364 dst->height = src->height;
365 dst->pix_fmt = src->pix_fmt;
367 dst->coded_width = src->coded_width;
368 dst->coded_height = src->coded_height;
370 dst->has_b_frames = src->has_b_frames;
371 dst->idct_algo = src->idct_algo;
373 dst->bits_per_coded_sample = src->bits_per_coded_sample;
374 dst->sample_aspect_ratio = src->sample_aspect_ratio;
375 dst->dtg_active_format = src->dtg_active_format;
377 dst->profile = src->profile;
378 dst->level = src->level;
380 dst->bits_per_raw_sample = src->bits_per_raw_sample;
381 dst->ticks_per_frame = src->ticks_per_frame;
382 dst->color_primaries = src->color_primaries;
384 dst->color_trc = src->color_trc;
385 dst->colorspace = src->colorspace;
386 dst->color_range = src->color_range;
387 dst->chroma_sample_location = src->chroma_sample_location;
389 dst->hwaccel = src->hwaccel;
390 dst->hwaccel_context = src->hwaccel_context;
394 dst->coded_frame = src->coded_frame;
396 if (dst->codec->update_thread_context)
397 err = dst->codec->update_thread_context(dst, src);
404 * Update the next thread's AVCodecContext with values set by the user.
406 * @param dst The destination context.
407 * @param src The source context.
408 * @return 0 on success, negative error code on failure
410 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
412 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
413 dst->flags = src->flags;
415 dst->draw_horiz_band= src->draw_horiz_band;
416 dst->get_buffer2 = src->get_buffer2;
417 #if FF_API_GET_BUFFER
418 FF_DISABLE_DEPRECATION_WARNINGS
419 dst->get_buffer = src->get_buffer;
420 dst->release_buffer = src->release_buffer;
421 FF_ENABLE_DEPRECATION_WARNINGS
424 dst->opaque = src->opaque;
425 dst->debug = src->debug;
426 dst->debug_mv = src->debug_mv;
428 dst->slice_flags = src->slice_flags;
429 dst->flags2 = src->flags2;
431 copy_fields(skip_loop_filter, subtitle_header);
433 dst->frame_number = src->frame_number;
434 dst->reordered_opaque = src->reordered_opaque;
436 if (src->slice_count && src->slice_offset) {
437 if (dst->slice_count < src->slice_count) {
438 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
439 sizeof(*dst->slice_offset));
441 av_free(dst->slice_offset);
442 return AVERROR(ENOMEM);
444 dst->slice_offset = tmp;
446 memcpy(dst->slice_offset, src->slice_offset,
447 src->slice_count * sizeof(*dst->slice_offset));
449 dst->slice_count = src->slice_count;
454 /// Releases the buffers that this decoding thread was the last user of.
455 static void release_delayed_buffers(PerThreadContext *p)
457 FrameThreadContext *fctx = p->parent;
459 while (p->num_released_buffers > 0) {
462 pthread_mutex_lock(&fctx->buffer_mutex);
464 // fix extended data in case the caller screwed it up
465 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
466 f = &p->released_buffers[--p->num_released_buffers];
467 f->extended_data = f->data;
470 pthread_mutex_unlock(&fctx->buffer_mutex);
474 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
476 FrameThreadContext *fctx = p->parent;
477 PerThreadContext *prev_thread = fctx->prev_thread;
478 const AVCodec *codec = p->avctx->codec;
480 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
482 pthread_mutex_lock(&p->mutex);
484 release_delayed_buffers(p);
488 if (prev_thread->state == STATE_SETTING_UP) {
489 pthread_mutex_lock(&prev_thread->progress_mutex);
490 while (prev_thread->state == STATE_SETTING_UP)
491 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
492 pthread_mutex_unlock(&prev_thread->progress_mutex);
495 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
497 pthread_mutex_unlock(&p->mutex);
502 av_buffer_unref(&p->avpkt.buf);
505 p->avpkt.buf = av_buffer_ref(avpkt->buf);
507 av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
508 p->avpkt.data = p->buf;
509 memcpy(p->buf, avpkt->data, avpkt->size);
510 memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
513 p->state = STATE_SETTING_UP;
514 pthread_cond_signal(&p->input_cond);
515 pthread_mutex_unlock(&p->mutex);
518 * If the client doesn't have a thread-safe get_buffer(),
519 * then decoding threads call back to the main thread,
520 * and it calls back to the client here.
523 FF_DISABLE_DEPRECATION_WARNINGS
524 if (!p->avctx->thread_safe_callbacks && (
525 #if FF_API_GET_BUFFER
526 p->avctx->get_buffer ||
528 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
529 FF_ENABLE_DEPRECATION_WARNINGS
530 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
531 pthread_mutex_lock(&p->progress_mutex);
532 while (p->state == STATE_SETTING_UP)
533 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
535 if (p->state == STATE_GET_BUFFER) {
536 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
537 p->state = STATE_SETTING_UP;
538 pthread_cond_signal(&p->progress_cond);
540 pthread_mutex_unlock(&p->progress_mutex);
544 fctx->prev_thread = p;
545 fctx->next_decoding++;
550 int ff_thread_decode_frame(AVCodecContext *avctx,
551 AVFrame *picture, int *got_picture_ptr,
554 FrameThreadContext *fctx = avctx->thread_opaque;
555 int finished = fctx->next_finished;
560 * Submit a packet to the next decoding thread.
563 p = &fctx->threads[fctx->next_decoding];
564 err = update_context_from_user(p->avctx, avctx);
566 err = submit_packet(p, avpkt);
570 * If we're still receiving the initial packets, don't return a frame.
573 if (fctx->delaying) {
574 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
582 * Return the next available frame from the oldest thread.
583 * If we're at the end of the stream, then we have to skip threads that
584 * didn't output a frame, because we don't want to accidentally signal
585 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
589 p = &fctx->threads[finished++];
591 if (p->state != STATE_INPUT_READY) {
592 pthread_mutex_lock(&p->progress_mutex);
593 while (p->state != STATE_INPUT_READY)
594 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
595 pthread_mutex_unlock(&p->progress_mutex);
598 av_frame_move_ref(picture, &p->frame);
599 *got_picture_ptr = p->got_frame;
600 picture->pkt_dts = p->avpkt.dts;
603 * A later call with avkpt->size == 0 may loop over all threads,
604 * including this one, searching for a frame to return before being
605 * stopped by the "finished != fctx->next_finished" condition.
606 * Make sure we don't mistakenly return the same frame again.
610 if (finished >= avctx->thread_count) finished = 0;
611 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
613 update_context_from_thread(avctx, p->avctx, 1);
615 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
617 fctx->next_finished = finished;
619 /* return the size of the consumed packet if no error occurred */
620 return (p->result >= 0) ? avpkt->size : p->result;
623 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
626 int *progress = f->progress ? (int*)f->progress->data : NULL;
628 if (!progress || progress[field] >= n) return;
630 p = f->owner->thread_opaque;
632 if (f->owner->debug&FF_DEBUG_THREADS)
633 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
635 pthread_mutex_lock(&p->progress_mutex);
637 pthread_cond_broadcast(&p->progress_cond);
638 pthread_mutex_unlock(&p->progress_mutex);
641 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
644 int *progress = f->progress ? (int*)f->progress->data : NULL;
646 if (!progress || progress[field] >= n) return;
648 p = f->owner->thread_opaque;
650 if (f->owner->debug&FF_DEBUG_THREADS)
651 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
653 pthread_mutex_lock(&p->progress_mutex);
654 while (progress[field] < n)
655 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
656 pthread_mutex_unlock(&p->progress_mutex);
659 void ff_thread_finish_setup(AVCodecContext *avctx) {
660 PerThreadContext *p = avctx->thread_opaque;
662 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
664 pthread_mutex_lock(&p->progress_mutex);
665 p->state = STATE_SETUP_FINISHED;
666 pthread_cond_broadcast(&p->progress_cond);
667 pthread_mutex_unlock(&p->progress_mutex);
670 /// Waits for all threads to finish.
671 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
675 for (i = 0; i < thread_count; i++) {
676 PerThreadContext *p = &fctx->threads[i];
678 if (p->state != STATE_INPUT_READY) {
679 pthread_mutex_lock(&p->progress_mutex);
680 while (p->state != STATE_INPUT_READY)
681 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
682 pthread_mutex_unlock(&p->progress_mutex);
687 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
689 FrameThreadContext *fctx = avctx->thread_opaque;
690 const AVCodec *codec = avctx->codec;
693 park_frame_worker_threads(fctx, thread_count);
695 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
696 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
700 for (i = 0; i < thread_count; i++) {
701 PerThreadContext *p = &fctx->threads[i];
703 pthread_mutex_lock(&p->mutex);
704 pthread_cond_signal(&p->input_cond);
705 pthread_mutex_unlock(&p->mutex);
708 pthread_join(p->thread, NULL);
711 codec->close(p->avctx);
715 release_delayed_buffers(p);
716 av_frame_unref(&p->frame);
719 for (i = 0; i < thread_count; i++) {
720 PerThreadContext *p = &fctx->threads[i];
722 pthread_mutex_destroy(&p->mutex);
723 pthread_mutex_destroy(&p->progress_mutex);
724 pthread_cond_destroy(&p->input_cond);
725 pthread_cond_destroy(&p->progress_cond);
726 pthread_cond_destroy(&p->output_cond);
727 av_buffer_unref(&p->avpkt.buf);
729 av_freep(&p->released_buffers);
732 av_freep(&p->avctx->priv_data);
733 av_freep(&p->avctx->internal);
734 av_freep(&p->avctx->slice_offset);
740 av_freep(&fctx->threads);
741 pthread_mutex_destroy(&fctx->buffer_mutex);
742 av_freep(&avctx->thread_opaque);
745 static int frame_thread_init(AVCodecContext *avctx)
747 int thread_count = avctx->thread_count;
748 const AVCodec *codec = avctx->codec;
749 AVCodecContext *src = avctx;
750 FrameThreadContext *fctx;
754 int nb_cpus = av_cpu_count();
755 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
756 // use number of cores + 1 as thread count if there is more than one
758 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
760 thread_count = avctx->thread_count = 1;
763 if (thread_count <= 1) {
764 avctx->active_thread_type = 0;
768 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
770 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
771 pthread_mutex_init(&fctx->buffer_mutex, NULL);
774 for (i = 0; i < thread_count; i++) {
775 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
776 PerThreadContext *p = &fctx->threads[i];
778 pthread_mutex_init(&p->mutex, NULL);
779 pthread_mutex_init(&p->progress_mutex, NULL);
780 pthread_cond_init(&p->input_cond, NULL);
781 pthread_cond_init(&p->progress_cond, NULL);
782 pthread_cond_init(&p->output_cond, NULL);
788 err = AVERROR(ENOMEM);
793 copy->thread_opaque = p;
794 copy->pkt = &p->avpkt;
800 err = codec->init(copy);
802 update_context_from_thread(avctx, copy, 1);
804 copy->priv_data = av_malloc(codec->priv_data_size);
805 if (!copy->priv_data) {
806 err = AVERROR(ENOMEM);
809 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
810 copy->internal = av_malloc(sizeof(AVCodecInternal));
811 if (!copy->internal) {
812 err = AVERROR(ENOMEM);
815 *copy->internal = *src->internal;
816 copy->internal->is_copy = 1;
818 if (codec->init_thread_copy)
819 err = codec->init_thread_copy(copy);
824 if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
831 frame_thread_free(avctx, i+1);
836 void ff_thread_flush(AVCodecContext *avctx)
839 FrameThreadContext *fctx = avctx->thread_opaque;
841 if (!avctx->thread_opaque) return;
843 park_frame_worker_threads(fctx, avctx->thread_count);
844 if (fctx->prev_thread) {
845 if (fctx->prev_thread != &fctx->threads[0])
846 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
847 if (avctx->codec->flush)
848 avctx->codec->flush(fctx->threads[0].avctx);
851 fctx->next_decoding = fctx->next_finished = 0;
853 fctx->prev_thread = NULL;
854 for (i = 0; i < avctx->thread_count; i++) {
855 PerThreadContext *p = &fctx->threads[i];
856 // Make sure decode flush calls with size=0 won't return old frames
858 av_frame_unref(&p->frame);
860 release_delayed_buffers(p);
864 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
866 PerThreadContext *p = avctx->thread_opaque;
871 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
872 return ff_get_buffer(avctx, f->f, flags);
874 if (p->state != STATE_SETTING_UP &&
875 (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
876 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
880 if (avctx->internal->allocate_progress) {
882 f->progress = av_buffer_alloc(2 * sizeof(int));
884 return AVERROR(ENOMEM);
886 progress = (int*)f->progress->data;
888 progress[0] = progress[1] = -1;
891 pthread_mutex_lock(&p->parent->buffer_mutex);
892 FF_DISABLE_DEPRECATION_WARNINGS
893 if (avctx->thread_safe_callbacks || (
894 #if FF_API_GET_BUFFER
895 !avctx->get_buffer &&
897 avctx->get_buffer2 == avcodec_default_get_buffer2)) {
898 FF_ENABLE_DEPRECATION_WARNINGS
899 err = ff_get_buffer(avctx, f->f, flags);
901 p->requested_frame = f->f;
902 p->requested_flags = flags;
903 p->state = STATE_GET_BUFFER;
904 pthread_mutex_lock(&p->progress_mutex);
905 pthread_cond_signal(&p->progress_cond);
907 while (p->state != STATE_SETTING_UP)
908 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
912 pthread_mutex_unlock(&p->progress_mutex);
915 if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
916 ff_thread_finish_setup(avctx);
919 av_buffer_unref(&f->progress);
921 pthread_mutex_unlock(&p->parent->buffer_mutex);
926 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
928 PerThreadContext *p = avctx->thread_opaque;
929 FrameThreadContext *fctx;
931 FF_DISABLE_DEPRECATION_WARNINGS
932 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
933 avctx->thread_safe_callbacks ||
935 #if FF_API_GET_BUFFER
936 !avctx->get_buffer &&
938 avctx->get_buffer2 == avcodec_default_get_buffer2);
939 FF_ENABLE_DEPRECATION_WARNINGS
944 if (avctx->debug & FF_DEBUG_BUFFERS)
945 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
947 av_buffer_unref(&f->progress);
950 if (can_direct_free) {
951 av_frame_unref(f->f);
956 pthread_mutex_lock(&fctx->buffer_mutex);
958 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
960 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
961 (p->num_released_buffers + 1) *
962 sizeof(*p->released_buffers));
965 p->released_buffers = tmp;
967 dst = &p->released_buffers[p->num_released_buffers];
968 av_frame_move_ref(dst, f->f);
970 p->num_released_buffers++;
973 pthread_mutex_unlock(&fctx->buffer_mutex);
977 * Set the threading algorithms used.
979 * Threading requires more than one thread.
980 * Frame threading requires entire frames to be passed to the codec,
981 * and introduces extra decoding delay, so is incompatible with low_delay.
983 * @param avctx The context.
985 static void validate_thread_parameters(AVCodecContext *avctx)
987 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
988 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
989 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
990 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
991 if (avctx->thread_count == 1) {
992 avctx->active_thread_type = 0;
993 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
994 avctx->active_thread_type = FF_THREAD_FRAME;
995 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
996 avctx->thread_type & FF_THREAD_SLICE) {
997 avctx->active_thread_type = FF_THREAD_SLICE;
998 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
999 avctx->thread_count = 1;
1000 avctx->active_thread_type = 0;
1003 if (avctx->thread_count > MAX_AUTO_THREADS)
1004 av_log(avctx, AV_LOG_WARNING,
1005 "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1006 avctx->thread_count, MAX_AUTO_THREADS);
1009 int ff_thread_init(AVCodecContext *avctx)
1015 validate_thread_parameters(avctx);
1017 if (avctx->active_thread_type&FF_THREAD_SLICE)
1018 return thread_init_internal(avctx);
1019 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1020 return frame_thread_init(avctx);
1025 void ff_thread_free(AVCodecContext *avctx)
1027 if (avctx->active_thread_type&FF_THREAD_FRAME)
1028 frame_thread_free(avctx, avctx->thread_count);