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