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