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