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