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