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