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