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