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