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