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