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;
409 dst->delay = src->thread_count - 1;
410 dst->coded_frame = src->coded_frame;
412 if (dst->codec->update_thread_context)
413 err = dst->codec->update_thread_context(dst, src);
420 * Update the next thread's AVCodecContext with values set by the user.
422 * @param dst The destination context.
423 * @param src The source context.
424 * @return 0 on success, negative error code on failure
426 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
428 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
429 dst->flags = src->flags;
431 dst->draw_horiz_band= src->draw_horiz_band;
432 dst->get_buffer2 = src->get_buffer2;
433 #if FF_API_GET_BUFFER
434 dst->get_buffer = src->get_buffer;
435 dst->release_buffer = src->release_buffer;
438 dst->opaque = src->opaque;
439 dst->debug = src->debug;
440 dst->debug_mv = src->debug_mv;
442 dst->slice_flags = src->slice_flags;
443 dst->flags2 = src->flags2;
445 copy_fields(skip_loop_filter, subtitle_header);
447 dst->frame_number = src->frame_number;
448 dst->reordered_opaque = src->reordered_opaque;
449 dst->thread_safe_callbacks = src->thread_safe_callbacks;
451 if (src->slice_count && src->slice_offset) {
452 if (dst->slice_count < src->slice_count) {
453 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
454 sizeof(*dst->slice_offset));
456 av_free(dst->slice_offset);
457 return AVERROR(ENOMEM);
459 dst->slice_offset = tmp;
461 memcpy(dst->slice_offset, src->slice_offset,
462 src->slice_count * sizeof(*dst->slice_offset));
464 dst->slice_count = src->slice_count;
469 /// Releases the buffers that this decoding thread was the last user of.
470 static void release_delayed_buffers(PerThreadContext *p)
472 FrameThreadContext *fctx = p->parent;
474 while (p->num_released_buffers > 0) {
477 pthread_mutex_lock(&fctx->buffer_mutex);
479 // fix extended data in case the caller screwed it up
480 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
481 f = &p->released_buffers[--p->num_released_buffers];
482 f->extended_data = f->data;
485 pthread_mutex_unlock(&fctx->buffer_mutex);
489 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
491 FrameThreadContext *fctx = p->parent;
492 PerThreadContext *prev_thread = fctx->prev_thread;
493 const AVCodec *codec = p->avctx->codec;
495 if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
497 pthread_mutex_lock(&p->mutex);
499 release_delayed_buffers(p);
503 if (prev_thread->state == STATE_SETTING_UP) {
504 pthread_mutex_lock(&prev_thread->progress_mutex);
505 while (prev_thread->state == STATE_SETTING_UP)
506 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
507 pthread_mutex_unlock(&prev_thread->progress_mutex);
510 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
512 pthread_mutex_unlock(&p->mutex);
517 av_buffer_unref(&p->avpkt.buf);
520 p->avpkt.buf = av_buffer_ref(avpkt->buf);
522 av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
523 p->avpkt.data = p->buf;
524 memcpy(p->buf, avpkt->data, avpkt->size);
525 memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
528 p->state = STATE_SETTING_UP;
529 pthread_cond_signal(&p->input_cond);
530 pthread_mutex_unlock(&p->mutex);
533 * If the client doesn't have a thread-safe get_buffer(),
534 * then decoding threads call back to the main thread,
535 * and it calls back to the client here.
538 if (!p->avctx->thread_safe_callbacks && (
539 p->avctx->get_format != avcodec_default_get_format ||
540 #if FF_API_GET_BUFFER
541 p->avctx->get_buffer ||
543 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
544 while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
546 pthread_mutex_lock(&p->progress_mutex);
547 while (p->state == STATE_SETTING_UP)
548 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
551 case STATE_GET_BUFFER:
552 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
554 case STATE_GET_FORMAT:
555 p->result_format = p->avctx->get_format(p->avctx, p->available_formats);
562 p->state = STATE_SETTING_UP;
563 pthread_cond_signal(&p->progress_cond);
565 pthread_mutex_unlock(&p->progress_mutex);
569 fctx->prev_thread = p;
570 fctx->next_decoding++;
575 int ff_thread_decode_frame(AVCodecContext *avctx,
576 AVFrame *picture, int *got_picture_ptr,
579 FrameThreadContext *fctx = avctx->thread_opaque;
580 int finished = fctx->next_finished;
585 * Submit a packet to the next decoding thread.
588 p = &fctx->threads[fctx->next_decoding];
589 err = update_context_from_user(p->avctx, avctx);
591 err = submit_packet(p, avpkt);
595 * If we're still receiving the initial packets, don't return a frame.
598 if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
601 if (fctx->delaying) {
608 * Return the next available frame from the oldest thread.
609 * If we're at the end of the stream, then we have to skip threads that
610 * didn't output a frame, because we don't want to accidentally signal
611 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
615 p = &fctx->threads[finished++];
617 if (p->state != STATE_INPUT_READY) {
618 pthread_mutex_lock(&p->progress_mutex);
619 while (p->state != STATE_INPUT_READY)
620 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
621 pthread_mutex_unlock(&p->progress_mutex);
624 av_frame_move_ref(picture, &p->frame);
625 *got_picture_ptr = p->got_frame;
626 picture->pkt_dts = p->avpkt.dts;
629 * A later call with avkpt->size == 0 may loop over all threads,
630 * including this one, searching for a frame to return before being
631 * stopped by the "finished != fctx->next_finished" condition.
632 * Make sure we don't mistakenly return the same frame again.
636 if (finished >= avctx->thread_count) finished = 0;
637 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
639 update_context_from_thread(avctx, p->avctx, 1);
641 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
643 fctx->next_finished = finished;
645 /* return the size of the consumed packet if no error occurred */
646 return (p->result >= 0) ? avpkt->size : p->result;
649 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
652 volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
654 if (!progress || progress[field] >= n) return;
656 p = f->owner->thread_opaque;
658 if (f->owner->debug&FF_DEBUG_THREADS)
659 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
661 pthread_mutex_lock(&p->progress_mutex);
663 pthread_cond_broadcast(&p->progress_cond);
664 pthread_mutex_unlock(&p->progress_mutex);
667 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
670 volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
672 if (!progress || progress[field] >= n) return;
674 p = f->owner->thread_opaque;
676 if (f->owner->debug&FF_DEBUG_THREADS)
677 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
679 pthread_mutex_lock(&p->progress_mutex);
680 while (progress[field] < n)
681 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
682 pthread_mutex_unlock(&p->progress_mutex);
685 void ff_thread_finish_setup(AVCodecContext *avctx) {
686 PerThreadContext *p = avctx->thread_opaque;
688 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
690 if(p->state == STATE_SETUP_FINISHED){
691 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
694 pthread_mutex_lock(&p->progress_mutex);
695 p->state = STATE_SETUP_FINISHED;
696 pthread_cond_broadcast(&p->progress_cond);
697 pthread_mutex_unlock(&p->progress_mutex);
700 /// Waits for all threads to finish.
701 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
705 for (i = 0; i < thread_count; i++) {
706 PerThreadContext *p = &fctx->threads[i];
708 if (p->state != STATE_INPUT_READY) {
709 pthread_mutex_lock(&p->progress_mutex);
710 while (p->state != STATE_INPUT_READY)
711 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
712 pthread_mutex_unlock(&p->progress_mutex);
718 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
720 FrameThreadContext *fctx = avctx->thread_opaque;
721 const AVCodec *codec = avctx->codec;
724 park_frame_worker_threads(fctx, thread_count);
726 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
727 if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
728 av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
729 fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
730 fctx->threads->avctx->internal->is_copy = 1;
735 for (i = 0; i < thread_count; i++) {
736 PerThreadContext *p = &fctx->threads[i];
738 pthread_mutex_lock(&p->mutex);
739 pthread_cond_signal(&p->input_cond);
740 pthread_mutex_unlock(&p->mutex);
743 pthread_join(p->thread, NULL);
747 codec->close(p->avctx);
751 release_delayed_buffers(p);
752 av_frame_unref(&p->frame);
755 for (i = 0; i < thread_count; i++) {
756 PerThreadContext *p = &fctx->threads[i];
758 pthread_mutex_destroy(&p->mutex);
759 pthread_mutex_destroy(&p->progress_mutex);
760 pthread_cond_destroy(&p->input_cond);
761 pthread_cond_destroy(&p->progress_cond);
762 pthread_cond_destroy(&p->output_cond);
763 av_buffer_unref(&p->avpkt.buf);
765 av_freep(&p->released_buffers);
768 av_freep(&p->avctx->priv_data);
769 av_freep(&p->avctx->internal);
770 av_freep(&p->avctx->slice_offset);
776 av_freep(&fctx->threads);
777 pthread_mutex_destroy(&fctx->buffer_mutex);
778 av_freep(&avctx->thread_opaque);
781 static int frame_thread_init(AVCodecContext *avctx)
783 int thread_count = avctx->thread_count;
784 const AVCodec *codec = avctx->codec;
785 AVCodecContext *src = avctx;
786 FrameThreadContext *fctx;
790 int nb_cpus = av_cpu_count();
791 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
793 // use number of cores + 1 as thread count if there is more than one
795 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
797 thread_count = avctx->thread_count = 1;
800 if (thread_count <= 1) {
801 avctx->active_thread_type = 0;
805 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
807 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
808 pthread_mutex_init(&fctx->buffer_mutex, NULL);
811 for (i = 0; i < thread_count; i++) {
812 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
813 PerThreadContext *p = &fctx->threads[i];
815 pthread_mutex_init(&p->mutex, NULL);
816 pthread_mutex_init(&p->progress_mutex, NULL);
817 pthread_cond_init(&p->input_cond, NULL);
818 pthread_cond_init(&p->progress_cond, NULL);
819 pthread_cond_init(&p->output_cond, NULL);
825 err = AVERROR(ENOMEM);
830 copy->thread_opaque = p;
831 copy->pkt = &p->avpkt;
837 err = codec->init(copy);
839 update_context_from_thread(avctx, copy, 1);
841 copy->priv_data = av_malloc(codec->priv_data_size);
842 if (!copy->priv_data) {
843 err = AVERROR(ENOMEM);
846 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
847 copy->internal = av_malloc(sizeof(AVCodecInternal));
848 if (!copy->internal) {
849 err = AVERROR(ENOMEM);
852 *copy->internal = *src->internal;
853 copy->internal->is_copy = 1;
855 if (codec->init_thread_copy)
856 err = codec->init_thread_copy(copy);
861 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
862 p->thread_init= !err;
870 frame_thread_free(avctx, i+1);
875 void ff_thread_flush(AVCodecContext *avctx)
878 FrameThreadContext *fctx = avctx->thread_opaque;
880 if (!avctx->thread_opaque) return;
882 park_frame_worker_threads(fctx, avctx->thread_count);
883 if (fctx->prev_thread) {
884 if (fctx->prev_thread != &fctx->threads[0])
885 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
886 if (avctx->codec->flush)
887 avctx->codec->flush(fctx->threads[0].avctx);
890 fctx->next_decoding = fctx->next_finished = 0;
892 fctx->prev_thread = NULL;
893 for (i = 0; i < avctx->thread_count; i++) {
894 PerThreadContext *p = &fctx->threads[i];
895 // Make sure decode flush calls with size=0 won't return old frames
897 av_frame_unref(&p->frame);
899 release_delayed_buffers(p);
903 int ff_thread_can_start_frame(AVCodecContext *avctx)
905 PerThreadContext *p = avctx->thread_opaque;
906 if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
907 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
913 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
915 PerThreadContext *p = avctx->thread_opaque;
920 ff_init_buffer_info(avctx, f->f);
922 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
923 return ff_get_buffer(avctx, f->f, flags);
925 if (p->state != STATE_SETTING_UP &&
926 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
927 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
931 if (avctx->internal->allocate_progress) {
933 f->progress = av_buffer_alloc(2 * sizeof(int));
935 return AVERROR(ENOMEM);
937 progress = (int*)f->progress->data;
939 progress[0] = progress[1] = -1;
942 pthread_mutex_lock(&p->parent->buffer_mutex);
944 if (avctx->thread_safe_callbacks || (
945 #if FF_API_GET_BUFFER
946 !avctx->get_buffer &&
948 avctx->get_buffer2 == avcodec_default_get_buffer2)) {
949 err = ff_get_buffer(avctx, f->f, flags);
951 pthread_mutex_lock(&p->progress_mutex);
952 p->requested_frame = f->f;
953 p->requested_flags = flags;
954 p->state = STATE_GET_BUFFER;
955 pthread_cond_broadcast(&p->progress_cond);
957 while (p->state != STATE_SETTING_UP)
958 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
962 pthread_mutex_unlock(&p->progress_mutex);
965 if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
966 ff_thread_finish_setup(avctx);
969 av_buffer_unref(&f->progress);
971 pthread_mutex_unlock(&p->parent->buffer_mutex);
976 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
978 enum AVPixelFormat res;
979 PerThreadContext *p = avctx->thread_opaque;
980 if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
981 avctx->get_format == avcodec_default_get_format)
982 return avctx->get_format(avctx, fmt);
983 if (p->state != STATE_SETTING_UP) {
984 av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
987 pthread_mutex_lock(&p->progress_mutex);
988 p->available_formats = fmt;
989 p->state = STATE_GET_FORMAT;
990 pthread_cond_broadcast(&p->progress_cond);
992 while (p->state != STATE_SETTING_UP)
993 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
995 res = p->result_format;
997 pthread_mutex_unlock(&p->progress_mutex);
1002 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1004 int ret = thread_get_buffer_internal(avctx, f, flags);
1006 av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1010 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1012 PerThreadContext *p = avctx->thread_opaque;
1013 FrameThreadContext *fctx;
1015 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1016 avctx->thread_safe_callbacks ||
1018 #if FF_API_GET_BUFFER
1019 !avctx->get_buffer &&
1021 avctx->get_buffer2 == avcodec_default_get_buffer2);
1026 if (avctx->debug & FF_DEBUG_BUFFERS)
1027 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1029 av_buffer_unref(&f->progress);
1032 if (can_direct_free) {
1033 av_frame_unref(f->f);
1038 pthread_mutex_lock(&fctx->buffer_mutex);
1040 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
1042 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
1043 (p->num_released_buffers + 1) *
1044 sizeof(*p->released_buffers));
1047 p->released_buffers = tmp;
1049 dst = &p->released_buffers[p->num_released_buffers];
1050 av_frame_move_ref(dst, f->f);
1052 p->num_released_buffers++;
1055 pthread_mutex_unlock(&fctx->buffer_mutex);
1059 * Set the threading algorithms used.
1061 * Threading requires more than one thread.
1062 * Frame threading requires entire frames to be passed to the codec,
1063 * and introduces extra decoding delay, so is incompatible with low_delay.
1065 * @param avctx The context.
1067 static void validate_thread_parameters(AVCodecContext *avctx)
1069 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1070 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1071 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1072 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1073 if (avctx->thread_count == 1) {
1074 avctx->active_thread_type = 0;
1075 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1076 avctx->active_thread_type = FF_THREAD_FRAME;
1077 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1078 avctx->thread_type & FF_THREAD_SLICE) {
1079 avctx->active_thread_type = FF_THREAD_SLICE;
1080 } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1081 avctx->thread_count = 1;
1082 avctx->active_thread_type = 0;
1085 if (avctx->thread_count > MAX_AUTO_THREADS)
1086 av_log(avctx, AV_LOG_WARNING,
1087 "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1088 avctx->thread_count, MAX_AUTO_THREADS);
1091 int ff_thread_init(AVCodecContext *avctx)
1097 validate_thread_parameters(avctx);
1099 if (avctx->active_thread_type&FF_THREAD_SLICE)
1100 return thread_init(avctx);
1101 else if (avctx->active_thread_type&FF_THREAD_FRAME)
1102 return frame_thread_init(avctx);
1107 void ff_thread_free(AVCodecContext *avctx)
1109 if (avctx->active_thread_type&FF_THREAD_FRAME)
1110 frame_thread_free(avctx, avctx->thread_count);