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