]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread_frame.c
pthread_frame: use atomics for PerThreadContext.state
[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     int *progress = f->progress ? (int*)f->progress->data : NULL;
448
449     if (!progress || progress[field] >= n) return;
450
451     p = f->owner->internal->thread_ctx;
452
453     if (f->owner->debug&FF_DEBUG_THREADS)
454         av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
455
456     pthread_mutex_lock(&p->progress_mutex);
457     progress[field] = n;
458     pthread_cond_broadcast(&p->progress_cond);
459     pthread_mutex_unlock(&p->progress_mutex);
460 }
461
462 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
463 {
464     PerThreadContext *p;
465     int *progress = f->progress ? (int*)f->progress->data : NULL;
466
467     if (!progress || progress[field] >= n) return;
468
469     p = f->owner->internal->thread_ctx;
470
471     if (f->owner->debug&FF_DEBUG_THREADS)
472         av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
473
474     pthread_mutex_lock(&p->progress_mutex);
475     while (progress[field] < n)
476         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
477     pthread_mutex_unlock(&p->progress_mutex);
478 }
479
480 void ff_thread_finish_setup(AVCodecContext *avctx) {
481     PerThreadContext *p = avctx->internal->thread_ctx;
482
483     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
484
485     pthread_mutex_lock(&p->progress_mutex);
486
487     atomic_store(&p->state, STATE_SETUP_FINISHED);
488
489     pthread_cond_broadcast(&p->progress_cond);
490     pthread_mutex_unlock(&p->progress_mutex);
491 }
492
493 /// Waits for all threads to finish.
494 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
495 {
496     int i;
497
498     for (i = 0; i < thread_count; i++) {
499         PerThreadContext *p = &fctx->threads[i];
500
501         if (atomic_load(&p->state) != STATE_INPUT_READY) {
502             pthread_mutex_lock(&p->progress_mutex);
503             while (atomic_load(&p->state) != STATE_INPUT_READY)
504                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
505             pthread_mutex_unlock(&p->progress_mutex);
506         }
507     }
508 }
509
510 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
511 {
512     FrameThreadContext *fctx = avctx->internal->thread_ctx;
513     const AVCodec *codec = avctx->codec;
514     int i;
515
516     park_frame_worker_threads(fctx, thread_count);
517
518     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
519         update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
520
521     for (i = 0; i < thread_count; i++) {
522         PerThreadContext *p = &fctx->threads[i];
523
524         pthread_mutex_lock(&p->mutex);
525         p->die = 1;
526         pthread_cond_signal(&p->input_cond);
527         pthread_mutex_unlock(&p->mutex);
528
529         if (p->thread_init)
530             pthread_join(p->thread, NULL);
531
532         if (codec->close)
533             codec->close(p->avctx);
534
535         avctx->codec = NULL;
536
537         release_delayed_buffers(p);
538         av_frame_free(&p->frame);
539     }
540
541     for (i = 0; i < thread_count; i++) {
542         PerThreadContext *p = &fctx->threads[i];
543
544         pthread_mutex_destroy(&p->mutex);
545         pthread_mutex_destroy(&p->progress_mutex);
546         pthread_cond_destroy(&p->input_cond);
547         pthread_cond_destroy(&p->progress_cond);
548         pthread_cond_destroy(&p->output_cond);
549         av_packet_unref(&p->avpkt);
550         av_freep(&p->released_buffers);
551
552         if (i) {
553             av_freep(&p->avctx->priv_data);
554             av_freep(&p->avctx->slice_offset);
555         }
556
557         av_freep(&p->avctx->internal);
558         av_freep(&p->avctx);
559     }
560
561     av_freep(&fctx->threads);
562     pthread_mutex_destroy(&fctx->buffer_mutex);
563     av_freep(&avctx->internal->thread_ctx);
564 }
565
566 int ff_frame_thread_init(AVCodecContext *avctx)
567 {
568     int thread_count = avctx->thread_count;
569     const AVCodec *codec = avctx->codec;
570     AVCodecContext *src = avctx;
571     FrameThreadContext *fctx;
572     int i, err = 0;
573
574 #if HAVE_W32THREADS
575     w32thread_init();
576 #endif
577
578     if (!thread_count) {
579         int nb_cpus = av_cpu_count();
580         av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
581         // use number of cores + 1 as thread count if there is more than one
582         if (nb_cpus > 1)
583             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
584         else
585             thread_count = avctx->thread_count = 1;
586     }
587
588     if (thread_count <= 1) {
589         avctx->active_thread_type = 0;
590         return 0;
591     }
592
593     avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
594     if (!fctx)
595         return AVERROR(ENOMEM);
596
597     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
598     if (!fctx->threads) {
599         av_freep(&avctx->internal->thread_ctx);
600         return AVERROR(ENOMEM);
601     }
602
603     pthread_mutex_init(&fctx->buffer_mutex, NULL);
604     fctx->delaying = 1;
605
606     for (i = 0; i < thread_count; i++) {
607         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
608         PerThreadContext *p  = &fctx->threads[i];
609
610         pthread_mutex_init(&p->mutex, NULL);
611         pthread_mutex_init(&p->progress_mutex, NULL);
612         pthread_cond_init(&p->input_cond, NULL);
613         pthread_cond_init(&p->progress_cond, NULL);
614         pthread_cond_init(&p->output_cond, NULL);
615
616         p->frame = av_frame_alloc();
617         if (!p->frame) {
618             av_freep(&copy);
619             err = AVERROR(ENOMEM);
620             goto error;
621         }
622
623         p->parent = fctx;
624         p->avctx  = copy;
625
626         if (!copy) {
627             err = AVERROR(ENOMEM);
628             goto error;
629         }
630
631         *copy = *src;
632
633         copy->internal = av_malloc(sizeof(AVCodecInternal));
634         if (!copy->internal) {
635             err = AVERROR(ENOMEM);
636             goto error;
637         }
638         *copy->internal = *src->internal;
639         copy->internal->thread_ctx = p;
640         copy->internal->pkt = &p->avpkt;
641
642         if (!i) {
643             src = copy;
644
645             if (codec->init)
646                 err = codec->init(copy);
647
648             update_context_from_thread(avctx, copy, 1);
649         } else {
650             copy->priv_data = av_malloc(codec->priv_data_size);
651             if (!copy->priv_data) {
652                 err = AVERROR(ENOMEM);
653                 goto error;
654             }
655             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
656             copy->internal->is_copy = 1;
657
658             if (codec->init_thread_copy)
659                 err = codec->init_thread_copy(copy);
660         }
661
662         if (err) goto error;
663
664         if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
665             p->thread_init = 1;
666     }
667
668     return 0;
669
670 error:
671     ff_frame_thread_free(avctx, i+1);
672
673     return err;
674 }
675
676 void ff_thread_flush(AVCodecContext *avctx)
677 {
678     int i;
679     FrameThreadContext *fctx = avctx->internal->thread_ctx;
680
681     if (!fctx) return;
682
683     park_frame_worker_threads(fctx, avctx->thread_count);
684     if (fctx->prev_thread) {
685         if (fctx->prev_thread != &fctx->threads[0])
686             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
687     }
688
689     fctx->next_decoding = fctx->next_finished = 0;
690     fctx->delaying = 1;
691     fctx->prev_thread = NULL;
692     for (i = 0; i < avctx->thread_count; i++) {
693         PerThreadContext *p = &fctx->threads[i];
694         // Make sure decode flush calls with size=0 won't return old frames
695         p->got_frame = 0;
696         av_frame_unref(p->frame);
697
698         release_delayed_buffers(p);
699
700         if (avctx->codec->flush)
701             avctx->codec->flush(p->avctx);
702     }
703 }
704
705 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
706 {
707     PerThreadContext *p = avctx->internal->thread_ctx;
708     int err;
709
710     f->owner = avctx;
711
712     if (!(avctx->active_thread_type & FF_THREAD_FRAME))
713         return ff_get_buffer(avctx, f->f, flags);
714
715     if (atomic_load(&p->state) != STATE_SETTING_UP &&
716         (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
717         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
718         return -1;
719     }
720
721     if (avctx->internal->allocate_progress) {
722         int *progress;
723         f->progress = av_buffer_alloc(2 * sizeof(int));
724         if (!f->progress) {
725             return AVERROR(ENOMEM);
726         }
727         progress = (int*)f->progress->data;
728
729         progress[0] = progress[1] = -1;
730     }
731
732     pthread_mutex_lock(&p->parent->buffer_mutex);
733     if (avctx->thread_safe_callbacks ||
734         avctx->get_buffer2 == avcodec_default_get_buffer2) {
735         err = ff_get_buffer(avctx, f->f, flags);
736     } else {
737         p->requested_frame = f->f;
738         p->requested_flags = flags;
739         atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
740         pthread_mutex_lock(&p->progress_mutex);
741         pthread_cond_signal(&p->progress_cond);
742
743         while (atomic_load(&p->state) != STATE_SETTING_UP)
744             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
745
746         err = p->result;
747
748         pthread_mutex_unlock(&p->progress_mutex);
749
750     }
751     if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
752         ff_thread_finish_setup(avctx);
753
754     if (err)
755         av_buffer_unref(&f->progress);
756
757     pthread_mutex_unlock(&p->parent->buffer_mutex);
758
759     return err;
760 }
761
762 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
763 {
764     PerThreadContext *p = avctx->internal->thread_ctx;
765     FrameThreadContext *fctx;
766     AVFrame *dst, *tmp;
767     int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
768                           avctx->thread_safe_callbacks                   ||
769                           avctx->get_buffer2 == avcodec_default_get_buffer2;
770
771     if (!f->f || !f->f->buf[0])
772         return;
773
774     if (avctx->debug & FF_DEBUG_BUFFERS)
775         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
776
777     av_buffer_unref(&f->progress);
778     f->owner    = NULL;
779
780     if (can_direct_free) {
781         av_frame_unref(f->f);
782         return;
783     }
784
785     fctx = p->parent;
786     pthread_mutex_lock(&fctx->buffer_mutex);
787
788     if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
789         goto fail;
790     tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
791                           (p->num_released_buffers + 1) *
792                           sizeof(*p->released_buffers));
793     if (!tmp)
794         goto fail;
795     p->released_buffers = tmp;
796
797     dst = &p->released_buffers[p->num_released_buffers];
798     av_frame_move_ref(dst, f->f);
799
800     p->num_released_buffers++;
801
802 fail:
803     pthread_mutex_unlock(&fctx->buffer_mutex);
804 }