]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread_frame.c
avcodec/mediacodec_wrapper: use MediaFormat to probe frame color characteristics
[ffmpeg] / libavcodec / pthread_frame.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 /**
20  * @file
21  * Frame multithreading support functions
22  * @see doc/multithreading.txt
23  */
24
25 #include "config.h"
26
27 #include <stdatomic.h>
28 #include <stdint.h>
29
30 #include "avcodec.h"
31 #include "hwconfig.h"
32 #include "internal.h"
33 #include "pthread_internal.h"
34 #include "thread.h"
35 #include "version.h"
36
37 #include "libavutil/avassert.h"
38 #include "libavutil/buffer.h"
39 #include "libavutil/common.h"
40 #include "libavutil/cpu.h"
41 #include "libavutil/frame.h"
42 #include "libavutil/internal.h"
43 #include "libavutil/log.h"
44 #include "libavutil/mem.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/thread.h"
47
48 enum {
49     ///< Set when the thread is awaiting a packet.
50     STATE_INPUT_READY,
51     ///< Set before the codec has called ff_thread_finish_setup().
52     STATE_SETTING_UP,
53     /**
54      * Set when the codec calls get_buffer().
55      * State is returned to STATE_SETTING_UP afterwards.
56      */
57     STATE_GET_BUFFER,
58      /**
59       * Set when the codec calls get_format().
60       * State is returned to STATE_SETTING_UP afterwards.
61       */
62     STATE_GET_FORMAT,
63     ///< Set after the codec has called ff_thread_finish_setup().
64     STATE_SETUP_FINISHED,
65 };
66
67 /**
68  * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
69  */
70 typedef struct PerThreadContext {
71     struct FrameThreadContext *parent;
72
73     pthread_t      thread;
74     int            thread_init;
75     pthread_cond_t input_cond;      ///< Used to wait for a new packet from the main thread.
76     pthread_cond_t progress_cond;   ///< Used by child threads to wait for progress to change.
77     pthread_cond_t output_cond;     ///< Used by the main thread to wait for frames to finish.
78
79     pthread_mutex_t mutex;          ///< Mutex used to protect the contents of the PerThreadContext.
80     pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
81
82     AVCodecContext *avctx;          ///< Context used to decode packets passed to this thread.
83
84     AVPacket       avpkt;           ///< Input packet (for decoding) or output (for encoding).
85
86     AVFrame *frame;                 ///< Output frame (for decoding) or input (for encoding).
87     int     got_frame;              ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
88     int     result;                 ///< The result of the last codec decode/encode() call.
89
90     atomic_int state;
91
92     /**
93      * Array of frames passed to ff_thread_release_buffer().
94      * Frames are released after all threads referencing them are finished.
95      */
96     AVFrame **released_buffers;
97     int   num_released_buffers;
98     int       released_buffers_allocated;
99
100     AVFrame *requested_frame;       ///< AVFrame the codec passed to get_buffer()
101     int      requested_flags;       ///< flags passed to get_buffer() for requested_frame
102
103     const enum AVPixelFormat *available_formats; ///< Format array for get_format()
104     enum AVPixelFormat result_format;            ///< get_format() result
105
106     int die;                        ///< Set when the thread should exit.
107
108     int hwaccel_serializing;
109     int async_serializing;
110
111     atomic_int debug_threads;       ///< Set if the FF_DEBUG_THREADS option is set.
112 } PerThreadContext;
113
114 /**
115  * Context stored in the client AVCodecInternal thread_ctx.
116  */
117 typedef struct FrameThreadContext {
118     PerThreadContext *threads;     ///< The contexts for each thread.
119     PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
120
121     pthread_mutex_t buffer_mutex;  ///< Mutex used to protect get/release_buffer().
122     /**
123      * This lock is used for ensuring threads run in serial when hwaccel
124      * is used.
125      */
126     pthread_mutex_t hwaccel_mutex;
127     pthread_mutex_t async_mutex;
128     pthread_cond_t async_cond;
129     int async_lock;
130
131     int next_decoding;             ///< The next context to submit a packet to.
132     int next_finished;             ///< The next context to return output from.
133
134     int delaying;                  /**<
135                                     * Set for the first N packets, where N is the number of threads.
136                                     * While it is set, ff_thread_en/decode_frame won't return any results.
137                                     */
138 } FrameThreadContext;
139
140 #define THREAD_SAFE_CALLBACKS(avctx) \
141 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
142
143 static void async_lock(FrameThreadContext *fctx)
144 {
145     pthread_mutex_lock(&fctx->async_mutex);
146     while (fctx->async_lock)
147         pthread_cond_wait(&fctx->async_cond, &fctx->async_mutex);
148     fctx->async_lock = 1;
149     pthread_mutex_unlock(&fctx->async_mutex);
150 }
151
152 static void async_unlock(FrameThreadContext *fctx)
153 {
154     pthread_mutex_lock(&fctx->async_mutex);
155     av_assert0(fctx->async_lock);
156     fctx->async_lock = 0;
157     pthread_cond_broadcast(&fctx->async_cond);
158     pthread_mutex_unlock(&fctx->async_mutex);
159 }
160
161 /**
162  * Codec worker thread.
163  *
164  * Automatically calls ff_thread_finish_setup() if the codec does
165  * not provide an update_thread_context method, or if the codec returns
166  * before calling it.
167  */
168 static attribute_align_arg void *frame_worker_thread(void *arg)
169 {
170     PerThreadContext *p = arg;
171     AVCodecContext *avctx = p->avctx;
172     const AVCodec *codec = avctx->codec;
173
174     pthread_mutex_lock(&p->mutex);
175     while (1) {
176         while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
177             pthread_cond_wait(&p->input_cond, &p->mutex);
178
179         if (p->die) break;
180
181         if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
182             ff_thread_finish_setup(avctx);
183
184         /* If a decoder supports hwaccel, then it must call ff_get_format().
185          * Since that call must happen before ff_thread_finish_setup(), the
186          * decoder is required to implement update_thread_context() and call
187          * ff_thread_finish_setup() manually. Therefore the above
188          * ff_thread_finish_setup() call did not happen and hwaccel_serializing
189          * cannot be true here. */
190         av_assert0(!p->hwaccel_serializing);
191
192         /* if the previous thread uses hwaccel then we take the lock to ensure
193          * the threads don't run concurrently */
194         if (avctx->hwaccel) {
195             pthread_mutex_lock(&p->parent->hwaccel_mutex);
196             p->hwaccel_serializing = 1;
197         }
198
199         av_frame_unref(p->frame);
200         p->got_frame = 0;
201         p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
202
203         if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
204             if (avctx->codec->caps_internal & FF_CODEC_CAP_ALLOCATE_PROGRESS)
205                 av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
206                        "free the frame on failure. This is a bug, please report it.\n");
207             av_frame_unref(p->frame);
208         }
209
210         if (atomic_load(&p->state) == STATE_SETTING_UP)
211             ff_thread_finish_setup(avctx);
212
213         if (p->hwaccel_serializing) {
214             p->hwaccel_serializing = 0;
215             pthread_mutex_unlock(&p->parent->hwaccel_mutex);
216         }
217
218         if (p->async_serializing) {
219             p->async_serializing = 0;
220
221             async_unlock(p->parent);
222         }
223
224         pthread_mutex_lock(&p->progress_mutex);
225
226         atomic_store(&p->state, STATE_INPUT_READY);
227
228         pthread_cond_broadcast(&p->progress_cond);
229         pthread_cond_signal(&p->output_cond);
230         pthread_mutex_unlock(&p->progress_mutex);
231     }
232     pthread_mutex_unlock(&p->mutex);
233
234     return NULL;
235 }
236
237 /**
238  * Update the next thread's AVCodecContext with values from the reference thread's context.
239  *
240  * @param dst The destination context.
241  * @param src The source context.
242  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
243  * @return 0 on success, negative error code on failure
244  */
245 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
246 {
247     int err = 0;
248
249     if (dst != src && (for_user || !(src->codec_descriptor->props & AV_CODEC_PROP_INTRA_ONLY))) {
250         dst->time_base = src->time_base;
251         dst->framerate = src->framerate;
252         dst->width     = src->width;
253         dst->height    = src->height;
254         dst->pix_fmt   = src->pix_fmt;
255         dst->sw_pix_fmt = src->sw_pix_fmt;
256
257         dst->coded_width  = src->coded_width;
258         dst->coded_height = src->coded_height;
259
260         dst->has_b_frames = src->has_b_frames;
261         dst->idct_algo    = src->idct_algo;
262
263         dst->bits_per_coded_sample = src->bits_per_coded_sample;
264         dst->sample_aspect_ratio   = src->sample_aspect_ratio;
265
266         dst->profile = src->profile;
267         dst->level   = src->level;
268
269         dst->bits_per_raw_sample = src->bits_per_raw_sample;
270         dst->ticks_per_frame     = src->ticks_per_frame;
271         dst->color_primaries     = src->color_primaries;
272
273         dst->color_trc   = src->color_trc;
274         dst->colorspace  = src->colorspace;
275         dst->color_range = src->color_range;
276         dst->chroma_sample_location = src->chroma_sample_location;
277
278         dst->hwaccel = src->hwaccel;
279         dst->hwaccel_context = src->hwaccel_context;
280
281         dst->channels       = src->channels;
282         dst->sample_rate    = src->sample_rate;
283         dst->sample_fmt     = src->sample_fmt;
284         dst->channel_layout = src->channel_layout;
285         dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
286
287         if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
288             (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
289             av_buffer_unref(&dst->hw_frames_ctx);
290
291             if (src->hw_frames_ctx) {
292                 dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
293                 if (!dst->hw_frames_ctx)
294                     return AVERROR(ENOMEM);
295             }
296         }
297
298         dst->hwaccel_flags = src->hwaccel_flags;
299
300         if (!!dst->internal->pool != !!src->internal->pool ||
301             (dst->internal->pool && dst->internal->pool->data != src->internal->pool->data)) {
302             av_buffer_unref(&dst->internal->pool);
303
304             if (src->internal->pool) {
305                 dst->internal->pool = av_buffer_ref(src->internal->pool);
306                 if (!dst->internal->pool)
307                     return AVERROR(ENOMEM);
308             }
309         }
310     }
311
312     if (for_user) {
313         dst->delay       = src->thread_count - 1;
314 #if FF_API_CODED_FRAME
315 FF_DISABLE_DEPRECATION_WARNINGS
316         dst->coded_frame = src->coded_frame;
317 FF_ENABLE_DEPRECATION_WARNINGS
318 #endif
319     } else {
320         if (dst->codec->update_thread_context)
321             err = dst->codec->update_thread_context(dst, src);
322     }
323
324     return err;
325 }
326
327 /**
328  * Update the next thread's AVCodecContext with values set by the user.
329  *
330  * @param dst The destination context.
331  * @param src The source context.
332  * @return 0 on success, negative error code on failure
333  */
334 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
335 {
336     dst->flags          = src->flags;
337
338     dst->draw_horiz_band= src->draw_horiz_band;
339     dst->get_buffer2    = src->get_buffer2;
340
341     dst->opaque   = src->opaque;
342     dst->debug    = src->debug;
343     dst->debug_mv = src->debug_mv;
344
345     dst->slice_flags = src->slice_flags;
346     dst->flags2      = src->flags2;
347     dst->export_side_data = src->export_side_data;
348
349     dst->skip_loop_filter = src->skip_loop_filter;
350     dst->skip_idct        = src->skip_idct;
351     dst->skip_frame       = src->skip_frame;
352
353     dst->frame_number     = src->frame_number;
354     dst->reordered_opaque = src->reordered_opaque;
355     dst->thread_safe_callbacks = src->thread_safe_callbacks;
356
357     if (src->slice_count && src->slice_offset) {
358         if (dst->slice_count < src->slice_count) {
359             int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
360                                         sizeof(*dst->slice_offset));
361             if (err < 0)
362                 return err;
363         }
364         memcpy(dst->slice_offset, src->slice_offset,
365                src->slice_count * sizeof(*dst->slice_offset));
366     }
367     dst->slice_count = src->slice_count;
368     return 0;
369 }
370
371 /// Releases the buffers that this decoding thread was the last user of.
372 static void release_delayed_buffers(PerThreadContext *p)
373 {
374     FrameThreadContext *fctx = p->parent;
375
376     while (p->num_released_buffers > 0) {
377         AVFrame *f;
378
379         pthread_mutex_lock(&fctx->buffer_mutex);
380
381         // fix extended data in case the caller screwed it up
382         av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
383                    p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
384         f = p->released_buffers[--p->num_released_buffers];
385         f->extended_data = f->data;
386         av_frame_unref(f);
387
388         pthread_mutex_unlock(&fctx->buffer_mutex);
389     }
390 }
391
392 static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx,
393                          AVPacket *avpkt)
394 {
395     FrameThreadContext *fctx = p->parent;
396     PerThreadContext *prev_thread = fctx->prev_thread;
397     const AVCodec *codec = p->avctx->codec;
398     int ret;
399
400     if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
401         return 0;
402
403     pthread_mutex_lock(&p->mutex);
404
405     ret = update_context_from_user(p->avctx, user_avctx);
406     if (ret) {
407         pthread_mutex_unlock(&p->mutex);
408         return ret;
409     }
410     atomic_store_explicit(&p->debug_threads,
411                           (p->avctx->debug & FF_DEBUG_THREADS) != 0,
412                           memory_order_relaxed);
413
414     release_delayed_buffers(p);
415
416     if (prev_thread) {
417         int err;
418         if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
419             pthread_mutex_lock(&prev_thread->progress_mutex);
420             while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
421                 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
422             pthread_mutex_unlock(&prev_thread->progress_mutex);
423         }
424
425         err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
426         if (err) {
427             pthread_mutex_unlock(&p->mutex);
428             return err;
429         }
430     }
431
432     av_packet_unref(&p->avpkt);
433     ret = av_packet_ref(&p->avpkt, avpkt);
434     if (ret < 0) {
435         pthread_mutex_unlock(&p->mutex);
436         av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
437         return ret;
438     }
439
440     atomic_store(&p->state, STATE_SETTING_UP);
441     pthread_cond_signal(&p->input_cond);
442     pthread_mutex_unlock(&p->mutex);
443
444     /*
445      * If the client doesn't have a thread-safe get_buffer(),
446      * then decoding threads call back to the main thread,
447      * and it calls back to the client here.
448      */
449
450     if (!p->avctx->thread_safe_callbacks && (
451          p->avctx->get_format != avcodec_default_get_format ||
452          p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
453         while (atomic_load(&p->state) != STATE_SETUP_FINISHED && atomic_load(&p->state) != STATE_INPUT_READY) {
454             int call_done = 1;
455             pthread_mutex_lock(&p->progress_mutex);
456             while (atomic_load(&p->state) == STATE_SETTING_UP)
457                 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
458
459             switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
460             case STATE_GET_BUFFER:
461                 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
462                 break;
463             case STATE_GET_FORMAT:
464                 p->result_format = ff_get_format(p->avctx, p->available_formats);
465                 break;
466             default:
467                 call_done = 0;
468                 break;
469             }
470             if (call_done) {
471                 atomic_store(&p->state, STATE_SETTING_UP);
472                 pthread_cond_signal(&p->progress_cond);
473             }
474             pthread_mutex_unlock(&p->progress_mutex);
475         }
476     }
477
478     fctx->prev_thread = p;
479     fctx->next_decoding++;
480
481     return 0;
482 }
483
484 int ff_thread_decode_frame(AVCodecContext *avctx,
485                            AVFrame *picture, int *got_picture_ptr,
486                            AVPacket *avpkt)
487 {
488     FrameThreadContext *fctx = avctx->internal->thread_ctx;
489     int finished = fctx->next_finished;
490     PerThreadContext *p;
491     int err;
492
493     /* release the async lock, permitting blocked hwaccel threads to
494      * go forward while we are in this function */
495     async_unlock(fctx);
496
497     /*
498      * Submit a packet to the next decoding thread.
499      */
500
501     p = &fctx->threads[fctx->next_decoding];
502     err = submit_packet(p, avctx, avpkt);
503     if (err)
504         goto finish;
505
506     /*
507      * If we're still receiving the initial packets, don't return a frame.
508      */
509
510     if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
511         fctx->delaying = 0;
512
513     if (fctx->delaying) {
514         *got_picture_ptr=0;
515         if (avpkt->size) {
516             err = avpkt->size;
517             goto finish;
518         }
519     }
520
521     /*
522      * Return the next available frame from the oldest thread.
523      * If we're at the end of the stream, then we have to skip threads that
524      * didn't output a frame/error, because we don't want to accidentally signal
525      * EOF (avpkt->size == 0 && *got_picture_ptr == 0 && err >= 0).
526      */
527
528     do {
529         p = &fctx->threads[finished++];
530
531         if (atomic_load(&p->state) != STATE_INPUT_READY) {
532             pthread_mutex_lock(&p->progress_mutex);
533             while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
534                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
535             pthread_mutex_unlock(&p->progress_mutex);
536         }
537
538         av_frame_move_ref(picture, p->frame);
539         *got_picture_ptr = p->got_frame;
540         picture->pkt_dts = p->avpkt.dts;
541         err = p->result;
542
543         /*
544          * A later call with avkpt->size == 0 may loop over all threads,
545          * including this one, searching for a frame/error to return before being
546          * stopped by the "finished != fctx->next_finished" condition.
547          * Make sure we don't mistakenly return the same frame/error again.
548          */
549         p->got_frame = 0;
550         p->result = 0;
551
552         if (finished >= avctx->thread_count) finished = 0;
553     } while (!avpkt->size && !*got_picture_ptr && err >= 0 && finished != fctx->next_finished);
554
555     update_context_from_thread(avctx, p->avctx, 1);
556
557     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
558
559     fctx->next_finished = finished;
560
561     /* return the size of the consumed packet if no error occurred */
562     if (err >= 0)
563         err = avpkt->size;
564 finish:
565     async_lock(fctx);
566     return err;
567 }
568
569 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
570 {
571     PerThreadContext *p;
572     atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
573
574     if (!progress ||
575         atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
576         return;
577
578     p = f->owner[field]->internal->thread_ctx;
579
580     if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
581         av_log(f->owner[field], AV_LOG_DEBUG,
582                "%p finished %d field %d\n", progress, n, field);
583
584     pthread_mutex_lock(&p->progress_mutex);
585
586     atomic_store_explicit(&progress[field], n, memory_order_release);
587
588     pthread_cond_broadcast(&p->progress_cond);
589     pthread_mutex_unlock(&p->progress_mutex);
590 }
591
592 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
593 {
594     PerThreadContext *p;
595     atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
596
597     if (!progress ||
598         atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
599         return;
600
601     p = f->owner[field]->internal->thread_ctx;
602
603     if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
604         av_log(f->owner[field], AV_LOG_DEBUG,
605                "thread awaiting %d field %d from %p\n", n, field, progress);
606
607     pthread_mutex_lock(&p->progress_mutex);
608     while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
609         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
610     pthread_mutex_unlock(&p->progress_mutex);
611 }
612
613 void ff_thread_finish_setup(AVCodecContext *avctx) {
614     PerThreadContext *p = avctx->internal->thread_ctx;
615
616     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
617
618     if (avctx->hwaccel && !p->hwaccel_serializing) {
619         pthread_mutex_lock(&p->parent->hwaccel_mutex);
620         p->hwaccel_serializing = 1;
621     }
622
623     /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
624     if (avctx->hwaccel &&
625         !(avctx->hwaccel->caps_internal & HWACCEL_CAP_ASYNC_SAFE)) {
626         p->async_serializing = 1;
627
628         async_lock(p->parent);
629     }
630
631     pthread_mutex_lock(&p->progress_mutex);
632     if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
633         av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
634     }
635
636     atomic_store(&p->state, STATE_SETUP_FINISHED);
637
638     pthread_cond_broadcast(&p->progress_cond);
639     pthread_mutex_unlock(&p->progress_mutex);
640 }
641
642 /// Waits for all threads to finish.
643 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
644 {
645     int i;
646
647     async_unlock(fctx);
648
649     for (i = 0; i < thread_count; i++) {
650         PerThreadContext *p = &fctx->threads[i];
651
652         if (atomic_load(&p->state) != STATE_INPUT_READY) {
653             pthread_mutex_lock(&p->progress_mutex);
654             while (atomic_load(&p->state) != STATE_INPUT_READY)
655                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
656             pthread_mutex_unlock(&p->progress_mutex);
657         }
658         p->got_frame = 0;
659     }
660
661     async_lock(fctx);
662 }
663
664 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
665 {
666     FrameThreadContext *fctx = avctx->internal->thread_ctx;
667     const AVCodec *codec = avctx->codec;
668     int i, j;
669
670     park_frame_worker_threads(fctx, thread_count);
671
672     if (fctx->prev_thread && avctx->internal->hwaccel_priv_data !=
673                              fctx->prev_thread->avctx->internal->hwaccel_priv_data) {
674         if (update_context_from_thread(avctx, fctx->prev_thread->avctx, 1) < 0) {
675             av_log(avctx, AV_LOG_ERROR, "Failed to update user thread.\n");
676         }
677     }
678
679     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
680         if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
681             av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
682             fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
683             fctx->threads->avctx->internal->is_copy = 1;
684         }
685
686     for (i = 0; i < thread_count; i++) {
687         PerThreadContext *p = &fctx->threads[i];
688
689         pthread_mutex_lock(&p->mutex);
690         p->die = 1;
691         pthread_cond_signal(&p->input_cond);
692         pthread_mutex_unlock(&p->mutex);
693
694         if (p->thread_init)
695             pthread_join(p->thread, NULL);
696         p->thread_init=0;
697
698         if (codec->close && p->avctx)
699             codec->close(p->avctx);
700
701         release_delayed_buffers(p);
702         av_frame_free(&p->frame);
703     }
704
705     for (i = 0; i < thread_count; i++) {
706         PerThreadContext *p = &fctx->threads[i];
707
708         pthread_mutex_destroy(&p->mutex);
709         pthread_mutex_destroy(&p->progress_mutex);
710         pthread_cond_destroy(&p->input_cond);
711         pthread_cond_destroy(&p->progress_cond);
712         pthread_cond_destroy(&p->output_cond);
713         av_packet_unref(&p->avpkt);
714
715         for (j = 0; j < p->released_buffers_allocated; j++)
716             av_frame_free(&p->released_buffers[j]);
717         av_freep(&p->released_buffers);
718
719         if (p->avctx) {
720             if (codec->priv_class)
721                 av_opt_free(p->avctx->priv_data);
722             av_freep(&p->avctx->priv_data);
723
724             av_freep(&p->avctx->slice_offset);
725         }
726
727         if (p->avctx) {
728             av_buffer_unref(&p->avctx->internal->pool);
729             av_freep(&p->avctx->internal);
730             av_buffer_unref(&p->avctx->hw_frames_ctx);
731         }
732
733         av_freep(&p->avctx);
734     }
735
736     av_freep(&fctx->threads);
737     pthread_mutex_destroy(&fctx->buffer_mutex);
738     pthread_mutex_destroy(&fctx->hwaccel_mutex);
739     pthread_mutex_destroy(&fctx->async_mutex);
740     pthread_cond_destroy(&fctx->async_cond);
741
742     av_freep(&avctx->internal->thread_ctx);
743
744     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
745         av_opt_free(avctx->priv_data);
746     avctx->codec = NULL;
747 }
748
749 int ff_frame_thread_init(AVCodecContext *avctx)
750 {
751     int thread_count = avctx->thread_count;
752     const AVCodec *codec = avctx->codec;
753     AVCodecContext *src = avctx;
754     FrameThreadContext *fctx;
755     int i, err = 0;
756
757     if (!thread_count) {
758         int nb_cpus = av_cpu_count();
759 #if FF_API_DEBUG_MV
760         if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
761             nb_cpus = 1;
762 #endif
763         // use number of cores + 1 as thread count if there is more than one
764         if (nb_cpus > 1)
765             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
766         else
767             thread_count = avctx->thread_count = 1;
768     }
769
770     if (thread_count <= 1) {
771         avctx->active_thread_type = 0;
772         return 0;
773     }
774
775     avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
776     if (!fctx)
777         return AVERROR(ENOMEM);
778
779     fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
780     if (!fctx->threads) {
781         av_freep(&avctx->internal->thread_ctx);
782         return AVERROR(ENOMEM);
783     }
784
785     pthread_mutex_init(&fctx->buffer_mutex, NULL);
786     pthread_mutex_init(&fctx->hwaccel_mutex, NULL);
787     pthread_mutex_init(&fctx->async_mutex, NULL);
788     pthread_cond_init(&fctx->async_cond, NULL);
789
790     fctx->async_lock = 1;
791     fctx->delaying = 1;
792
793     for (i = 0; i < thread_count; i++) {
794         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
795         PerThreadContext *p  = &fctx->threads[i];
796
797         pthread_mutex_init(&p->mutex, NULL);
798         pthread_mutex_init(&p->progress_mutex, NULL);
799         pthread_cond_init(&p->input_cond, NULL);
800         pthread_cond_init(&p->progress_cond, NULL);
801         pthread_cond_init(&p->output_cond, NULL);
802
803         p->frame = av_frame_alloc();
804         if (!p->frame) {
805             av_freep(&copy);
806             err = AVERROR(ENOMEM);
807             goto error;
808         }
809
810         p->parent = fctx;
811         p->avctx  = copy;
812
813         if (!copy) {
814             err = AVERROR(ENOMEM);
815             goto error;
816         }
817
818         *copy = *src;
819
820         copy->internal = av_malloc(sizeof(AVCodecInternal));
821         if (!copy->internal) {
822             copy->priv_data = NULL;
823             err = AVERROR(ENOMEM);
824             goto error;
825         }
826         *copy->internal = *src->internal;
827         copy->internal->thread_ctx = p;
828         copy->internal->last_pkt_props = &p->avpkt;
829
830         if (codec->priv_data_size) {
831             copy->priv_data = av_mallocz(codec->priv_data_size);
832             if (!copy->priv_data) {
833                 err = AVERROR(ENOMEM);
834                 goto error;
835             }
836
837             if (codec->priv_class) {
838                 *(const AVClass **)copy->priv_data = codec->priv_class;
839                 err = av_opt_copy(copy->priv_data, src->priv_data);
840                 if (err < 0)
841                     goto error;
842             }
843         }
844
845         if (i)
846             copy->internal->is_copy = 1;
847
848         if (codec->init)
849             err = codec->init(copy);
850
851         if (err) goto error;
852
853         if (!i)
854             update_context_from_thread(avctx, copy, 1);
855
856         atomic_init(&p->debug_threads, (copy->debug & FF_DEBUG_THREADS) != 0);
857
858         err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
859         p->thread_init= !err;
860         if(!p->thread_init)
861             goto error;
862     }
863
864     return 0;
865
866 error:
867     ff_frame_thread_free(avctx, i+1);
868
869     return err;
870 }
871
872 void ff_thread_flush(AVCodecContext *avctx)
873 {
874     int i;
875     FrameThreadContext *fctx = avctx->internal->thread_ctx;
876
877     if (!fctx) return;
878
879     park_frame_worker_threads(fctx, avctx->thread_count);
880     if (fctx->prev_thread) {
881         if (fctx->prev_thread != &fctx->threads[0])
882             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
883     }
884
885     fctx->next_decoding = fctx->next_finished = 0;
886     fctx->delaying = 1;
887     fctx->prev_thread = NULL;
888     for (i = 0; i < avctx->thread_count; i++) {
889         PerThreadContext *p = &fctx->threads[i];
890         // Make sure decode flush calls with size=0 won't return old frames
891         p->got_frame = 0;
892         av_frame_unref(p->frame);
893         p->result = 0;
894
895         release_delayed_buffers(p);
896
897         if (avctx->codec->flush)
898             avctx->codec->flush(p->avctx);
899     }
900 }
901
902 int ff_thread_can_start_frame(AVCodecContext *avctx)
903 {
904     PerThreadContext *p = avctx->internal->thread_ctx;
905     if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
906         (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
907         return 0;
908     }
909     return 1;
910 }
911
912 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
913 {
914     PerThreadContext *p = avctx->internal->thread_ctx;
915     int err;
916
917     f->owner[0] = f->owner[1] = avctx;
918
919     if (!(avctx->active_thread_type & FF_THREAD_FRAME))
920         return ff_get_buffer(avctx, f->f, flags);
921
922     if (atomic_load(&p->state) != STATE_SETTING_UP &&
923         (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
924         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
925         return -1;
926     }
927
928     if (avctx->codec->caps_internal & FF_CODEC_CAP_ALLOCATE_PROGRESS) {
929         atomic_int *progress;
930         f->progress = av_buffer_alloc(2 * sizeof(*progress));
931         if (!f->progress) {
932             return AVERROR(ENOMEM);
933         }
934         progress = (atomic_int*)f->progress->data;
935
936         atomic_init(&progress[0], -1);
937         atomic_init(&progress[1], -1);
938     }
939
940     pthread_mutex_lock(&p->parent->buffer_mutex);
941     if (THREAD_SAFE_CALLBACKS(avctx)) {
942         err = ff_get_buffer(avctx, f->f, flags);
943     } else {
944         pthread_mutex_lock(&p->progress_mutex);
945         p->requested_frame = f->f;
946         p->requested_flags = flags;
947         atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
948         pthread_cond_broadcast(&p->progress_cond);
949
950         while (atomic_load(&p->state) != STATE_SETTING_UP)
951             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
952
953         err = p->result;
954
955         pthread_mutex_unlock(&p->progress_mutex);
956
957     }
958     if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
959         ff_thread_finish_setup(avctx);
960     if (err)
961         av_buffer_unref(&f->progress);
962
963     pthread_mutex_unlock(&p->parent->buffer_mutex);
964
965     return err;
966 }
967
968 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
969 {
970     enum AVPixelFormat res;
971     PerThreadContext *p = avctx->internal->thread_ctx;
972     if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
973         avctx->get_format == avcodec_default_get_format)
974         return ff_get_format(avctx, fmt);
975     if (atomic_load(&p->state) != STATE_SETTING_UP) {
976         av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
977         return -1;
978     }
979     pthread_mutex_lock(&p->progress_mutex);
980     p->available_formats = fmt;
981     atomic_store(&p->state, STATE_GET_FORMAT);
982     pthread_cond_broadcast(&p->progress_cond);
983
984     while (atomic_load(&p->state) != STATE_SETTING_UP)
985         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
986
987     res = p->result_format;
988
989     pthread_mutex_unlock(&p->progress_mutex);
990
991     return res;
992 }
993
994 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
995 {
996     int ret = thread_get_buffer_internal(avctx, f, flags);
997     if (ret < 0)
998         av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
999     return ret;
1000 }
1001
1002 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1003 {
1004     PerThreadContext *p = avctx->internal->thread_ctx;
1005     FrameThreadContext *fctx;
1006     AVFrame *dst;
1007     int ret = 0;
1008     int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1009                           THREAD_SAFE_CALLBACKS(avctx);
1010
1011     if (!f->f)
1012         return;
1013
1014     if (avctx->debug & FF_DEBUG_BUFFERS)
1015         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1016
1017     av_buffer_unref(&f->progress);
1018     f->owner[0] = f->owner[1] = NULL;
1019
1020     // when the frame buffers are not allocated, just reset it to clean state
1021     if (can_direct_free || !f->f->buf[0]) {
1022         av_frame_unref(f->f);
1023         return;
1024     }
1025
1026     fctx = p->parent;
1027     pthread_mutex_lock(&fctx->buffer_mutex);
1028
1029     if (p->num_released_buffers == p->released_buffers_allocated) {
1030         AVFrame **tmp = av_realloc_array(p->released_buffers, p->released_buffers_allocated + 1,
1031                                          sizeof(*p->released_buffers));
1032         if (tmp) {
1033             tmp[p->released_buffers_allocated] = av_frame_alloc();
1034             p->released_buffers = tmp;
1035         }
1036
1037         if (!tmp || !tmp[p->released_buffers_allocated]) {
1038             ret = AVERROR(ENOMEM);
1039             goto fail;
1040         }
1041         p->released_buffers_allocated++;
1042     }
1043
1044     dst = p->released_buffers[p->num_released_buffers];
1045     av_frame_move_ref(dst, f->f);
1046
1047     p->num_released_buffers++;
1048
1049 fail:
1050     pthread_mutex_unlock(&fctx->buffer_mutex);
1051
1052     // make sure the frame is clean even if we fail to free it
1053     // this leaks, but it is better than crashing
1054     if (ret < 0) {
1055         av_log(avctx, AV_LOG_ERROR, "Could not queue a frame for freeing, this will leak\n");
1056         memset(f->f->buf, 0, sizeof(f->f->buf));
1057         if (f->f->extended_buf)
1058             memset(f->f->extended_buf, 0, f->f->nb_extended_buf * sizeof(*f->f->extended_buf));
1059         av_frame_unref(f->f);
1060     }
1061 }