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