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