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