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;
69 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
71 typedef struct PerThreadContext {
72 struct FrameThreadContext *parent;
76 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
77 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
78 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
80 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
81 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
83 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
85 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
86 uint8_t *buf; ///< backup storage for packet data when the input packet is not refcounted
87 int allocated_buf_size; ///< Size allocated for buf
89 AVFrame frame; ///< Output frame (for decoding) or input (for encoding).
90 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
91 int result; ///< The result of the last codec decode/encode() call.
94 STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
95 STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
96 STATE_GET_BUFFER, /**<
97 * Set when the codec calls get_buffer().
98 * State is returned to STATE_SETTING_UP afterwards.
100 STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
104 * Array of frames passed to ff_thread_release_buffer().
105 * Frames are released after all threads referencing them are finished.
107 AVFrame *released_buffers;
108 int num_released_buffers;
109 int released_buffers_allocated;
111 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
112 int requested_flags; ///< flags passed to get_buffer() for requested_frame
116 * Context stored in the client AVCodecContext thread_opaque.
118 typedef struct FrameThreadContext {
119 PerThreadContext *threads; ///< The contexts for each thread.
120 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
122 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
124 int next_decoding; ///< The next context to submit a packet to.
125 int next_finished; ///< The next context to return output from.
128 * Set for the first N packets, where N is the number of threads.
129 * While it is set, ff_thread_en/decode_frame won't return any results.
132 int die; ///< Set when threads should exit.
133 } FrameThreadContext;
136 /* H264 slice threading seems to be buggy with more than 16 threads,
137 * limit the number of threads to 16 for automatic detection */
138 #define MAX_AUTO_THREADS 16
140 static void* attribute_align_arg worker(void *v)
142 AVCodecContext *avctx = v;
143 ThreadContext *c = avctx->thread_opaque;
144 int our_job = c->job_count;
145 int thread_count = avctx->thread_count;
148 pthread_mutex_lock(&c->current_job_lock);
149 self_id = c->current_job++;
151 while (our_job >= c->job_count) {
152 if (c->current_job == thread_count + c->job_count)
153 pthread_cond_signal(&c->last_job_cond);
155 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
159 pthread_mutex_unlock(&c->current_job_lock);
163 pthread_mutex_unlock(&c->current_job_lock);
165 c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
166 c->func2(avctx, c->args, our_job, self_id);
168 pthread_mutex_lock(&c->current_job_lock);
169 our_job = c->current_job++;
173 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
175 pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
176 pthread_mutex_unlock(&c->current_job_lock);
179 static void thread_free(AVCodecContext *avctx)
181 ThreadContext *c = avctx->thread_opaque;
184 pthread_mutex_lock(&c->current_job_lock);
186 pthread_cond_broadcast(&c->current_job_cond);
187 pthread_mutex_unlock(&c->current_job_lock);
189 for (i=0; i<avctx->thread_count; i++)
190 pthread_join(c->workers[i], NULL);
192 pthread_mutex_destroy(&c->current_job_lock);
193 pthread_cond_destroy(&c->current_job_cond);
194 pthread_cond_destroy(&c->last_job_cond);
196 av_freep(&avctx->thread_opaque);
199 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
201 ThreadContext *c= avctx->thread_opaque;
204 if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
205 return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
210 pthread_mutex_lock(&c->current_job_lock);
212 c->current_job = avctx->thread_count;
213 c->job_count = job_count;
214 c->job_size = job_size;
219 c->rets_count = job_count;
221 c->rets = &dummy_ret;
224 pthread_cond_broadcast(&c->current_job_cond);
226 avcodec_thread_park_workers(c, avctx->thread_count);
231 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
233 ThreadContext *c= avctx->thread_opaque;
235 return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
238 static int thread_init_internal(AVCodecContext *avctx)
242 int thread_count = avctx->thread_count;
245 int nb_cpus = av_cpu_count();
246 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
247 // use number of cores + 1 as thread count if there is more than one
249 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
251 thread_count = avctx->thread_count = 1;
254 if (thread_count <= 1) {
255 avctx->active_thread_type = 0;
259 c = av_mallocz(sizeof(ThreadContext));
263 c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
269 avctx->thread_opaque = c;
274 pthread_cond_init(&c->current_job_cond, NULL);
275 pthread_cond_init(&c->last_job_cond, NULL);
276 pthread_mutex_init(&c->current_job_lock, NULL);
277 pthread_mutex_lock(&c->current_job_lock);
278 for (i=0; i<thread_count; i++) {
279 if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
280 avctx->thread_count = i;
281 pthread_mutex_unlock(&c->current_job_lock);
282 ff_thread_free(avctx);
287 avcodec_thread_park_workers(c, thread_count);
289 avctx->execute = avcodec_thread_execute;
290 avctx->execute2 = avcodec_thread_execute2;
295 * Codec worker thread.
297 * Automatically calls ff_thread_finish_setup() if the codec does
298 * not provide an update_thread_context method, or if the codec returns
301 static attribute_align_arg void *frame_worker_thread(void *arg)
303 PerThreadContext *p = arg;
304 FrameThreadContext *fctx = p->parent;
305 AVCodecContext *avctx = p->avctx;
306 const AVCodec *codec = avctx->codec;
309 if (p->state == STATE_INPUT_READY && !fctx->die) {
310 pthread_mutex_lock(&p->mutex);
311 while (p->state == STATE_INPUT_READY && !fctx->die)
312 pthread_cond_wait(&p->input_cond, &p->mutex);
313 pthread_mutex_unlock(&p->mutex);
316 if (fctx->die) break;
318 if (!codec->update_thread_context && avctx->thread_safe_callbacks)
319 ff_thread_finish_setup(avctx);
321 pthread_mutex_lock(&p->mutex);
322 avcodec_get_frame_defaults(&p->frame);
324 p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
326 /* many decoders assign whole AVFrames, thus overwriting extended_data;
327 * make sure it's set correctly */
328 p->frame.extended_data = p->frame.data;
330 if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
332 p->state = STATE_INPUT_READY;
334 pthread_mutex_lock(&p->progress_mutex);
335 pthread_cond_signal(&p->output_cond);
336 pthread_mutex_unlock(&p->progress_mutex);
338 pthread_mutex_unlock(&p->mutex);
345 * Update the next thread's AVCodecContext with values from the reference thread's context.
347 * @param dst The destination context.
348 * @param src The source context.
349 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
351 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
356 dst->time_base = src->time_base;
357 dst->width = src->width;
358 dst->height = src->height;
359 dst->pix_fmt = src->pix_fmt;
361 dst->coded_width = src->coded_width;
362 dst->coded_height = src->coded_height;
364 dst->has_b_frames = src->has_b_frames;
365 dst->idct_algo = src->idct_algo;
367 dst->bits_per_coded_sample = src->bits_per_coded_sample;
368 dst->sample_aspect_ratio = src->sample_aspect_ratio;
369 dst->dtg_active_format = src->dtg_active_format;
371 dst->profile = src->profile;
372 dst->level = src->level;
374 dst->bits_per_raw_sample = src->bits_per_raw_sample;
375 dst->ticks_per_frame = src->ticks_per_frame;
376 dst->color_primaries = src->color_primaries;
378 dst->color_trc = src->color_trc;
379 dst->colorspace = src->colorspace;
380 dst->color_range = src->color_range;
381 dst->chroma_sample_location = src->chroma_sample_location;
383 dst->hwaccel = src->hwaccel;
384 dst->hwaccel_context = src->hwaccel_context;
388 dst->coded_frame = src->coded_frame;
390 if (dst->codec->update_thread_context)
391 err = dst->codec->update_thread_context(dst, src);
398 * Update the next thread's AVCodecContext with values set by the user.
400 * @param dst The destination context.
401 * @param src The source context.
402 * @return 0 on success, negative error code on failure
404 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
406 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
407 dst->flags = src->flags;
409 dst->draw_horiz_band= src->draw_horiz_band;
410 dst->get_buffer2 = src->get_buffer2;
411 #if FF_API_GET_BUFFER
412 FF_DISABLE_DEPRECATION_WARNINGS
413 dst->get_buffer = src->get_buffer;
414 dst->release_buffer = src->release_buffer;
415 FF_ENABLE_DEPRECATION_WARNINGS
418 dst->opaque = src->opaque;
419 dst->debug = src->debug;
420 dst->debug_mv = src->debug_mv;
422 dst->slice_flags = src->slice_flags;
423 dst->flags2 = src->flags2;
425 copy_fields(skip_loop_filter, subtitle_header);
427 dst->frame_number = src->frame_number;
428 dst->reordered_opaque = src->reordered_opaque;
430 if (src->slice_count && src->slice_offset) {
431 if (dst->slice_count < src->slice_count) {
432 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
433 sizeof(*dst->slice_offset));
435 av_free(dst->slice_offset);
436 return AVERROR(ENOMEM);
438 dst->slice_offset = tmp;
440 memcpy(dst->slice_offset, src->slice_offset,
441 src->slice_count * sizeof(*dst->slice_offset));
443 dst->slice_count = src->slice_count;
448 /// Releases the buffers that this decoding thread was the last user of.
449 static void release_delayed_buffers(PerThreadContext *p)
451 FrameThreadContext *fctx = p->parent;
453 while (p->num_released_buffers > 0) {
456 pthread_mutex_lock(&fctx->buffer_mutex);
458 // fix extended data in case the caller screwed it up
459 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
460 f = &p->released_buffers[--p->num_released_buffers];
461 f->extended_data = f->data;
464 pthread_mutex_unlock(&fctx->buffer_mutex);
468 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
470 FrameThreadContext *fctx = p->parent;
471 PerThreadContext *prev_thread = fctx->prev_thread;
472 const AVCodec *codec = p->avctx->codec;
474 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
476 pthread_mutex_lock(&p->mutex);
478 release_delayed_buffers(p);
482 if (prev_thread->state == STATE_SETTING_UP) {
483 pthread_mutex_lock(&prev_thread->progress_mutex);
484 while (prev_thread->state == STATE_SETTING_UP)
485 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
486 pthread_mutex_unlock(&prev_thread->progress_mutex);
489 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
491 pthread_mutex_unlock(&p->mutex);
496 av_buffer_unref(&p->avpkt.buf);
499 p->avpkt.buf = av_buffer_ref(avpkt->buf);
501 av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
502 p->avpkt.data = p->buf;
503 memcpy(p->buf, avpkt->data, avpkt->size);
504 memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
507 p->state = STATE_SETTING_UP;
508 pthread_cond_signal(&p->input_cond);
509 pthread_mutex_unlock(&p->mutex);
512 * If the client doesn't have a thread-safe get_buffer(),
513 * then decoding threads call back to the main thread,
514 * and it calls back to the client here.
517 FF_DISABLE_DEPRECATION_WARNINGS
518 if (!p->avctx->thread_safe_callbacks && (
519 #if FF_API_GET_BUFFER
520 p->avctx->get_buffer ||
522 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
523 FF_ENABLE_DEPRECATION_WARNINGS
524 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
525 pthread_mutex_lock(&p->progress_mutex);
526 while (p->state == STATE_SETTING_UP)
527 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
529 if (p->state == STATE_GET_BUFFER) {
530 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
531 p->state = STATE_SETTING_UP;
532 pthread_cond_signal(&p->progress_cond);
534 pthread_mutex_unlock(&p->progress_mutex);
538 fctx->prev_thread = p;
539 fctx->next_decoding++;
544 int ff_thread_decode_frame(AVCodecContext *avctx,
545 AVFrame *picture, int *got_picture_ptr,
548 FrameThreadContext *fctx = avctx->thread_opaque;
549 int finished = fctx->next_finished;
554 * Submit a packet to the next decoding thread.
557 p = &fctx->threads[fctx->next_decoding];
558 err = update_context_from_user(p->avctx, avctx);
560 err = submit_packet(p, avpkt);
564 * If we're still receiving the initial packets, don't return a frame.
567 if (fctx->delaying) {
568 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
576 * Return the next available frame from the oldest thread.
577 * If we're at the end of the stream, then we have to skip threads that
578 * didn't output a frame, because we don't want to accidentally signal
579 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
583 p = &fctx->threads[finished++];
585 if (p->state != STATE_INPUT_READY) {
586 pthread_mutex_lock(&p->progress_mutex);
587 while (p->state != STATE_INPUT_READY)
588 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
589 pthread_mutex_unlock(&p->progress_mutex);
592 av_frame_move_ref(picture, &p->frame);
593 *got_picture_ptr = p->got_frame;
594 picture->pkt_dts = p->avpkt.dts;
597 * A later call with avkpt->size == 0 may loop over all threads,
598 * including this one, searching for a frame to return before being
599 * stopped by the "finished != fctx->next_finished" condition.
600 * Make sure we don't mistakenly return the same frame again.
604 if (finished >= avctx->thread_count) finished = 0;
605 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
607 update_context_from_thread(avctx, p->avctx, 1);
609 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
611 fctx->next_finished = finished;
613 /* return the size of the consumed packet if no error occurred */
614 return (p->result >= 0) ? avpkt->size : p->result;
617 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
620 int *progress = f->progress ? (int*)f->progress->data : NULL;
622 if (!progress || progress[field] >= n) return;
624 p = f->owner->thread_opaque;
626 if (f->owner->debug&FF_DEBUG_THREADS)
627 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
629 pthread_mutex_lock(&p->progress_mutex);
631 pthread_cond_broadcast(&p->progress_cond);
632 pthread_mutex_unlock(&p->progress_mutex);
635 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
638 int *progress = f->progress ? (int*)f->progress->data : NULL;
640 if (!progress || progress[field] >= n) return;
642 p = f->owner->thread_opaque;
644 if (f->owner->debug&FF_DEBUG_THREADS)
645 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
647 pthread_mutex_lock(&p->progress_mutex);
648 while (progress[field] < n)
649 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
650 pthread_mutex_unlock(&p->progress_mutex);
653 void ff_thread_finish_setup(AVCodecContext *avctx) {
654 PerThreadContext *p = avctx->thread_opaque;
656 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
658 pthread_mutex_lock(&p->progress_mutex);
659 p->state = STATE_SETUP_FINISHED;
660 pthread_cond_broadcast(&p->progress_cond);
661 pthread_mutex_unlock(&p->progress_mutex);
664 /// Waits for all threads to finish.
665 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
669 for (i = 0; i < thread_count; i++) {
670 PerThreadContext *p = &fctx->threads[i];
672 if (p->state != STATE_INPUT_READY) {
673 pthread_mutex_lock(&p->progress_mutex);
674 while (p->state != STATE_INPUT_READY)
675 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
676 pthread_mutex_unlock(&p->progress_mutex);
681 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
683 FrameThreadContext *fctx = avctx->thread_opaque;
684 const AVCodec *codec = avctx->codec;
687 park_frame_worker_threads(fctx, thread_count);
689 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
690 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
694 for (i = 0; i < thread_count; i++) {
695 PerThreadContext *p = &fctx->threads[i];
697 pthread_mutex_lock(&p->mutex);
698 pthread_cond_signal(&p->input_cond);
699 pthread_mutex_unlock(&p->mutex);
702 pthread_join(p->thread, NULL);
705 codec->close(p->avctx);
709 release_delayed_buffers(p);
710 av_frame_unref(&p->frame);
713 for (i = 0; i < thread_count; i++) {
714 PerThreadContext *p = &fctx->threads[i];
716 pthread_mutex_destroy(&p->mutex);
717 pthread_mutex_destroy(&p->progress_mutex);
718 pthread_cond_destroy(&p->input_cond);
719 pthread_cond_destroy(&p->progress_cond);
720 pthread_cond_destroy(&p->output_cond);
721 av_buffer_unref(&p->avpkt.buf);
723 av_freep(&p->released_buffers);
726 av_freep(&p->avctx->priv_data);
727 av_freep(&p->avctx->internal);
728 av_freep(&p->avctx->slice_offset);
734 av_freep(&fctx->threads);
735 pthread_mutex_destroy(&fctx->buffer_mutex);
736 av_freep(&avctx->thread_opaque);
739 static int frame_thread_init(AVCodecContext *avctx)
741 int thread_count = avctx->thread_count;
742 const AVCodec *codec = avctx->codec;
743 AVCodecContext *src = avctx;
744 FrameThreadContext *fctx;
748 int nb_cpus = av_cpu_count();
749 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
750 // use number of cores + 1 as thread count if there is more than one
752 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
754 thread_count = avctx->thread_count = 1;
757 if (thread_count <= 1) {
758 avctx->active_thread_type = 0;
762 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
764 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
765 pthread_mutex_init(&fctx->buffer_mutex, NULL);
768 for (i = 0; i < thread_count; i++) {
769 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
770 PerThreadContext *p = &fctx->threads[i];
772 pthread_mutex_init(&p->mutex, NULL);
773 pthread_mutex_init(&p->progress_mutex, NULL);
774 pthread_cond_init(&p->input_cond, NULL);
775 pthread_cond_init(&p->progress_cond, NULL);
776 pthread_cond_init(&p->output_cond, NULL);
782 err = AVERROR(ENOMEM);
787 copy->thread_opaque = p;
788 copy->pkt = &p->avpkt;
794 err = codec->init(copy);
796 update_context_from_thread(avctx, copy, 1);
798 copy->priv_data = av_malloc(codec->priv_data_size);
799 if (!copy->priv_data) {
800 err = AVERROR(ENOMEM);
803 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
804 copy->internal = av_malloc(sizeof(AVCodecInternal));
805 if (!copy->internal) {
806 err = AVERROR(ENOMEM);
809 *copy->internal = *src->internal;
810 copy->internal->is_copy = 1;
812 if (codec->init_thread_copy)
813 err = codec->init_thread_copy(copy);
818 if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
825 frame_thread_free(avctx, i+1);
830 void ff_thread_flush(AVCodecContext *avctx)
833 FrameThreadContext *fctx = avctx->thread_opaque;
835 if (!avctx->thread_opaque) return;
837 park_frame_worker_threads(fctx, avctx->thread_count);
838 if (fctx->prev_thread) {
839 if (fctx->prev_thread != &fctx->threads[0])
840 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
841 if (avctx->codec->flush)
842 avctx->codec->flush(fctx->threads[0].avctx);
845 fctx->next_decoding = fctx->next_finished = 0;
847 fctx->prev_thread = NULL;
848 for (i = 0; i < avctx->thread_count; i++) {
849 PerThreadContext *p = &fctx->threads[i];
850 // Make sure decode flush calls with size=0 won't return old frames
852 av_frame_unref(&p->frame);
854 release_delayed_buffers(p);
858 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
860 PerThreadContext *p = avctx->thread_opaque;
865 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
866 return ff_get_buffer(avctx, f->f, flags);
868 if (p->state != STATE_SETTING_UP &&
869 (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
870 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
874 if (avctx->internal->allocate_progress) {
876 f->progress = av_buffer_alloc(2 * sizeof(int));
878 return AVERROR(ENOMEM);
880 progress = (int*)f->progress->data;
882 progress[0] = progress[1] = -1;
885 pthread_mutex_lock(&p->parent->buffer_mutex);
886 FF_DISABLE_DEPRECATION_WARNINGS
887 if (avctx->thread_safe_callbacks || (
888 #if FF_API_GET_BUFFER
889 !avctx->get_buffer &&
891 avctx->get_buffer2 == avcodec_default_get_buffer2)) {
892 FF_ENABLE_DEPRECATION_WARNINGS
893 err = ff_get_buffer(avctx, f->f, flags);
895 p->requested_frame = f->f;
896 p->requested_flags = flags;
897 p->state = STATE_GET_BUFFER;
898 pthread_mutex_lock(&p->progress_mutex);
899 pthread_cond_signal(&p->progress_cond);
901 while (p->state != STATE_SETTING_UP)
902 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
906 pthread_mutex_unlock(&p->progress_mutex);
909 if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
910 ff_thread_finish_setup(avctx);
913 av_buffer_unref(&f->progress);
915 pthread_mutex_unlock(&p->parent->buffer_mutex);
920 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
922 PerThreadContext *p = avctx->thread_opaque;
923 FrameThreadContext *fctx;
925 FF_DISABLE_DEPRECATION_WARNINGS
926 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
927 avctx->thread_safe_callbacks ||
929 #if FF_API_GET_BUFFER
930 !avctx->get_buffer &&
932 avctx->get_buffer2 == avcodec_default_get_buffer2);
933 FF_ENABLE_DEPRECATION_WARNINGS
938 if (avctx->debug & FF_DEBUG_BUFFERS)
939 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
941 av_buffer_unref(&f->progress);
944 if (can_direct_free) {
945 av_frame_unref(f->f);
950 pthread_mutex_lock(&fctx->buffer_mutex);
952 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
954 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
955 (p->num_released_buffers + 1) *
956 sizeof(*p->released_buffers));
959 p->released_buffers = tmp;
961 dst = &p->released_buffers[p->num_released_buffers];
962 av_frame_move_ref(dst, f->f);
964 p->num_released_buffers++;
967 pthread_mutex_unlock(&fctx->buffer_mutex);
971 * Set the threading algorithms used.
973 * Threading requires more than one thread.
974 * Frame threading requires entire frames to be passed to the codec,
975 * and introduces extra decoding delay, so is incompatible with low_delay.
977 * @param avctx The context.
979 static void validate_thread_parameters(AVCodecContext *avctx)
981 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
982 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
983 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
984 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
985 if (avctx->thread_count == 1) {
986 avctx->active_thread_type = 0;
987 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
988 avctx->active_thread_type = FF_THREAD_FRAME;
989 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
990 avctx->thread_type & FF_THREAD_SLICE) {
991 avctx->active_thread_type = FF_THREAD_SLICE;
992 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
993 avctx->thread_count = 1;
994 avctx->active_thread_type = 0;
997 if (avctx->thread_count > MAX_AUTO_THREADS)
998 av_log(avctx, AV_LOG_WARNING,
999 "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1000 avctx->thread_count, MAX_AUTO_THREADS);
1003 int ff_thread_init(AVCodecContext *avctx)
1009 validate_thread_parameters(avctx);
1011 if (avctx->active_thread_type&FF_THREAD_SLICE)
1012 return thread_init_internal(avctx);
1013 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1014 return frame_thread_init(avctx);
1019 void ff_thread_free(AVCodecContext *avctx)
1021 if (avctx->active_thread_type&FF_THREAD_FRAME)
1022 frame_thread_free(avctx, avctx->thread_count);