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