]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread.c
indeo4: Check the inherited quant_mat
[ffmpeg] / libavcodec / pthread.c
1 /*
2  * Copyright (c) 2004 Roman Shaposhnik
3  * Copyright (c) 2008 Alexander Strange (astrange@ithinksw.com)
4  *
5  * Many thanks to Steven M. Schultz for providing clever ideas and
6  * to Michael Niedermayer <michaelni@gmx.at> for writing initial
7  * implementation.
8  *
9  * This file is part of Libav.
10  *
11  * Libav is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * Libav is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with Libav; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24  */
25
26 /**
27  * @file
28  * Multithreading support functions
29  * @see doc/multithreading.txt
30  */
31
32 #include "config.h"
33
34 #include "avcodec.h"
35 #include "internal.h"
36 #include "thread.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/common.h"
39 #include "libavutil/cpu.h"
40 #include "libavutil/internal.h"
41
42 #if HAVE_PTHREADS
43 #include <pthread.h>
44 #elif HAVE_W32THREADS
45 #include "compat/w32pthreads.h"
46 #endif
47
48 typedef int (action_func)(AVCodecContext *c, void *arg);
49 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
50
51 typedef struct ThreadContext {
52     pthread_t *workers;
53     action_func *func;
54     action_func2 *func2;
55     void *args;
56     int *rets;
57     int rets_count;
58     int job_count;
59     int job_size;
60
61     pthread_cond_t last_job_cond;
62     pthread_cond_t current_job_cond;
63     pthread_mutex_t current_job_lock;
64     int current_job;
65     int done;
66 } ThreadContext;
67
68 /**
69  * Context used by codec threads and stored in their AVCodecContext thread_opaque.
70  */
71 typedef struct PerThreadContext {
72     struct FrameThreadContext *parent;
73
74     pthread_t      thread;
75     int            thread_init;
76     pthread_cond_t input_cond;      ///< Used to wait for a new packet from the main thread.
77     pthread_cond_t progress_cond;   ///< Used by child threads to wait for progress to change.
78     pthread_cond_t output_cond;     ///< Used by the main thread to wait for frames to finish.
79
80     pthread_mutex_t mutex;          ///< Mutex used to protect the contents of the PerThreadContext.
81     pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
82
83     AVCodecContext *avctx;          ///< Context used to decode packets passed to this thread.
84
85     AVPacket       avpkt;           ///< Input packet (for decoding) or output (for encoding).
86     uint8_t       *buf;             ///< backup storage for packet data when the input packet is not refcounted
87     int            allocated_buf_size; ///< Size allocated for buf
88
89     AVFrame frame;                  ///< Output frame (for decoding) or input (for encoding).
90     int     got_frame;              ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
91     int     result;                 ///< The result of the last codec decode/encode() call.
92
93     enum {
94         STATE_INPUT_READY,          ///< Set when the thread is awaiting a packet.
95         STATE_SETTING_UP,           ///< Set before the codec has called ff_thread_finish_setup().
96         STATE_GET_BUFFER,           /**<
97                                      * Set when the codec calls get_buffer().
98                                      * State is returned to STATE_SETTING_UP afterwards.
99                                      */
100         STATE_SETUP_FINISHED        ///< Set after the codec has called ff_thread_finish_setup().
101     } state;
102
103     /**
104      * Array of frames passed to ff_thread_release_buffer().
105      * Frames are released after all threads referencing them are finished.
106      */
107     AVFrame *released_buffers;
108     int  num_released_buffers;
109     int      released_buffers_allocated;
110
111     AVFrame *requested_frame;       ///< AVFrame the codec passed to get_buffer()
112     int      requested_flags;       ///< flags passed to get_buffer() for requested_frame
113 } PerThreadContext;
114
115 /**
116  * Context stored in the client AVCodecContext thread_opaque.
117  */
118 typedef struct FrameThreadContext {
119     PerThreadContext *threads;     ///< The contexts for each thread.
120     PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
121
122     pthread_mutex_t buffer_mutex;  ///< Mutex used to protect get/release_buffer().
123
124     int next_decoding;             ///< The next context to submit a packet to.
125     int next_finished;             ///< The next context to return output from.
126
127     int delaying;                  /**<
128                                     * Set for the first N packets, where N is the number of threads.
129                                     * While it is set, ff_thread_en/decode_frame won't return any results.
130                                     */
131
132     int die;                       ///< Set when threads should exit.
133 } FrameThreadContext;
134
135
136 /* H264 slice threading seems to be buggy with more than 16 threads,
137  * limit the number of threads to 16 for automatic detection */
138 #define MAX_AUTO_THREADS 16
139
140 static void* attribute_align_arg worker(void *v)
141 {
142     AVCodecContext *avctx = v;
143     ThreadContext *c = avctx->thread_opaque;
144     int our_job = c->job_count;
145     int thread_count = avctx->thread_count;
146     int self_id;
147
148     pthread_mutex_lock(&c->current_job_lock);
149     self_id = c->current_job++;
150     for (;;){
151         while (our_job >= c->job_count) {
152             if (c->current_job == thread_count + c->job_count)
153                 pthread_cond_signal(&c->last_job_cond);
154
155             pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
156             our_job = self_id;
157
158             if (c->done) {
159                 pthread_mutex_unlock(&c->current_job_lock);
160                 return NULL;
161             }
162         }
163         pthread_mutex_unlock(&c->current_job_lock);
164
165         c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
166                                                    c->func2(avctx, c->args, our_job, self_id);
167
168         pthread_mutex_lock(&c->current_job_lock);
169         our_job = c->current_job++;
170     }
171 }
172
173 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
174 {
175     pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
176     pthread_mutex_unlock(&c->current_job_lock);
177 }
178
179 static void thread_free(AVCodecContext *avctx)
180 {
181     ThreadContext *c = avctx->thread_opaque;
182     int i;
183
184     pthread_mutex_lock(&c->current_job_lock);
185     c->done = 1;
186     pthread_cond_broadcast(&c->current_job_cond);
187     pthread_mutex_unlock(&c->current_job_lock);
188
189     for (i=0; i<avctx->thread_count; i++)
190          pthread_join(c->workers[i], NULL);
191
192     pthread_mutex_destroy(&c->current_job_lock);
193     pthread_cond_destroy(&c->current_job_cond);
194     pthread_cond_destroy(&c->last_job_cond);
195     av_free(c->workers);
196     av_freep(&avctx->thread_opaque);
197 }
198
199 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
200 {
201     ThreadContext *c= avctx->thread_opaque;
202     int dummy_ret;
203
204     if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
205         return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
206
207     if (job_count <= 0)
208         return 0;
209
210     pthread_mutex_lock(&c->current_job_lock);
211
212     c->current_job = avctx->thread_count;
213     c->job_count = job_count;
214     c->job_size = job_size;
215     c->args = arg;
216     c->func = func;
217     if (ret) {
218         c->rets = ret;
219         c->rets_count = job_count;
220     } else {
221         c->rets = &dummy_ret;
222         c->rets_count = 1;
223     }
224     pthread_cond_broadcast(&c->current_job_cond);
225
226     avcodec_thread_park_workers(c, avctx->thread_count);
227
228     return 0;
229 }
230
231 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
232 {
233     ThreadContext *c= avctx->thread_opaque;
234     c->func2 = func2;
235     return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
236 }
237
238 static int thread_init_internal(AVCodecContext *avctx)
239 {
240     int i;
241     ThreadContext *c;
242     int thread_count = avctx->thread_count;
243
244     if (!thread_count) {
245         int nb_cpus = av_cpu_count();
246         av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
247         // use number of cores + 1 as thread count if there is more than one
248         if (nb_cpus > 1)
249             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
250         else
251             thread_count = avctx->thread_count = 1;
252     }
253
254     if (thread_count <= 1) {
255         avctx->active_thread_type = 0;
256         return 0;
257     }
258
259     c = av_mallocz(sizeof(ThreadContext));
260     if (!c)
261         return -1;
262
263     c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
264     if (!c->workers) {
265         av_free(c);
266         return -1;
267     }
268
269     avctx->thread_opaque = c;
270     c->current_job = 0;
271     c->job_count = 0;
272     c->job_size = 0;
273     c->done = 0;
274     pthread_cond_init(&c->current_job_cond, NULL);
275     pthread_cond_init(&c->last_job_cond, NULL);
276     pthread_mutex_init(&c->current_job_lock, NULL);
277     pthread_mutex_lock(&c->current_job_lock);
278     for (i=0; i<thread_count; i++) {
279         if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
280            avctx->thread_count = i;
281            pthread_mutex_unlock(&c->current_job_lock);
282            ff_thread_free(avctx);
283            return -1;
284         }
285     }
286
287     avcodec_thread_park_workers(c, thread_count);
288
289     avctx->execute = avcodec_thread_execute;
290     avctx->execute2 = avcodec_thread_execute2;
291     return 0;
292 }
293
294 /**
295  * Codec worker thread.
296  *
297  * Automatically calls ff_thread_finish_setup() if the codec does
298  * not provide an update_thread_context method, or if the codec returns
299  * before calling it.
300  */
301 static attribute_align_arg void *frame_worker_thread(void *arg)
302 {
303     PerThreadContext *p = arg;
304     FrameThreadContext *fctx = p->parent;
305     AVCodecContext *avctx = p->avctx;
306     const AVCodec *codec = avctx->codec;
307
308     while (1) {
309         if (p->state == STATE_INPUT_READY && !fctx->die) {
310             pthread_mutex_lock(&p->mutex);
311             while (p->state == STATE_INPUT_READY && !fctx->die)
312                 pthread_cond_wait(&p->input_cond, &p->mutex);
313             pthread_mutex_unlock(&p->mutex);
314         }
315
316         if (fctx->die) break;
317
318         if (!codec->update_thread_context && avctx->thread_safe_callbacks)
319             ff_thread_finish_setup(avctx);
320
321         pthread_mutex_lock(&p->mutex);
322         avcodec_get_frame_defaults(&p->frame);
323         p->got_frame = 0;
324         p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
325
326         /* many decoders assign whole AVFrames, thus overwriting extended_data;
327          * make sure it's set correctly */
328         p->frame.extended_data = p->frame.data;
329
330         if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
331
332         p->state = STATE_INPUT_READY;
333
334         pthread_mutex_lock(&p->progress_mutex);
335         pthread_cond_signal(&p->output_cond);
336         pthread_mutex_unlock(&p->progress_mutex);
337
338         pthread_mutex_unlock(&p->mutex);
339     }
340
341     return NULL;
342 }
343
344 /**
345  * Update the next thread's AVCodecContext with values from the reference thread's context.
346  *
347  * @param dst The destination context.
348  * @param src The source context.
349  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
350  */
351 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
352 {
353     int err = 0;
354
355     if (dst != src) {
356         dst->time_base = src->time_base;
357         dst->width     = src->width;
358         dst->height    = src->height;
359         dst->pix_fmt   = src->pix_fmt;
360
361         dst->coded_width  = src->coded_width;
362         dst->coded_height = src->coded_height;
363
364         dst->has_b_frames = src->has_b_frames;
365         dst->idct_algo    = src->idct_algo;
366
367         dst->bits_per_coded_sample = src->bits_per_coded_sample;
368         dst->sample_aspect_ratio   = src->sample_aspect_ratio;
369         dst->dtg_active_format     = src->dtg_active_format;
370
371         dst->profile = src->profile;
372         dst->level   = src->level;
373
374         dst->bits_per_raw_sample = src->bits_per_raw_sample;
375         dst->ticks_per_frame     = src->ticks_per_frame;
376         dst->color_primaries     = src->color_primaries;
377
378         dst->color_trc   = src->color_trc;
379         dst->colorspace  = src->colorspace;
380         dst->color_range = src->color_range;
381         dst->chroma_sample_location = src->chroma_sample_location;
382
383         dst->hwaccel = src->hwaccel;
384         dst->hwaccel_context = src->hwaccel_context;
385     }
386
387     if (for_user) {
388         dst->coded_frame = src->coded_frame;
389     } else {
390         if (dst->codec->update_thread_context)
391             err = dst->codec->update_thread_context(dst, src);
392     }
393
394     return err;
395 }
396
397 /**
398  * Update the next thread's AVCodecContext with values set by the user.
399  *
400  * @param dst The destination context.
401  * @param src The source context.
402  * @return 0 on success, negative error code on failure
403  */
404 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
405 {
406 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
407     dst->flags          = src->flags;
408
409     dst->draw_horiz_band= src->draw_horiz_band;
410     dst->get_buffer2    = src->get_buffer2;
411 #if FF_API_GET_BUFFER
412 FF_DISABLE_DEPRECATION_WARNINGS
413     dst->get_buffer     = src->get_buffer;
414     dst->release_buffer = src->release_buffer;
415 FF_ENABLE_DEPRECATION_WARNINGS
416 #endif
417
418     dst->opaque   = src->opaque;
419     dst->debug    = src->debug;
420     dst->debug_mv = src->debug_mv;
421
422     dst->slice_flags = src->slice_flags;
423     dst->flags2      = src->flags2;
424
425     copy_fields(skip_loop_filter, subtitle_header);
426
427     dst->frame_number     = src->frame_number;
428     dst->reordered_opaque = src->reordered_opaque;
429
430     if (src->slice_count && src->slice_offset) {
431         if (dst->slice_count < src->slice_count) {
432             int *tmp = av_realloc(dst->slice_offset, src->slice_count *
433                                   sizeof(*dst->slice_offset));
434             if (!tmp) {
435                 av_free(dst->slice_offset);
436                 return AVERROR(ENOMEM);
437             }
438             dst->slice_offset = tmp;
439         }
440         memcpy(dst->slice_offset, src->slice_offset,
441                src->slice_count * sizeof(*dst->slice_offset));
442     }
443     dst->slice_count = src->slice_count;
444     return 0;
445 #undef copy_fields
446 }
447
448 /// Releases the buffers that this decoding thread was the last user of.
449 static void release_delayed_buffers(PerThreadContext *p)
450 {
451     FrameThreadContext *fctx = p->parent;
452
453     while (p->num_released_buffers > 0) {
454         AVFrame *f;
455
456         pthread_mutex_lock(&fctx->buffer_mutex);
457
458         // fix extended data in case the caller screwed it up
459         av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
460         f = &p->released_buffers[--p->num_released_buffers];
461         f->extended_data = f->data;
462         av_frame_unref(f);
463
464         pthread_mutex_unlock(&fctx->buffer_mutex);
465     }
466 }
467
468 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
469 {
470     FrameThreadContext *fctx = p->parent;
471     PerThreadContext *prev_thread = fctx->prev_thread;
472     const AVCodec *codec = p->avctx->codec;
473
474     if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
475
476     pthread_mutex_lock(&p->mutex);
477
478     release_delayed_buffers(p);
479
480     if (prev_thread) {
481         int err;
482         if (prev_thread->state == STATE_SETTING_UP) {
483             pthread_mutex_lock(&prev_thread->progress_mutex);
484             while (prev_thread->state == STATE_SETTING_UP)
485                 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
486             pthread_mutex_unlock(&prev_thread->progress_mutex);
487         }
488
489         err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
490         if (err) {
491             pthread_mutex_unlock(&p->mutex);
492             return err;
493         }
494     }
495
496     av_buffer_unref(&p->avpkt.buf);
497     p->avpkt = *avpkt;
498     if (avpkt->buf)
499         p->avpkt.buf = av_buffer_ref(avpkt->buf);
500     else {
501         av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
502         p->avpkt.data = p->buf;
503         memcpy(p->buf, avpkt->data, avpkt->size);
504         memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
505     }
506
507     p->state = STATE_SETTING_UP;
508     pthread_cond_signal(&p->input_cond);
509     pthread_mutex_unlock(&p->mutex);
510
511     /*
512      * If the client doesn't have a thread-safe get_buffer(),
513      * then decoding threads call back to the main thread,
514      * and it calls back to the client here.
515      */
516
517 FF_DISABLE_DEPRECATION_WARNINGS
518     if (!p->avctx->thread_safe_callbacks && (
519 #if FF_API_GET_BUFFER
520          p->avctx->get_buffer ||
521 #endif
522          p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
523 FF_ENABLE_DEPRECATION_WARNINGS
524         while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
525             pthread_mutex_lock(&p->progress_mutex);
526             while (p->state == STATE_SETTING_UP)
527                 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
528
529             if (p->state == STATE_GET_BUFFER) {
530                 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
531                 p->state  = STATE_SETTING_UP;
532                 pthread_cond_signal(&p->progress_cond);
533             }
534             pthread_mutex_unlock(&p->progress_mutex);
535         }
536     }
537
538     fctx->prev_thread = p;
539     fctx->next_decoding++;
540
541     return 0;
542 }
543
544 int ff_thread_decode_frame(AVCodecContext *avctx,
545                            AVFrame *picture, int *got_picture_ptr,
546                            AVPacket *avpkt)
547 {
548     FrameThreadContext *fctx = avctx->thread_opaque;
549     int finished = fctx->next_finished;
550     PerThreadContext *p;
551     int err;
552
553     /*
554      * Submit a packet to the next decoding thread.
555      */
556
557     p = &fctx->threads[fctx->next_decoding];
558     err = update_context_from_user(p->avctx, avctx);
559     if (err) return err;
560     err = submit_packet(p, avpkt);
561     if (err) return err;
562
563     /*
564      * If we're still receiving the initial packets, don't return a frame.
565      */
566
567     if (fctx->delaying) {
568         if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
569
570         *got_picture_ptr=0;
571         if (avpkt->size)
572             return avpkt->size;
573     }
574
575     /*
576      * Return the next available frame from the oldest thread.
577      * If we're at the end of the stream, then we have to skip threads that
578      * didn't output a frame, because we don't want to accidentally signal
579      * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
580      */
581
582     do {
583         p = &fctx->threads[finished++];
584
585         if (p->state != STATE_INPUT_READY) {
586             pthread_mutex_lock(&p->progress_mutex);
587             while (p->state != STATE_INPUT_READY)
588                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
589             pthread_mutex_unlock(&p->progress_mutex);
590         }
591
592         av_frame_move_ref(picture, &p->frame);
593         *got_picture_ptr = p->got_frame;
594         picture->pkt_dts = p->avpkt.dts;
595
596         /*
597          * A later call with avkpt->size == 0 may loop over all threads,
598          * including this one, searching for a frame to return before being
599          * stopped by the "finished != fctx->next_finished" condition.
600          * Make sure we don't mistakenly return the same frame again.
601          */
602         p->got_frame = 0;
603
604         if (finished >= avctx->thread_count) finished = 0;
605     } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
606
607     update_context_from_thread(avctx, p->avctx, 1);
608
609     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
610
611     fctx->next_finished = finished;
612
613     /* return the size of the consumed packet if no error occurred */
614     return (p->result >= 0) ? avpkt->size : p->result;
615 }
616
617 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
618 {
619     PerThreadContext *p;
620     int *progress = f->progress ? (int*)f->progress->data : NULL;
621
622     if (!progress || progress[field] >= n) return;
623
624     p = f->owner->thread_opaque;
625
626     if (f->owner->debug&FF_DEBUG_THREADS)
627         av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
628
629     pthread_mutex_lock(&p->progress_mutex);
630     progress[field] = n;
631     pthread_cond_broadcast(&p->progress_cond);
632     pthread_mutex_unlock(&p->progress_mutex);
633 }
634
635 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
636 {
637     PerThreadContext *p;
638     int *progress = f->progress ? (int*)f->progress->data : NULL;
639
640     if (!progress || progress[field] >= n) return;
641
642     p = f->owner->thread_opaque;
643
644     if (f->owner->debug&FF_DEBUG_THREADS)
645         av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
646
647     pthread_mutex_lock(&p->progress_mutex);
648     while (progress[field] < n)
649         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
650     pthread_mutex_unlock(&p->progress_mutex);
651 }
652
653 void ff_thread_finish_setup(AVCodecContext *avctx) {
654     PerThreadContext *p = avctx->thread_opaque;
655
656     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
657
658     pthread_mutex_lock(&p->progress_mutex);
659     p->state = STATE_SETUP_FINISHED;
660     pthread_cond_broadcast(&p->progress_cond);
661     pthread_mutex_unlock(&p->progress_mutex);
662 }
663
664 /// Waits for all threads to finish.
665 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
666 {
667     int i;
668
669     for (i = 0; i < thread_count; i++) {
670         PerThreadContext *p = &fctx->threads[i];
671
672         if (p->state != STATE_INPUT_READY) {
673             pthread_mutex_lock(&p->progress_mutex);
674             while (p->state != STATE_INPUT_READY)
675                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
676             pthread_mutex_unlock(&p->progress_mutex);
677         }
678     }
679 }
680
681 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
682 {
683     FrameThreadContext *fctx = avctx->thread_opaque;
684     const AVCodec *codec = avctx->codec;
685     int i;
686
687     park_frame_worker_threads(fctx, thread_count);
688
689     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
690         update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
691
692     fctx->die = 1;
693
694     for (i = 0; i < thread_count; i++) {
695         PerThreadContext *p = &fctx->threads[i];
696
697         pthread_mutex_lock(&p->mutex);
698         pthread_cond_signal(&p->input_cond);
699         pthread_mutex_unlock(&p->mutex);
700
701         if (p->thread_init)
702             pthread_join(p->thread, NULL);
703
704         if (codec->close)
705             codec->close(p->avctx);
706
707         avctx->codec = NULL;
708
709         release_delayed_buffers(p);
710         av_frame_unref(&p->frame);
711     }
712
713     for (i = 0; i < thread_count; i++) {
714         PerThreadContext *p = &fctx->threads[i];
715
716         pthread_mutex_destroy(&p->mutex);
717         pthread_mutex_destroy(&p->progress_mutex);
718         pthread_cond_destroy(&p->input_cond);
719         pthread_cond_destroy(&p->progress_cond);
720         pthread_cond_destroy(&p->output_cond);
721         av_buffer_unref(&p->avpkt.buf);
722         av_freep(&p->buf);
723         av_freep(&p->released_buffers);
724
725         if (i) {
726             av_freep(&p->avctx->priv_data);
727             av_freep(&p->avctx->internal);
728             av_freep(&p->avctx->slice_offset);
729         }
730
731         av_freep(&p->avctx);
732     }
733
734     av_freep(&fctx->threads);
735     pthread_mutex_destroy(&fctx->buffer_mutex);
736     av_freep(&avctx->thread_opaque);
737 }
738
739 static int frame_thread_init(AVCodecContext *avctx)
740 {
741     int thread_count = avctx->thread_count;
742     const AVCodec *codec = avctx->codec;
743     AVCodecContext *src = avctx;
744     FrameThreadContext *fctx;
745     int i, err = 0;
746
747     if (!thread_count) {
748         int nb_cpus = av_cpu_count();
749         av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
750         // use number of cores + 1 as thread count if there is more than one
751         if (nb_cpus > 1)
752             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
753         else
754             thread_count = avctx->thread_count = 1;
755     }
756
757     if (thread_count <= 1) {
758         avctx->active_thread_type = 0;
759         return 0;
760     }
761
762     avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
763
764     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
765     pthread_mutex_init(&fctx->buffer_mutex, NULL);
766     fctx->delaying = 1;
767
768     for (i = 0; i < thread_count; i++) {
769         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
770         PerThreadContext *p  = &fctx->threads[i];
771
772         pthread_mutex_init(&p->mutex, NULL);
773         pthread_mutex_init(&p->progress_mutex, NULL);
774         pthread_cond_init(&p->input_cond, NULL);
775         pthread_cond_init(&p->progress_cond, NULL);
776         pthread_cond_init(&p->output_cond, NULL);
777
778         p->parent = fctx;
779         p->avctx  = copy;
780
781         if (!copy) {
782             err = AVERROR(ENOMEM);
783             goto error;
784         }
785
786         *copy = *src;
787         copy->thread_opaque = p;
788         copy->pkt = &p->avpkt;
789
790         if (!i) {
791             src = copy;
792
793             if (codec->init)
794                 err = codec->init(copy);
795
796             update_context_from_thread(avctx, copy, 1);
797         } else {
798             copy->priv_data = av_malloc(codec->priv_data_size);
799             if (!copy->priv_data) {
800                 err = AVERROR(ENOMEM);
801                 goto error;
802             }
803             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
804             copy->internal = av_malloc(sizeof(AVCodecInternal));
805             if (!copy->internal) {
806                 err = AVERROR(ENOMEM);
807                 goto error;
808             }
809             *copy->internal = *src->internal;
810             copy->internal->is_copy = 1;
811
812             if (codec->init_thread_copy)
813                 err = codec->init_thread_copy(copy);
814         }
815
816         if (err) goto error;
817
818         if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
819             p->thread_init = 1;
820     }
821
822     return 0;
823
824 error:
825     frame_thread_free(avctx, i+1);
826
827     return err;
828 }
829
830 void ff_thread_flush(AVCodecContext *avctx)
831 {
832     int i;
833     FrameThreadContext *fctx = avctx->thread_opaque;
834
835     if (!avctx->thread_opaque) return;
836
837     park_frame_worker_threads(fctx, avctx->thread_count);
838     if (fctx->prev_thread) {
839         if (fctx->prev_thread != &fctx->threads[0])
840             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
841         if (avctx->codec->flush)
842             avctx->codec->flush(fctx->threads[0].avctx);
843     }
844
845     fctx->next_decoding = fctx->next_finished = 0;
846     fctx->delaying = 1;
847     fctx->prev_thread = NULL;
848     for (i = 0; i < avctx->thread_count; i++) {
849         PerThreadContext *p = &fctx->threads[i];
850         // Make sure decode flush calls with size=0 won't return old frames
851         p->got_frame = 0;
852         av_frame_unref(&p->frame);
853
854         release_delayed_buffers(p);
855     }
856 }
857
858 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
859 {
860     PerThreadContext *p = avctx->thread_opaque;
861     int err;
862
863     f->owner = avctx;
864
865     if (!(avctx->active_thread_type & FF_THREAD_FRAME))
866         return ff_get_buffer(avctx, f->f, flags);
867
868     if (p->state != STATE_SETTING_UP &&
869         (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
870         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
871         return -1;
872     }
873
874     if (avctx->internal->allocate_progress) {
875         int *progress;
876         f->progress = av_buffer_alloc(2 * sizeof(int));
877         if (!f->progress) {
878             return AVERROR(ENOMEM);
879         }
880         progress = (int*)f->progress->data;
881
882         progress[0] = progress[1] = -1;
883     }
884
885     pthread_mutex_lock(&p->parent->buffer_mutex);
886 FF_DISABLE_DEPRECATION_WARNINGS
887     if (avctx->thread_safe_callbacks || (
888 #if FF_API_GET_BUFFER
889         !avctx->get_buffer &&
890 #endif
891         avctx->get_buffer2 == avcodec_default_get_buffer2)) {
892 FF_ENABLE_DEPRECATION_WARNINGS
893         err = ff_get_buffer(avctx, f->f, flags);
894     } else {
895         p->requested_frame = f->f;
896         p->requested_flags = flags;
897         p->state = STATE_GET_BUFFER;
898         pthread_mutex_lock(&p->progress_mutex);
899         pthread_cond_signal(&p->progress_cond);
900
901         while (p->state != STATE_SETTING_UP)
902             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
903
904         err = p->result;
905
906         pthread_mutex_unlock(&p->progress_mutex);
907
908     }
909     if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
910         ff_thread_finish_setup(avctx);
911
912     if (err)
913         av_buffer_unref(&f->progress);
914
915     pthread_mutex_unlock(&p->parent->buffer_mutex);
916
917     return err;
918 }
919
920 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
921 {
922     PerThreadContext *p = avctx->thread_opaque;
923     FrameThreadContext *fctx;
924     AVFrame *dst, *tmp;
925 FF_DISABLE_DEPRECATION_WARNINGS
926     int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
927                           avctx->thread_safe_callbacks                   ||
928                           (
929 #if FF_API_GET_BUFFER
930                            !avctx->get_buffer &&
931 #endif
932                            avctx->get_buffer2 == avcodec_default_get_buffer2);
933 FF_ENABLE_DEPRECATION_WARNINGS
934
935     if (!f->f->data[0])
936         return;
937
938     if (avctx->debug & FF_DEBUG_BUFFERS)
939         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
940
941     av_buffer_unref(&f->progress);
942     f->owner    = NULL;
943
944     if (can_direct_free) {
945         av_frame_unref(f->f);
946         return;
947     }
948
949     fctx = p->parent;
950     pthread_mutex_lock(&fctx->buffer_mutex);
951
952     if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
953         goto fail;
954     tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
955                           (p->num_released_buffers + 1) *
956                           sizeof(*p->released_buffers));
957     if (!tmp)
958         goto fail;
959     p->released_buffers = tmp;
960
961     dst = &p->released_buffers[p->num_released_buffers];
962     av_frame_move_ref(dst, f->f);
963
964     p->num_released_buffers++;
965
966 fail:
967     pthread_mutex_unlock(&fctx->buffer_mutex);
968 }
969
970 /**
971  * Set the threading algorithms used.
972  *
973  * Threading requires more than one thread.
974  * Frame threading requires entire frames to be passed to the codec,
975  * and introduces extra decoding delay, so is incompatible with low_delay.
976  *
977  * @param avctx The context.
978  */
979 static void validate_thread_parameters(AVCodecContext *avctx)
980 {
981     int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
982                                 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
983                                 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
984                                 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
985     if (avctx->thread_count == 1) {
986         avctx->active_thread_type = 0;
987     } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
988         avctx->active_thread_type = FF_THREAD_FRAME;
989     } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
990                avctx->thread_type & FF_THREAD_SLICE) {
991         avctx->active_thread_type = FF_THREAD_SLICE;
992     } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
993         avctx->thread_count       = 1;
994         avctx->active_thread_type = 0;
995     }
996
997     if (avctx->thread_count > MAX_AUTO_THREADS)
998         av_log(avctx, AV_LOG_WARNING,
999                "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1000                avctx->thread_count, MAX_AUTO_THREADS);
1001 }
1002
1003 int ff_thread_init(AVCodecContext *avctx)
1004 {
1005 #if HAVE_W32THREADS
1006     w32thread_init();
1007 #endif
1008
1009     validate_thread_parameters(avctx);
1010
1011     if (avctx->active_thread_type&FF_THREAD_SLICE)
1012         return thread_init_internal(avctx);
1013     else if (avctx->active_thread_type&FF_THREAD_FRAME)
1014         return frame_thread_init(avctx);
1015
1016     return 0;
1017 }
1018
1019 void ff_thread_free(AVCodecContext *avctx)
1020 {
1021     if (avctx->active_thread_type&FF_THREAD_FRAME)
1022         frame_thread_free(avctx, avctx->thread_count);
1023     else
1024         thread_free(avctx);
1025 }