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