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