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