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