]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread_frame.c
Merge commit 'ff7f6ea9db2a77d74f7e68a716f53ba1f3f85017'
[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  */
191 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
192 {
193     int err = 0;
194
195     if (dst != src) {
196         dst->time_base = src->time_base;
197         dst->framerate = src->framerate;
198         dst->width     = src->width;
199         dst->height    = src->height;
200         dst->pix_fmt   = src->pix_fmt;
201
202         dst->coded_width  = src->coded_width;
203         dst->coded_height = src->coded_height;
204
205         dst->has_b_frames = src->has_b_frames;
206         dst->idct_algo    = src->idct_algo;
207
208         dst->bits_per_coded_sample = src->bits_per_coded_sample;
209         dst->sample_aspect_ratio   = src->sample_aspect_ratio;
210 #if FF_API_AFD
211 FF_DISABLE_DEPRECATION_WARNINGS
212         dst->dtg_active_format     = src->dtg_active_format;
213 FF_ENABLE_DEPRECATION_WARNINGS
214 #endif /* FF_API_AFD */
215
216         dst->profile = src->profile;
217         dst->level   = src->level;
218
219         dst->bits_per_raw_sample = src->bits_per_raw_sample;
220         dst->ticks_per_frame     = src->ticks_per_frame;
221         dst->color_primaries     = src->color_primaries;
222
223         dst->color_trc   = src->color_trc;
224         dst->colorspace  = src->colorspace;
225         dst->color_range = src->color_range;
226         dst->chroma_sample_location = src->chroma_sample_location;
227
228         dst->hwaccel = src->hwaccel;
229         dst->hwaccel_context = src->hwaccel_context;
230
231         dst->channels       = src->channels;
232         dst->sample_rate    = src->sample_rate;
233         dst->sample_fmt     = src->sample_fmt;
234         dst->channel_layout = src->channel_layout;
235         dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
236     }
237
238     if (for_user) {
239         dst->delay       = src->thread_count - 1;
240 #if FF_API_CODED_FRAME
241 FF_DISABLE_DEPRECATION_WARNINGS
242         dst->coded_frame = src->coded_frame;
243 FF_ENABLE_DEPRECATION_WARNINGS
244 #endif
245     } else {
246         if (dst->codec->update_thread_context)
247             err = dst->codec->update_thread_context(dst, src);
248     }
249
250     return err;
251 }
252
253 /**
254  * Update the next thread's AVCodecContext with values set by the user.
255  *
256  * @param dst The destination context.
257  * @param src The source context.
258  * @return 0 on success, negative error code on failure
259  */
260 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
261 {
262 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
263     dst->flags          = src->flags;
264
265     dst->draw_horiz_band= src->draw_horiz_band;
266     dst->get_buffer2    = src->get_buffer2;
267
268     dst->opaque   = src->opaque;
269     dst->debug    = src->debug;
270     dst->debug_mv = src->debug_mv;
271
272     dst->slice_flags = src->slice_flags;
273     dst->flags2      = src->flags2;
274
275     copy_fields(skip_loop_filter, subtitle_header);
276
277     dst->frame_number     = src->frame_number;
278     dst->reordered_opaque = src->reordered_opaque;
279     dst->thread_safe_callbacks = src->thread_safe_callbacks;
280
281     if (src->slice_count && src->slice_offset) {
282         if (dst->slice_count < src->slice_count) {
283             int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
284                                         sizeof(*dst->slice_offset));
285             if (err < 0)
286                 return err;
287         }
288         memcpy(dst->slice_offset, src->slice_offset,
289                src->slice_count * sizeof(*dst->slice_offset));
290     }
291     dst->slice_count = src->slice_count;
292     return 0;
293 #undef copy_fields
294 }
295
296 /// Releases the buffers that this decoding thread was the last user of.
297 static void release_delayed_buffers(PerThreadContext *p)
298 {
299     FrameThreadContext *fctx = p->parent;
300
301     while (p->num_released_buffers > 0) {
302         AVFrame *f;
303
304         pthread_mutex_lock(&fctx->buffer_mutex);
305
306         // fix extended data in case the caller screwed it up
307         av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
308                    p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
309         f = &p->released_buffers[--p->num_released_buffers];
310         f->extended_data = f->data;
311         av_frame_unref(f);
312
313         pthread_mutex_unlock(&fctx->buffer_mutex);
314     }
315 }
316
317 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
318 {
319     FrameThreadContext *fctx = p->parent;
320     PerThreadContext *prev_thread = fctx->prev_thread;
321     const AVCodec *codec = p->avctx->codec;
322
323     if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
324         return 0;
325
326     pthread_mutex_lock(&p->mutex);
327
328     release_delayed_buffers(p);
329
330     if (prev_thread) {
331         int err;
332         if (prev_thread->state == STATE_SETTING_UP) {
333             pthread_mutex_lock(&prev_thread->progress_mutex);
334             while (prev_thread->state == STATE_SETTING_UP)
335                 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
336             pthread_mutex_unlock(&prev_thread->progress_mutex);
337         }
338
339         err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
340         if (err) {
341             pthread_mutex_unlock(&p->mutex);
342             return err;
343         }
344     }
345
346     av_packet_unref(&p->avpkt);
347     av_packet_ref(&p->avpkt, avpkt);
348
349     p->state = STATE_SETTING_UP;
350     pthread_cond_signal(&p->input_cond);
351     pthread_mutex_unlock(&p->mutex);
352
353     /*
354      * If the client doesn't have a thread-safe get_buffer(),
355      * then decoding threads call back to the main thread,
356      * and it calls back to the client here.
357      */
358
359     if (!p->avctx->thread_safe_callbacks && (
360          p->avctx->get_format != avcodec_default_get_format ||
361          p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
362         while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
363             int call_done = 1;
364             pthread_mutex_lock(&p->progress_mutex);
365             while (p->state == STATE_SETTING_UP)
366                 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
367
368             switch (p->state) {
369             case STATE_GET_BUFFER:
370                 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
371                 break;
372             case STATE_GET_FORMAT:
373                 p->result_format = ff_get_format(p->avctx, p->available_formats);
374                 break;
375             default:
376                 call_done = 0;
377                 break;
378             }
379             if (call_done) {
380                 p->state  = STATE_SETTING_UP;
381                 pthread_cond_signal(&p->progress_cond);
382             }
383             pthread_mutex_unlock(&p->progress_mutex);
384         }
385     }
386
387     fctx->prev_thread = p;
388     fctx->next_decoding++;
389
390     return 0;
391 }
392
393 int ff_thread_decode_frame(AVCodecContext *avctx,
394                            AVFrame *picture, int *got_picture_ptr,
395                            AVPacket *avpkt)
396 {
397     FrameThreadContext *fctx = avctx->internal->thread_ctx;
398     int finished = fctx->next_finished;
399     PerThreadContext *p;
400     int err;
401
402     /*
403      * Submit a packet to the next decoding thread.
404      */
405
406     p = &fctx->threads[fctx->next_decoding];
407     err = update_context_from_user(p->avctx, avctx);
408     if (err) return err;
409     err = submit_packet(p, avpkt);
410     if (err) return err;
411
412     /*
413      * If we're still receiving the initial packets, don't return a frame.
414      */
415
416     if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
417         fctx->delaying = 0;
418
419     if (fctx->delaying) {
420         *got_picture_ptr=0;
421         if (avpkt->size)
422             return avpkt->size;
423     }
424
425     /*
426      * Return the next available frame from the oldest thread.
427      * If we're at the end of the stream, then we have to skip threads that
428      * didn't output a frame, because we don't want to accidentally signal
429      * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
430      */
431
432     do {
433         p = &fctx->threads[finished++];
434
435         if (p->state != STATE_INPUT_READY) {
436             pthread_mutex_lock(&p->progress_mutex);
437             while (p->state != STATE_INPUT_READY)
438                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
439             pthread_mutex_unlock(&p->progress_mutex);
440         }
441
442         av_frame_move_ref(picture, p->frame);
443         *got_picture_ptr = p->got_frame;
444         picture->pkt_dts = p->avpkt.dts;
445
446         if (p->result < 0)
447             err = p->result;
448
449         /*
450          * A later call with avkpt->size == 0 may loop over all threads,
451          * including this one, searching for a frame to return before being
452          * stopped by the "finished != fctx->next_finished" condition.
453          * Make sure we don't mistakenly return the same frame again.
454          */
455         p->got_frame = 0;
456
457         if (finished >= avctx->thread_count) finished = 0;
458     } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
459
460     update_context_from_thread(avctx, p->avctx, 1);
461
462     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
463
464     fctx->next_finished = finished;
465
466     /*
467      * When no frame was found while flushing, but an error occurred in
468      * any thread, return it instead of 0.
469      * Otherwise the error can get lost.
470      */
471     if (!avpkt->size && !*got_picture_ptr)
472         return err;
473
474     /* return the size of the consumed packet if no error occurred */
475     return (p->result >= 0) ? avpkt->size : p->result;
476 }
477
478 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
479 {
480     PerThreadContext *p;
481     volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
482
483     if (!progress || progress[field] >= n) return;
484
485     p = f->owner->internal->thread_ctx;
486
487     if (f->owner->debug&FF_DEBUG_THREADS)
488         av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
489
490     pthread_mutex_lock(&p->progress_mutex);
491     progress[field] = n;
492     pthread_cond_broadcast(&p->progress_cond);
493     pthread_mutex_unlock(&p->progress_mutex);
494 }
495
496 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
497 {
498     PerThreadContext *p;
499     volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
500
501     if (!progress || progress[field] >= n) return;
502
503     p = f->owner->internal->thread_ctx;
504
505     if (f->owner->debug&FF_DEBUG_THREADS)
506         av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
507
508     pthread_mutex_lock(&p->progress_mutex);
509     while (progress[field] < n)
510         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
511     pthread_mutex_unlock(&p->progress_mutex);
512 }
513
514 void ff_thread_finish_setup(AVCodecContext *avctx) {
515     PerThreadContext *p = avctx->internal->thread_ctx;
516
517     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
518
519     if(p->state == STATE_SETUP_FINISHED){
520         av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
521     }
522
523     pthread_mutex_lock(&p->progress_mutex);
524     p->state = STATE_SETUP_FINISHED;
525     pthread_cond_broadcast(&p->progress_cond);
526     pthread_mutex_unlock(&p->progress_mutex);
527 }
528
529 /// Waits for all threads to finish.
530 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
531 {
532     int i;
533
534     for (i = 0; i < thread_count; i++) {
535         PerThreadContext *p = &fctx->threads[i];
536
537         if (p->state != STATE_INPUT_READY) {
538             pthread_mutex_lock(&p->progress_mutex);
539             while (p->state != STATE_INPUT_READY)
540                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
541             pthread_mutex_unlock(&p->progress_mutex);
542         }
543         p->got_frame = 0;
544     }
545 }
546
547 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
548 {
549     FrameThreadContext *fctx = avctx->internal->thread_ctx;
550     const AVCodec *codec = avctx->codec;
551     int i;
552
553     park_frame_worker_threads(fctx, thread_count);
554
555     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
556         if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
557             av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
558             fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
559             fctx->threads->avctx->internal->is_copy = 1;
560         }
561
562     fctx->die = 1;
563
564     for (i = 0; i < thread_count; i++) {
565         PerThreadContext *p = &fctx->threads[i];
566
567         pthread_mutex_lock(&p->mutex);
568         pthread_cond_signal(&p->input_cond);
569         pthread_mutex_unlock(&p->mutex);
570
571         if (p->thread_init)
572             pthread_join(p->thread, NULL);
573         p->thread_init=0;
574
575         if (codec->close && p->avctx)
576             codec->close(p->avctx);
577
578         release_delayed_buffers(p);
579         av_frame_free(&p->frame);
580     }
581
582     for (i = 0; i < thread_count; i++) {
583         PerThreadContext *p = &fctx->threads[i];
584
585         pthread_mutex_destroy(&p->mutex);
586         pthread_mutex_destroy(&p->progress_mutex);
587         pthread_cond_destroy(&p->input_cond);
588         pthread_cond_destroy(&p->progress_cond);
589         pthread_cond_destroy(&p->output_cond);
590         av_packet_unref(&p->avpkt);
591         av_freep(&p->released_buffers);
592
593         if (i && p->avctx) {
594             av_freep(&p->avctx->priv_data);
595             av_freep(&p->avctx->slice_offset);
596         }
597
598         if (p->avctx)
599             av_freep(&p->avctx->internal);
600         av_freep(&p->avctx);
601     }
602
603     av_freep(&fctx->threads);
604     pthread_mutex_destroy(&fctx->buffer_mutex);
605     av_freep(&avctx->internal->thread_ctx);
606
607     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
608         av_opt_free(avctx->priv_data);
609     avctx->codec = NULL;
610 }
611
612 int ff_frame_thread_init(AVCodecContext *avctx)
613 {
614     int thread_count = avctx->thread_count;
615     const AVCodec *codec = avctx->codec;
616     AVCodecContext *src = avctx;
617     FrameThreadContext *fctx;
618     int i, err = 0;
619
620 #if HAVE_W32THREADS
621     w32thread_init();
622 #endif
623
624     if (!thread_count) {
625         int nb_cpus = av_cpu_count();
626         if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
627             nb_cpus = 1;
628         // use number of cores + 1 as thread count if there is more than one
629         if (nb_cpus > 1)
630             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
631         else
632             thread_count = avctx->thread_count = 1;
633     }
634
635     if (thread_count <= 1) {
636         avctx->active_thread_type = 0;
637         return 0;
638     }
639
640     avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
641     if (!fctx)
642         return AVERROR(ENOMEM);
643
644     fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
645     if (!fctx->threads) {
646         av_freep(&avctx->internal->thread_ctx);
647         return AVERROR(ENOMEM);
648     }
649
650     pthread_mutex_init(&fctx->buffer_mutex, NULL);
651     fctx->delaying = 1;
652
653     for (i = 0; i < thread_count; i++) {
654         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
655         PerThreadContext *p  = &fctx->threads[i];
656
657         pthread_mutex_init(&p->mutex, NULL);
658         pthread_mutex_init(&p->progress_mutex, NULL);
659         pthread_cond_init(&p->input_cond, NULL);
660         pthread_cond_init(&p->progress_cond, NULL);
661         pthread_cond_init(&p->output_cond, NULL);
662
663         p->frame = av_frame_alloc();
664         if (!p->frame) {
665             av_freep(&copy);
666             err = AVERROR(ENOMEM);
667             goto error;
668         }
669
670         p->parent = fctx;
671         p->avctx  = copy;
672
673         if (!copy) {
674             err = AVERROR(ENOMEM);
675             goto error;
676         }
677
678         *copy = *src;
679
680         copy->internal = av_malloc(sizeof(AVCodecInternal));
681         if (!copy->internal) {
682             copy->priv_data = NULL;
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     if (avctx->thread_safe_callbacks ||
796         avctx->get_buffer2 == avcodec_default_get_buffer2) {
797         err = ff_get_buffer(avctx, f->f, flags);
798     } else {
799         pthread_mutex_lock(&p->progress_mutex);
800         p->requested_frame = f->f;
801         p->requested_flags = flags;
802         p->state = STATE_GET_BUFFER;
803         pthread_cond_broadcast(&p->progress_cond);
804
805         while (p->state != STATE_SETTING_UP)
806             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
807
808         err = p->result;
809
810         pthread_mutex_unlock(&p->progress_mutex);
811
812     }
813     if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
814         ff_thread_finish_setup(avctx);
815     if (err)
816         av_buffer_unref(&f->progress);
817
818     pthread_mutex_unlock(&p->parent->buffer_mutex);
819
820     return err;
821 }
822
823 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
824 {
825     enum AVPixelFormat res;
826     PerThreadContext *p = avctx->internal->thread_ctx;
827     if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
828         avctx->get_format == avcodec_default_get_format)
829         return ff_get_format(avctx, fmt);
830     if (p->state != STATE_SETTING_UP) {
831         av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
832         return -1;
833     }
834     pthread_mutex_lock(&p->progress_mutex);
835     p->available_formats = fmt;
836     p->state = STATE_GET_FORMAT;
837     pthread_cond_broadcast(&p->progress_cond);
838
839     while (p->state != STATE_SETTING_UP)
840         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
841
842     res = p->result_format;
843
844     pthread_mutex_unlock(&p->progress_mutex);
845
846     return res;
847 }
848
849 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
850 {
851     int ret = thread_get_buffer_internal(avctx, f, flags);
852     if (ret < 0)
853         av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
854     return ret;
855 }
856
857 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
858 {
859     PerThreadContext *p = avctx->internal->thread_ctx;
860     FrameThreadContext *fctx;
861     AVFrame *dst, *tmp;
862     int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
863                           avctx->thread_safe_callbacks                   ||
864                           avctx->get_buffer2 == avcodec_default_get_buffer2;
865
866     if (!f->f || !f->f->buf[0])
867         return;
868
869     if (avctx->debug & FF_DEBUG_BUFFERS)
870         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
871
872     av_buffer_unref(&f->progress);
873     f->owner    = NULL;
874
875     if (can_direct_free) {
876         av_frame_unref(f->f);
877         return;
878     }
879
880     fctx = p->parent;
881     pthread_mutex_lock(&fctx->buffer_mutex);
882
883     if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
884         goto fail;
885     tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
886                           (p->num_released_buffers + 1) *
887                           sizeof(*p->released_buffers));
888     if (!tmp)
889         goto fail;
890     p->released_buffers = tmp;
891
892     dst = &p->released_buffers[p->num_released_buffers];
893     av_frame_move_ref(dst, f->f);
894
895     p->num_released_buffers++;
896
897 fail:
898     pthread_mutex_unlock(&fctx->buffer_mutex);
899 }