]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread_frame.c
Merge commit 'd1916d13e28b87f4b1b214231149e12e1d536b4b'
[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         avcodec_get_frame_defaults(&p->frame);
152         p->got_frame = 0;
153         p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
154
155         /* many decoders assign whole AVFrames, thus overwriting extended_data;
156          * make sure it's set correctly */
157         p->frame.extended_data = p->frame.data;
158
159         if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
160
161         pthread_mutex_lock(&p->progress_mutex);
162 #if 0 //BUFREF-FIXME
163         for (i = 0; i < MAX_BUFFERS; i++)
164             if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
165                 p->progress[i][0] = INT_MAX;
166                 p->progress[i][1] = INT_MAX;
167             }
168 #endif
169         p->state = STATE_INPUT_READY;
170
171         pthread_cond_broadcast(&p->progress_cond);
172         pthread_cond_signal(&p->output_cond);
173         pthread_mutex_unlock(&p->progress_mutex);
174     }
175     pthread_mutex_unlock(&p->mutex);
176
177     return NULL;
178 }
179
180 /**
181  * Update the next thread's AVCodecContext with values from the reference thread's context.
182  *
183  * @param dst The destination context.
184  * @param src The source context.
185  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
186  */
187 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
188 {
189     int err = 0;
190
191     if (dst != src) {
192         dst->time_base = src->time_base;
193         dst->width     = src->width;
194         dst->height    = src->height;
195         dst->pix_fmt   = src->pix_fmt;
196
197         dst->coded_width  = src->coded_width;
198         dst->coded_height = src->coded_height;
199
200         dst->has_b_frames = src->has_b_frames;
201         dst->idct_algo    = src->idct_algo;
202
203         dst->bits_per_coded_sample = src->bits_per_coded_sample;
204         dst->sample_aspect_ratio   = src->sample_aspect_ratio;
205         dst->dtg_active_format     = src->dtg_active_format;
206
207         dst->profile = src->profile;
208         dst->level   = src->level;
209
210         dst->bits_per_raw_sample = src->bits_per_raw_sample;
211         dst->ticks_per_frame     = src->ticks_per_frame;
212         dst->color_primaries     = src->color_primaries;
213
214         dst->color_trc   = src->color_trc;
215         dst->colorspace  = src->colorspace;
216         dst->color_range = src->color_range;
217         dst->chroma_sample_location = src->chroma_sample_location;
218
219         dst->hwaccel = src->hwaccel;
220         dst->hwaccel_context = src->hwaccel_context;
221
222         dst->channels       = src->channels;
223         dst->sample_rate    = src->sample_rate;
224         dst->sample_fmt     = src->sample_fmt;
225         dst->channel_layout = src->channel_layout;
226     }
227
228     if (for_user) {
229         dst->delay       = src->thread_count - 1;
230         dst->coded_frame = src->coded_frame;
231     } else {
232         if (dst->codec->update_thread_context)
233             err = dst->codec->update_thread_context(dst, src);
234     }
235
236     return err;
237 }
238
239 /**
240  * Update the next thread's AVCodecContext with values set by the user.
241  *
242  * @param dst The destination context.
243  * @param src The source context.
244  * @return 0 on success, negative error code on failure
245  */
246 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
247 {
248 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
249     dst->flags          = src->flags;
250
251     dst->draw_horiz_band= src->draw_horiz_band;
252     dst->get_buffer2    = src->get_buffer2;
253 #if FF_API_GET_BUFFER
254 FF_DISABLE_DEPRECATION_WARNINGS
255     dst->get_buffer     = src->get_buffer;
256     dst->release_buffer = src->release_buffer;
257 FF_ENABLE_DEPRECATION_WARNINGS
258 #endif
259
260     dst->opaque   = src->opaque;
261     dst->debug    = src->debug;
262     dst->debug_mv = src->debug_mv;
263
264     dst->slice_flags = src->slice_flags;
265     dst->flags2      = src->flags2;
266
267     copy_fields(skip_loop_filter, subtitle_header);
268
269     dst->frame_number     = src->frame_number;
270     dst->reordered_opaque = src->reordered_opaque;
271     dst->thread_safe_callbacks = src->thread_safe_callbacks;
272
273     if (src->slice_count && src->slice_offset) {
274         if (dst->slice_count < src->slice_count) {
275             int *tmp = av_realloc(dst->slice_offset, src->slice_count *
276                                   sizeof(*dst->slice_offset));
277             if (!tmp) {
278                 av_free(dst->slice_offset);
279                 return AVERROR(ENOMEM);
280             }
281             dst->slice_offset = tmp;
282         }
283         memcpy(dst->slice_offset, src->slice_offset,
284                src->slice_count * sizeof(*dst->slice_offset));
285     }
286     dst->slice_count = src->slice_count;
287     return 0;
288 #undef copy_fields
289 }
290
291 /// Releases the buffers that this decoding thread was the last user of.
292 static void release_delayed_buffers(PerThreadContext *p)
293 {
294     FrameThreadContext *fctx = p->parent;
295
296     while (p->num_released_buffers > 0) {
297         AVFrame *f;
298
299         pthread_mutex_lock(&fctx->buffer_mutex);
300
301         // fix extended data in case the caller screwed it up
302         av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
303                    p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
304         f = &p->released_buffers[--p->num_released_buffers];
305         f->extended_data = f->data;
306         av_frame_unref(f);
307
308         pthread_mutex_unlock(&fctx->buffer_mutex);
309     }
310 }
311
312 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
313 {
314     FrameThreadContext *fctx = p->parent;
315     PerThreadContext *prev_thread = fctx->prev_thread;
316     const AVCodec *codec = p->avctx->codec;
317
318     if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
319
320     pthread_mutex_lock(&p->mutex);
321
322     release_delayed_buffers(p);
323
324     if (prev_thread) {
325         int err;
326         if (prev_thread->state == STATE_SETTING_UP) {
327             pthread_mutex_lock(&prev_thread->progress_mutex);
328             while (prev_thread->state == STATE_SETTING_UP)
329                 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
330             pthread_mutex_unlock(&prev_thread->progress_mutex);
331         }
332
333         err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
334         if (err) {
335             pthread_mutex_unlock(&p->mutex);
336             return err;
337         }
338     }
339
340     av_buffer_unref(&p->avpkt.buf);
341     p->avpkt = *avpkt;
342     if (avpkt->buf)
343         p->avpkt.buf = av_buffer_ref(avpkt->buf);
344     else {
345         av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
346         if (!p->buf) {
347             pthread_mutex_unlock(&p->mutex);
348             return AVERROR(ENOMEM);
349         }
350         p->avpkt.data = p->buf;
351         memcpy(p->buf, avpkt->data, avpkt->size);
352         memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
353     }
354
355     p->state = STATE_SETTING_UP;
356     pthread_cond_signal(&p->input_cond);
357     pthread_mutex_unlock(&p->mutex);
358
359     /*
360      * If the client doesn't have a thread-safe get_buffer(),
361      * then decoding threads call back to the main thread,
362      * and it calls back to the client here.
363      */
364
365 FF_DISABLE_DEPRECATION_WARNINGS
366     if (!p->avctx->thread_safe_callbacks && (
367          p->avctx->get_format != avcodec_default_get_format ||
368 #if FF_API_GET_BUFFER
369          p->avctx->get_buffer ||
370 #endif
371          p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
372 FF_ENABLE_DEPRECATION_WARNINGS
373         while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
374             int call_done = 1;
375             pthread_mutex_lock(&p->progress_mutex);
376             while (p->state == STATE_SETTING_UP)
377                 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
378
379             switch (p->state) {
380             case STATE_GET_BUFFER:
381                 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
382                 break;
383             case STATE_GET_FORMAT:
384                 p->result_format = p->avctx->get_format(p->avctx, p->available_formats);
385                 break;
386             default:
387                 call_done = 0;
388                 break;
389             }
390             if (call_done) {
391                 p->state  = STATE_SETTING_UP;
392                 pthread_cond_signal(&p->progress_cond);
393             }
394             pthread_mutex_unlock(&p->progress_mutex);
395         }
396     }
397
398     fctx->prev_thread = p;
399     fctx->next_decoding++;
400
401     return 0;
402 }
403
404 int ff_thread_decode_frame(AVCodecContext *avctx,
405                            AVFrame *picture, int *got_picture_ptr,
406                            AVPacket *avpkt)
407 {
408     FrameThreadContext *fctx = avctx->internal->thread_ctx;
409     int finished = fctx->next_finished;
410     PerThreadContext *p;
411     int err;
412
413     /*
414      * Submit a packet to the next decoding thread.
415      */
416
417     p = &fctx->threads[fctx->next_decoding];
418     err = update_context_from_user(p->avctx, avctx);
419     if (err) return err;
420     err = submit_packet(p, avpkt);
421     if (err) return err;
422
423     /*
424      * If we're still receiving the initial packets, don't return a frame.
425      */
426
427     if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
428         fctx->delaying = 0;
429
430     if (fctx->delaying) {
431         *got_picture_ptr=0;
432         if (avpkt->size)
433             return avpkt->size;
434     }
435
436     /*
437      * Return the next available frame from the oldest thread.
438      * If we're at the end of the stream, then we have to skip threads that
439      * didn't output a frame, because we don't want to accidentally signal
440      * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
441      */
442
443     do {
444         p = &fctx->threads[finished++];
445
446         if (p->state != STATE_INPUT_READY) {
447             pthread_mutex_lock(&p->progress_mutex);
448             while (p->state != STATE_INPUT_READY)
449                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
450             pthread_mutex_unlock(&p->progress_mutex);
451         }
452
453         av_frame_move_ref(picture, &p->frame);
454         *got_picture_ptr = p->got_frame;
455         picture->pkt_dts = p->avpkt.dts;
456
457         /*
458          * A later call with avkpt->size == 0 may loop over all threads,
459          * including this one, searching for a frame to return before being
460          * stopped by the "finished != fctx->next_finished" condition.
461          * Make sure we don't mistakenly return the same frame again.
462          */
463         p->got_frame = 0;
464
465         if (finished >= avctx->thread_count) finished = 0;
466     } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
467
468     update_context_from_thread(avctx, p->avctx, 1);
469
470     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
471
472     fctx->next_finished = finished;
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)
576             codec->close(p->avctx);
577
578         avctx->codec = NULL;
579
580         release_delayed_buffers(p);
581         av_frame_unref(&p->frame);
582     }
583
584     for (i = 0; i < thread_count; i++) {
585         PerThreadContext *p = &fctx->threads[i];
586
587         pthread_mutex_destroy(&p->mutex);
588         pthread_mutex_destroy(&p->progress_mutex);
589         pthread_cond_destroy(&p->input_cond);
590         pthread_cond_destroy(&p->progress_cond);
591         pthread_cond_destroy(&p->output_cond);
592         av_buffer_unref(&p->avpkt.buf);
593         av_freep(&p->buf);
594         av_freep(&p->released_buffers);
595
596         if (i) {
597             av_freep(&p->avctx->priv_data);
598             av_freep(&p->avctx->slice_offset);
599         }
600
601         av_freep(&p->avctx->internal);
602         av_freep(&p->avctx);
603     }
604
605     av_freep(&fctx->threads);
606     pthread_mutex_destroy(&fctx->buffer_mutex);
607     av_freep(&avctx->internal->thread_ctx);
608 }
609
610 int ff_frame_thread_init(AVCodecContext *avctx)
611 {
612     int thread_count = avctx->thread_count;
613     const AVCodec *codec = avctx->codec;
614     AVCodecContext *src = avctx;
615     FrameThreadContext *fctx;
616     int i, err = 0;
617
618 #if HAVE_W32THREADS
619     w32thread_init();
620 #endif
621
622     if (!thread_count) {
623         int nb_cpus = av_cpu_count();
624         if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
625             nb_cpus = 1;
626         // use number of cores + 1 as thread count if there is more than one
627         if (nb_cpus > 1)
628             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
629         else
630             thread_count = avctx->thread_count = 1;
631     }
632
633     if (thread_count <= 1) {
634         avctx->active_thread_type = 0;
635         return 0;
636     }
637
638     avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
639
640     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
641     pthread_mutex_init(&fctx->buffer_mutex, NULL);
642     fctx->delaying = 1;
643
644     for (i = 0; i < thread_count; i++) {
645         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
646         PerThreadContext *p  = &fctx->threads[i];
647
648         pthread_mutex_init(&p->mutex, NULL);
649         pthread_mutex_init(&p->progress_mutex, NULL);
650         pthread_cond_init(&p->input_cond, NULL);
651         pthread_cond_init(&p->progress_cond, NULL);
652         pthread_cond_init(&p->output_cond, NULL);
653
654         p->parent = fctx;
655         p->avctx  = copy;
656
657         if (!copy) {
658             err = AVERROR(ENOMEM);
659             goto error;
660         }
661
662         *copy = *src;
663
664         copy->internal = av_malloc(sizeof(AVCodecInternal));
665         if (!copy->internal) {
666             err = AVERROR(ENOMEM);
667             goto error;
668         }
669         *copy->internal = *src->internal;
670         copy->internal->thread_ctx = p;
671         copy->internal->pkt = &p->avpkt;
672
673         if (!i) {
674             src = copy;
675
676             if (codec->init)
677                 err = codec->init(copy);
678
679             update_context_from_thread(avctx, copy, 1);
680         } else {
681             copy->priv_data = av_malloc(codec->priv_data_size);
682             if (!copy->priv_data) {
683                 err = AVERROR(ENOMEM);
684                 goto error;
685             }
686             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
687             copy->internal->is_copy = 1;
688
689             if (codec->init_thread_copy)
690                 err = codec->init_thread_copy(copy);
691         }
692
693         if (err) goto error;
694
695         err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
696         p->thread_init= !err;
697         if(!p->thread_init)
698             goto error;
699     }
700
701     return 0;
702
703 error:
704     ff_frame_thread_free(avctx, i+1);
705
706     return err;
707 }
708
709 void ff_thread_flush(AVCodecContext *avctx)
710 {
711     int i;
712     FrameThreadContext *fctx = avctx->internal->thread_ctx;
713
714     if (!fctx) return;
715
716     park_frame_worker_threads(fctx, avctx->thread_count);
717     if (fctx->prev_thread) {
718         if (fctx->prev_thread != &fctx->threads[0])
719             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
720         if (avctx->codec->flush)
721             avctx->codec->flush(fctx->threads[0].avctx);
722     }
723
724     fctx->next_decoding = fctx->next_finished = 0;
725     fctx->delaying = 1;
726     fctx->prev_thread = NULL;
727     for (i = 0; i < avctx->thread_count; i++) {
728         PerThreadContext *p = &fctx->threads[i];
729         // Make sure decode flush calls with size=0 won't return old frames
730         p->got_frame = 0;
731         av_frame_unref(&p->frame);
732
733         release_delayed_buffers(p);
734     }
735 }
736
737 int ff_thread_can_start_frame(AVCodecContext *avctx)
738 {
739     PerThreadContext *p = avctx->internal->thread_ctx;
740     if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
741         (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
742         return 0;
743     }
744     return 1;
745 }
746
747 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
748 {
749     PerThreadContext *p = avctx->internal->thread_ctx;
750     int err;
751
752     f->owner = avctx;
753
754     ff_init_buffer_info(avctx, f->f);
755
756     if (!(avctx->active_thread_type & FF_THREAD_FRAME))
757         return ff_get_buffer(avctx, f->f, flags);
758
759     if (p->state != STATE_SETTING_UP &&
760         (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
761         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
762         return -1;
763     }
764
765     if (avctx->internal->allocate_progress) {
766         int *progress;
767         f->progress = av_buffer_alloc(2 * sizeof(int));
768         if (!f->progress) {
769             return AVERROR(ENOMEM);
770         }
771         progress = (int*)f->progress->data;
772
773         progress[0] = progress[1] = -1;
774     }
775
776     pthread_mutex_lock(&p->parent->buffer_mutex);
777 FF_DISABLE_DEPRECATION_WARNINGS
778     if (avctx->thread_safe_callbacks || (
779 #if FF_API_GET_BUFFER
780         !avctx->get_buffer &&
781 #endif
782         avctx->get_buffer2 == avcodec_default_get_buffer2)) {
783 FF_ENABLE_DEPRECATION_WARNINGS
784         err = ff_get_buffer(avctx, f->f, flags);
785     } else {
786         pthread_mutex_lock(&p->progress_mutex);
787         p->requested_frame = f->f;
788         p->requested_flags = flags;
789         p->state = STATE_GET_BUFFER;
790         pthread_cond_broadcast(&p->progress_cond);
791
792         while (p->state != STATE_SETTING_UP)
793             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
794
795         err = p->result;
796
797         pthread_mutex_unlock(&p->progress_mutex);
798
799     }
800     if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
801         ff_thread_finish_setup(avctx);
802
803     if (err)
804         av_buffer_unref(&f->progress);
805
806     pthread_mutex_unlock(&p->parent->buffer_mutex);
807
808     return err;
809 }
810
811 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
812 {
813     enum AVPixelFormat res;
814     PerThreadContext *p = avctx->internal->thread_ctx;
815     if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
816         avctx->get_format == avcodec_default_get_format)
817         return avctx->get_format(avctx, fmt);
818     if (p->state != STATE_SETTING_UP) {
819         av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
820         return -1;
821     }
822     pthread_mutex_lock(&p->progress_mutex);
823     p->available_formats = fmt;
824     p->state = STATE_GET_FORMAT;
825     pthread_cond_broadcast(&p->progress_cond);
826
827     while (p->state != STATE_SETTING_UP)
828         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
829
830     res = p->result_format;
831
832     pthread_mutex_unlock(&p->progress_mutex);
833
834     return res;
835 }
836
837 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
838 {
839     int ret = thread_get_buffer_internal(avctx, f, flags);
840     if (ret < 0)
841         av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
842     return ret;
843 }
844
845 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
846 {
847     PerThreadContext *p = avctx->internal->thread_ctx;
848     FrameThreadContext *fctx;
849     AVFrame *dst, *tmp;
850 FF_DISABLE_DEPRECATION_WARNINGS
851     int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
852                           avctx->thread_safe_callbacks                   ||
853                           (
854 #if FF_API_GET_BUFFER
855                            !avctx->get_buffer &&
856 #endif
857                            avctx->get_buffer2 == avcodec_default_get_buffer2);
858 FF_ENABLE_DEPRECATION_WARNINGS
859
860     if (!f->f->buf[0])
861         return;
862
863     if (avctx->debug & FF_DEBUG_BUFFERS)
864         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
865
866     av_buffer_unref(&f->progress);
867     f->owner    = NULL;
868
869     if (can_direct_free) {
870         av_frame_unref(f->f);
871         return;
872     }
873
874     fctx = p->parent;
875     pthread_mutex_lock(&fctx->buffer_mutex);
876
877     if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
878         goto fail;
879     tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
880                           (p->num_released_buffers + 1) *
881                           sizeof(*p->released_buffers));
882     if (!tmp)
883         goto fail;
884     p->released_buffers = tmp;
885
886     dst = &p->released_buffers[p->num_released_buffers];
887     av_frame_move_ref(dst, f->f);
888
889     p->num_released_buffers++;
890
891 fail:
892     pthread_mutex_unlock(&fctx->buffer_mutex);
893 }