]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread.c
73d96fca1a2bf3c1bbf99fc750d23a6e6281f862
[ffmpeg] / libavcodec / pthread.c
1 /*
2  * Copyright (c) 2004 Roman Shaposhnik
3  * Copyright (c) 2008 Alexander Strange (astrange@ithinksw.com)
4  *
5  * Many thanks to Steven M. Schultz for providing clever ideas and
6  * to Michael Niedermayer <michaelni@gmx.at> for writing initial
7  * implementation.
8  *
9  * This file is part of Libav.
10  *
11  * Libav is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * Libav is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with Libav; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24  */
25
26 /**
27  * @file
28  * Multithreading support functions
29  * @see doc/multithreading.txt
30  */
31
32 #include "config.h"
33
34 #if HAVE_SCHED_GETAFFINITY
35 #define _GNU_SOURCE
36 #include <sched.h>
37 #endif
38 #if HAVE_GETSYSTEMINFO
39 #include <windows.h>
40 #endif
41 #if HAVE_SYSCTL
42 #if HAVE_SYS_PARAM_H
43 #include <sys/param.h>
44 #endif
45 #include <sys/types.h>
46 #include <sys/sysctl.h>
47 #endif
48
49 #include "avcodec.h"
50 #include "internal.h"
51 #include "thread.h"
52
53 #if HAVE_PTHREADS
54 #include <pthread.h>
55 #elif HAVE_W32THREADS
56 #include "w32pthreads.h"
57 #endif
58
59 typedef int (action_func)(AVCodecContext *c, void *arg);
60 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
61
62 typedef struct ThreadContext {
63     pthread_t *workers;
64     action_func *func;
65     action_func2 *func2;
66     void *args;
67     int *rets;
68     int rets_count;
69     int job_count;
70     int job_size;
71
72     pthread_cond_t last_job_cond;
73     pthread_cond_t current_job_cond;
74     pthread_mutex_t current_job_lock;
75     int current_job;
76     int done;
77 } ThreadContext;
78
79 /// Max number of frame buffers that can be allocated when using frame threads.
80 #define MAX_BUFFERS (32+1)
81
82 /**
83  * Context used by codec threads and stored in their AVCodecContext thread_opaque.
84  */
85 typedef struct PerThreadContext {
86     struct FrameThreadContext *parent;
87
88     pthread_t      thread;
89     int            thread_init;
90     pthread_cond_t input_cond;      ///< Used to wait for a new packet from the main thread.
91     pthread_cond_t progress_cond;   ///< Used by child threads to wait for progress to change.
92     pthread_cond_t output_cond;     ///< Used by the main thread to wait for frames to finish.
93
94     pthread_mutex_t mutex;          ///< Mutex used to protect the contents of the PerThreadContext.
95     pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
96
97     AVCodecContext *avctx;          ///< Context used to decode packets passed to this thread.
98
99     AVPacket       avpkt;           ///< Input packet (for decoding) or output (for encoding).
100     int            allocated_buf_size; ///< Size allocated for avpkt.data
101
102     AVFrame frame;                  ///< Output frame (for decoding) or input (for encoding).
103     int     got_frame;              ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
104     int     result;                 ///< The result of the last codec decode/encode() call.
105
106     enum {
107         STATE_INPUT_READY,          ///< Set when the thread is awaiting a packet.
108         STATE_SETTING_UP,           ///< Set before the codec has called ff_thread_finish_setup().
109         STATE_GET_BUFFER,           /**<
110                                      * Set when the codec calls get_buffer().
111                                      * State is returned to STATE_SETTING_UP afterwards.
112                                      */
113         STATE_SETUP_FINISHED        ///< Set after the codec has called ff_thread_finish_setup().
114     } state;
115
116     /**
117      * Array of frames passed to ff_thread_release_buffer().
118      * Frames are released after all threads referencing them are finished.
119      */
120     AVFrame released_buffers[MAX_BUFFERS];
121     int     num_released_buffers;
122
123     /**
124      * Array of progress values used by ff_thread_get_buffer().
125      */
126     int     progress[MAX_BUFFERS][2];
127     uint8_t progress_used[MAX_BUFFERS];
128
129     AVFrame *requested_frame;       ///< AVFrame the codec passed to get_buffer()
130 } PerThreadContext;
131
132 /**
133  * Context stored in the client AVCodecContext thread_opaque.
134  */
135 typedef struct FrameThreadContext {
136     PerThreadContext *threads;     ///< The contexts for each thread.
137     PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
138
139     pthread_mutex_t buffer_mutex;  ///< Mutex used to protect get/release_buffer().
140
141     int next_decoding;             ///< The next context to submit a packet to.
142     int next_finished;             ///< The next context to return output from.
143
144     int delaying;                  /**<
145                                     * Set for the first N packets, where N is the number of threads.
146                                     * While it is set, ff_thread_en/decode_frame won't return any results.
147                                     */
148
149     int die;                       ///< Set when threads should exit.
150 } FrameThreadContext;
151
152
153 /* H264 slice threading seems to be buggy with more than 16 threads,
154  * limit the number of threads to 16 for automatic detection */
155 #define MAX_AUTO_THREADS 16
156
157 static int get_logical_cpus(AVCodecContext *avctx)
158 {
159     int ret, nb_cpus = 1;
160 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
161     cpu_set_t cpuset;
162
163     CPU_ZERO(&cpuset);
164
165     ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
166     if (!ret) {
167         nb_cpus = CPU_COUNT(&cpuset);
168     }
169 #elif HAVE_GETSYSTEMINFO
170     SYSTEM_INFO sysinfo;
171     GetSystemInfo(&sysinfo);
172     nb_cpus = sysinfo.dwNumberOfProcessors;
173 #elif HAVE_SYSCTL && defined(HW_NCPU)
174     int mib[2] = { CTL_HW, HW_NCPU };
175     size_t len = sizeof(nb_cpus);
176
177     ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
178     if (ret == -1)
179         nb_cpus = 0;
180 #endif
181     av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
182     return FFMIN(nb_cpus, MAX_AUTO_THREADS);
183 }
184
185
186 static void* attribute_align_arg worker(void *v)
187 {
188     AVCodecContext *avctx = v;
189     ThreadContext *c = avctx->thread_opaque;
190     int our_job = c->job_count;
191     int thread_count = avctx->thread_count;
192     int self_id;
193
194     pthread_mutex_lock(&c->current_job_lock);
195     self_id = c->current_job++;
196     for (;;){
197         while (our_job >= c->job_count) {
198             if (c->current_job == thread_count + c->job_count)
199                 pthread_cond_signal(&c->last_job_cond);
200
201             pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
202             our_job = self_id;
203
204             if (c->done) {
205                 pthread_mutex_unlock(&c->current_job_lock);
206                 return NULL;
207             }
208         }
209         pthread_mutex_unlock(&c->current_job_lock);
210
211         c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
212                                                    c->func2(avctx, c->args, our_job, self_id);
213
214         pthread_mutex_lock(&c->current_job_lock);
215         our_job = c->current_job++;
216     }
217 }
218
219 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
220 {
221     pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
222     pthread_mutex_unlock(&c->current_job_lock);
223 }
224
225 static void thread_free(AVCodecContext *avctx)
226 {
227     ThreadContext *c = avctx->thread_opaque;
228     int i;
229
230     pthread_mutex_lock(&c->current_job_lock);
231     c->done = 1;
232     pthread_cond_broadcast(&c->current_job_cond);
233     pthread_mutex_unlock(&c->current_job_lock);
234
235     for (i=0; i<avctx->thread_count; i++)
236          pthread_join(c->workers[i], NULL);
237
238     pthread_mutex_destroy(&c->current_job_lock);
239     pthread_cond_destroy(&c->current_job_cond);
240     pthread_cond_destroy(&c->last_job_cond);
241     av_free(c->workers);
242     av_freep(&avctx->thread_opaque);
243 }
244
245 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
246 {
247     ThreadContext *c= avctx->thread_opaque;
248     int dummy_ret;
249
250     if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
251         return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
252
253     if (job_count <= 0)
254         return 0;
255
256     pthread_mutex_lock(&c->current_job_lock);
257
258     c->current_job = avctx->thread_count;
259     c->job_count = job_count;
260     c->job_size = job_size;
261     c->args = arg;
262     c->func = func;
263     if (ret) {
264         c->rets = ret;
265         c->rets_count = job_count;
266     } else {
267         c->rets = &dummy_ret;
268         c->rets_count = 1;
269     }
270     pthread_cond_broadcast(&c->current_job_cond);
271
272     avcodec_thread_park_workers(c, avctx->thread_count);
273
274     return 0;
275 }
276
277 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
278 {
279     ThreadContext *c= avctx->thread_opaque;
280     c->func2 = func2;
281     return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
282 }
283
284 static int thread_init(AVCodecContext *avctx)
285 {
286     int i;
287     ThreadContext *c;
288     int thread_count = avctx->thread_count;
289
290     if (!thread_count) {
291         int nb_cpus = get_logical_cpus(avctx);
292         // use number of cores + 1 as thread count if there is motre than one
293         if (nb_cpus > 1)
294             thread_count = avctx->thread_count = nb_cpus + 1;
295     }
296
297     if (thread_count <= 1) {
298         avctx->active_thread_type = 0;
299         return 0;
300     }
301
302     c = av_mallocz(sizeof(ThreadContext));
303     if (!c)
304         return -1;
305
306     c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
307     if (!c->workers) {
308         av_free(c);
309         return -1;
310     }
311
312     avctx->thread_opaque = c;
313     c->current_job = 0;
314     c->job_count = 0;
315     c->job_size = 0;
316     c->done = 0;
317     pthread_cond_init(&c->current_job_cond, NULL);
318     pthread_cond_init(&c->last_job_cond, NULL);
319     pthread_mutex_init(&c->current_job_lock, NULL);
320     pthread_mutex_lock(&c->current_job_lock);
321     for (i=0; i<thread_count; i++) {
322         if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
323            avctx->thread_count = i;
324            pthread_mutex_unlock(&c->current_job_lock);
325            ff_thread_free(avctx);
326            return -1;
327         }
328     }
329
330     avcodec_thread_park_workers(c, thread_count);
331
332     avctx->execute = avcodec_thread_execute;
333     avctx->execute2 = avcodec_thread_execute2;
334     return 0;
335 }
336
337 /**
338  * Codec worker thread.
339  *
340  * Automatically calls ff_thread_finish_setup() if the codec does
341  * not provide an update_thread_context method, or if the codec returns
342  * before calling it.
343  */
344 static attribute_align_arg void *frame_worker_thread(void *arg)
345 {
346     PerThreadContext *p = arg;
347     FrameThreadContext *fctx = p->parent;
348     AVCodecContext *avctx = p->avctx;
349     AVCodec *codec = avctx->codec;
350
351     while (1) {
352         if (p->state == STATE_INPUT_READY && !fctx->die) {
353             pthread_mutex_lock(&p->mutex);
354             while (p->state == STATE_INPUT_READY && !fctx->die)
355                 pthread_cond_wait(&p->input_cond, &p->mutex);
356             pthread_mutex_unlock(&p->mutex);
357         }
358
359         if (fctx->die) break;
360
361         if (!codec->update_thread_context && avctx->thread_safe_callbacks)
362             ff_thread_finish_setup(avctx);
363
364         pthread_mutex_lock(&p->mutex);
365         avcodec_get_frame_defaults(&p->frame);
366         p->got_frame = 0;
367         p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
368
369         if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
370
371         p->state = STATE_INPUT_READY;
372
373         pthread_mutex_lock(&p->progress_mutex);
374         pthread_cond_signal(&p->output_cond);
375         pthread_mutex_unlock(&p->progress_mutex);
376
377         pthread_mutex_unlock(&p->mutex);
378     }
379
380     return NULL;
381 }
382
383 /**
384  * Update the next thread's AVCodecContext with values from the reference thread's context.
385  *
386  * @param dst The destination context.
387  * @param src The source context.
388  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
389  */
390 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
391 {
392     int err = 0;
393
394     if (dst != src) {
395         dst->sub_id    = src->sub_id;
396         dst->time_base = src->time_base;
397         dst->width     = src->width;
398         dst->height    = src->height;
399         dst->pix_fmt   = src->pix_fmt;
400
401         dst->coded_width  = src->coded_width;
402         dst->coded_height = src->coded_height;
403
404         dst->has_b_frames = src->has_b_frames;
405         dst->idct_algo    = src->idct_algo;
406         dst->slice_count  = src->slice_count;
407
408         dst->bits_per_coded_sample = src->bits_per_coded_sample;
409         dst->sample_aspect_ratio   = src->sample_aspect_ratio;
410         dst->dtg_active_format     = src->dtg_active_format;
411
412         dst->profile = src->profile;
413         dst->level   = src->level;
414
415         dst->bits_per_raw_sample = src->bits_per_raw_sample;
416         dst->ticks_per_frame     = src->ticks_per_frame;
417         dst->color_primaries     = src->color_primaries;
418
419         dst->color_trc   = src->color_trc;
420         dst->colorspace  = src->colorspace;
421         dst->color_range = src->color_range;
422         dst->chroma_sample_location = src->chroma_sample_location;
423     }
424
425     if (for_user) {
426         dst->coded_frame = src->coded_frame;
427     } else {
428         if (dst->codec->update_thread_context)
429             err = dst->codec->update_thread_context(dst, src);
430     }
431
432     return err;
433 }
434
435 /**
436  * Update the next thread's AVCodecContext with values set by the user.
437  *
438  * @param dst The destination context.
439  * @param src The source context.
440  */
441 static void update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
442 {
443 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
444     dst->flags          = src->flags;
445
446     dst->draw_horiz_band= src->draw_horiz_band;
447     dst->get_buffer     = src->get_buffer;
448     dst->release_buffer = src->release_buffer;
449
450     dst->opaque   = src->opaque;
451     dst->dsp_mask = src->dsp_mask;
452     dst->debug    = src->debug;
453     dst->debug_mv = src->debug_mv;
454
455     dst->slice_flags = src->slice_flags;
456     dst->flags2      = src->flags2;
457
458     copy_fields(skip_loop_filter, bidir_refine);
459
460     dst->frame_number     = src->frame_number;
461     dst->reordered_opaque = src->reordered_opaque;
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         picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
608         picture->width  = avctx->width;
609         picture->height = avctx->height;
610         picture->format = avctx->pix_fmt;
611
612         /*
613          * A later call with avkpt->size == 0 may loop over all threads,
614          * including this one, searching for a frame to return before being
615          * stopped by the "finished != fctx->next_finished" condition.
616          * Make sure we don't mistakenly return the same frame again.
617          */
618         p->got_frame = 0;
619
620         if (finished >= avctx->thread_count) finished = 0;
621     } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
622
623     update_context_from_thread(avctx, p->avctx, 1);
624
625     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
626
627     fctx->next_finished = finished;
628
629     /* return the size of the consumed packet if no error occurred */
630     return (p->result >= 0) ? avpkt->size : p->result;
631 }
632
633 void ff_thread_report_progress(AVFrame *f, int n, int field)
634 {
635     PerThreadContext *p;
636     int *progress = f->thread_opaque;
637
638     if (!progress || progress[field] >= n) return;
639
640     p = f->owner->thread_opaque;
641
642     if (f->owner->debug&FF_DEBUG_THREADS)
643         av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
644
645     pthread_mutex_lock(&p->progress_mutex);
646     progress[field] = n;
647     pthread_cond_broadcast(&p->progress_cond);
648     pthread_mutex_unlock(&p->progress_mutex);
649 }
650
651 void ff_thread_await_progress(AVFrame *f, int n, int field)
652 {
653     PerThreadContext *p;
654     int *progress = f->thread_opaque;
655
656     if (!progress || progress[field] >= n) return;
657
658     p = f->owner->thread_opaque;
659
660     if (f->owner->debug&FF_DEBUG_THREADS)
661         av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
662
663     pthread_mutex_lock(&p->progress_mutex);
664     while (progress[field] < n)
665         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
666     pthread_mutex_unlock(&p->progress_mutex);
667 }
668
669 void ff_thread_finish_setup(AVCodecContext *avctx) {
670     PerThreadContext *p = avctx->thread_opaque;
671
672     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
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
720         if (codec->close)
721             codec->close(p->avctx);
722
723         avctx->codec = NULL;
724
725         release_delayed_buffers(p);
726     }
727
728     for (i = 0; i < thread_count; i++) {
729         PerThreadContext *p = &fctx->threads[i];
730
731         avcodec_default_free_buffers(p->avctx);
732
733         pthread_mutex_destroy(&p->mutex);
734         pthread_mutex_destroy(&p->progress_mutex);
735         pthread_cond_destroy(&p->input_cond);
736         pthread_cond_destroy(&p->progress_cond);
737         pthread_cond_destroy(&p->output_cond);
738         av_freep(&p->avpkt.data);
739
740         if (i) {
741             av_freep(&p->avctx->priv_data);
742             av_freep(&p->avctx->internal);
743         }
744
745         av_freep(&p->avctx);
746     }
747
748     av_freep(&fctx->threads);
749     pthread_mutex_destroy(&fctx->buffer_mutex);
750     av_freep(&avctx->thread_opaque);
751 }
752
753 static int frame_thread_init(AVCodecContext *avctx)
754 {
755     int thread_count = avctx->thread_count;
756     AVCodec *codec = avctx->codec;
757     AVCodecContext *src = avctx;
758     FrameThreadContext *fctx;
759     int i, err = 0;
760
761     if (!thread_count) {
762         int nb_cpus = get_logical_cpus(avctx);
763         // use number of cores + 1 as thread count if there is motre than one
764         if (nb_cpus > 1)
765             thread_count = avctx->thread_count = nb_cpus + 1;
766     }
767
768     if (thread_count <= 1) {
769         avctx->active_thread_type = 0;
770         return 0;
771     }
772
773     avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
774
775     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
776     pthread_mutex_init(&fctx->buffer_mutex, NULL);
777     fctx->delaying = 1;
778
779     for (i = 0; i < thread_count; i++) {
780         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
781         PerThreadContext *p  = &fctx->threads[i];
782
783         pthread_mutex_init(&p->mutex, NULL);
784         pthread_mutex_init(&p->progress_mutex, NULL);
785         pthread_cond_init(&p->input_cond, NULL);
786         pthread_cond_init(&p->progress_cond, NULL);
787         pthread_cond_init(&p->output_cond, NULL);
788
789         p->parent = fctx;
790         p->avctx  = copy;
791
792         if (!copy) {
793             err = AVERROR(ENOMEM);
794             goto error;
795         }
796
797         *copy = *src;
798         copy->thread_opaque = p;
799         copy->pkt = &p->avpkt;
800
801         if (!i) {
802             src = copy;
803
804             if (codec->init)
805                 err = codec->init(copy);
806
807             update_context_from_thread(avctx, copy, 1);
808         } else {
809             copy->priv_data = av_malloc(codec->priv_data_size);
810             if (!copy->priv_data) {
811                 err = AVERROR(ENOMEM);
812                 goto error;
813             }
814             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
815             copy->internal = av_malloc(sizeof(AVCodecInternal));
816             if (!copy->internal) {
817                 err = AVERROR(ENOMEM);
818                 goto error;
819             }
820             *(copy->internal) = *(src->internal);
821             copy->internal->is_copy = 1;
822
823             if (codec->init_thread_copy)
824                 err = codec->init_thread_copy(copy);
825         }
826
827         if (err) goto error;
828
829         if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
830             p->thread_init = 1;
831     }
832
833     return 0;
834
835 error:
836     frame_thread_free(avctx, i+1);
837
838     return err;
839 }
840
841 void ff_thread_flush(AVCodecContext *avctx)
842 {
843     FrameThreadContext *fctx = avctx->thread_opaque;
844
845     if (!avctx->thread_opaque) return;
846
847     park_frame_worker_threads(fctx, avctx->thread_count);
848     if (fctx->prev_thread) {
849         if (fctx->prev_thread != &fctx->threads[0])
850             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
851         if (avctx->codec->flush)
852             avctx->codec->flush(fctx->threads[0].avctx);
853     }
854
855     fctx->next_decoding = fctx->next_finished = 0;
856     fctx->delaying = 1;
857     fctx->prev_thread = NULL;
858 }
859
860 static int *allocate_progress(PerThreadContext *p)
861 {
862     int i;
863
864     for (i = 0; i < MAX_BUFFERS; i++)
865         if (!p->progress_used[i]) break;
866
867     if (i == MAX_BUFFERS) {
868         av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
869         return NULL;
870     }
871
872     p->progress_used[i] = 1;
873
874     return p->progress[i];
875 }
876
877 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
878 {
879     PerThreadContext *p = avctx->thread_opaque;
880     int *progress, err;
881
882     f->owner = avctx;
883
884     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
885         f->thread_opaque = NULL;
886         return avctx->get_buffer(avctx, f);
887     }
888
889     if (p->state != STATE_SETTING_UP &&
890         (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
891         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
892         return -1;
893     }
894
895     pthread_mutex_lock(&p->parent->buffer_mutex);
896     f->thread_opaque = progress = allocate_progress(p);
897
898     if (!progress) {
899         pthread_mutex_unlock(&p->parent->buffer_mutex);
900         return -1;
901     }
902
903     progress[0] =
904     progress[1] = -1;
905
906     if (avctx->thread_safe_callbacks ||
907         avctx->get_buffer == avcodec_default_get_buffer) {
908         err = avctx->get_buffer(avctx, f);
909     } else {
910         p->requested_frame = f;
911         p->state = STATE_GET_BUFFER;
912         pthread_mutex_lock(&p->progress_mutex);
913         pthread_cond_signal(&p->progress_cond);
914
915         while (p->state != STATE_SETTING_UP)
916             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
917
918         err = p->result;
919
920         pthread_mutex_unlock(&p->progress_mutex);
921
922         if (!avctx->codec->update_thread_context)
923             ff_thread_finish_setup(avctx);
924     }
925
926     pthread_mutex_unlock(&p->parent->buffer_mutex);
927
928     return err;
929 }
930
931 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
932 {
933     PerThreadContext *p = avctx->thread_opaque;
934     FrameThreadContext *fctx;
935
936     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
937         avctx->release_buffer(avctx, f);
938         return;
939     }
940
941     if (p->num_released_buffers >= MAX_BUFFERS) {
942         av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
943         return;
944     }
945
946     if(avctx->debug & FF_DEBUG_BUFFERS)
947         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
948
949     fctx = p->parent;
950     pthread_mutex_lock(&fctx->buffer_mutex);
951     p->released_buffers[p->num_released_buffers++] = *f;
952     pthread_mutex_unlock(&fctx->buffer_mutex);
953     memset(f->data, 0, sizeof(f->data));
954 }
955
956 /**
957  * Set the threading algorithms used.
958  *
959  * Threading requires more than one thread.
960  * Frame threading requires entire frames to be passed to the codec,
961  * and introduces extra decoding delay, so is incompatible with low_delay.
962  *
963  * @param avctx The context.
964  */
965 static void validate_thread_parameters(AVCodecContext *avctx)
966 {
967     int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
968                                 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
969                                 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
970                                 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
971     if (avctx->thread_count == 1) {
972         avctx->active_thread_type = 0;
973     } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
974         avctx->active_thread_type = FF_THREAD_FRAME;
975     } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
976                avctx->thread_type & FF_THREAD_SLICE) {
977         avctx->active_thread_type = FF_THREAD_SLICE;
978     }
979 }
980
981 int ff_thread_init(AVCodecContext *avctx)
982 {
983     if (avctx->thread_opaque) {
984         av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
985         return -1;
986     }
987
988 #if HAVE_W32THREADS
989     w32thread_init();
990 #endif
991
992     if (avctx->codec) {
993         validate_thread_parameters(avctx);
994
995         if (avctx->active_thread_type&FF_THREAD_SLICE)
996             return thread_init(avctx);
997         else if (avctx->active_thread_type&FF_THREAD_FRAME)
998             return frame_thread_init(avctx);
999     }
1000
1001     return 0;
1002 }
1003
1004 void ff_thread_free(AVCodecContext *avctx)
1005 {
1006     if (avctx->active_thread_type&FF_THREAD_FRAME)
1007         frame_thread_free(avctx, avctx->thread_count);
1008     else
1009         thread_free(avctx);
1010 }