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