]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread.c
Merge commit '8b7dffc2d6c6c19f8e0a1fedcd0e95dce7a273ff'
[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(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
408     if (for_user) {
409         dst->delay       = src->thread_count - 1;
410         dst->coded_frame = src->coded_frame;
411     } else {
412         if (dst->codec->update_thread_context)
413             err = dst->codec->update_thread_context(dst, src);
414     }
415
416     return err;
417 }
418
419 /**
420  * Update the next thread's AVCodecContext with values set by the user.
421  *
422  * @param dst The destination context.
423  * @param src The source context.
424  * @return 0 on success, negative error code on failure
425  */
426 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
427 {
428 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
429     dst->flags          = src->flags;
430
431     dst->draw_horiz_band= src->draw_horiz_band;
432     dst->get_buffer2    = src->get_buffer2;
433 #if FF_API_GET_BUFFER
434     dst->get_buffer     = src->get_buffer;
435     dst->release_buffer = src->release_buffer;
436 #endif
437
438     dst->opaque   = src->opaque;
439     dst->debug    = src->debug;
440     dst->debug_mv = src->debug_mv;
441
442     dst->slice_flags = src->slice_flags;
443     dst->flags2      = src->flags2;
444
445     copy_fields(skip_loop_filter, subtitle_header);
446
447     dst->frame_number     = src->frame_number;
448     dst->reordered_opaque = src->reordered_opaque;
449     dst->thread_safe_callbacks = src->thread_safe_callbacks;
450
451     if (src->slice_count && src->slice_offset) {
452         if (dst->slice_count < src->slice_count) {
453             int *tmp = av_realloc(dst->slice_offset, src->slice_count *
454                                   sizeof(*dst->slice_offset));
455             if (!tmp) {
456                 av_free(dst->slice_offset);
457                 return AVERROR(ENOMEM);
458             }
459             dst->slice_offset = tmp;
460         }
461         memcpy(dst->slice_offset, src->slice_offset,
462                src->slice_count * sizeof(*dst->slice_offset));
463     }
464     dst->slice_count = src->slice_count;
465     return 0;
466 #undef copy_fields
467 }
468
469 /// Releases the buffers that this decoding thread was the last user of.
470 static void release_delayed_buffers(PerThreadContext *p)
471 {
472     FrameThreadContext *fctx = p->parent;
473
474     while (p->num_released_buffers > 0) {
475         AVFrame *f;
476
477         pthread_mutex_lock(&fctx->buffer_mutex);
478
479         // fix extended data in case the caller screwed it up
480         av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
481         f = &p->released_buffers[--p->num_released_buffers];
482         f->extended_data = f->data;
483         av_frame_unref(f);
484
485         pthread_mutex_unlock(&fctx->buffer_mutex);
486     }
487 }
488
489 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
490 {
491     FrameThreadContext *fctx = p->parent;
492     PerThreadContext *prev_thread = fctx->prev_thread;
493     const AVCodec *codec = p->avctx->codec;
494
495     if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
496
497     pthread_mutex_lock(&p->mutex);
498
499     release_delayed_buffers(p);
500
501     if (prev_thread) {
502         int err;
503         if (prev_thread->state == STATE_SETTING_UP) {
504             pthread_mutex_lock(&prev_thread->progress_mutex);
505             while (prev_thread->state == STATE_SETTING_UP)
506                 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
507             pthread_mutex_unlock(&prev_thread->progress_mutex);
508         }
509
510         err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
511         if (err) {
512             pthread_mutex_unlock(&p->mutex);
513             return err;
514         }
515     }
516
517     av_buffer_unref(&p->avpkt.buf);
518     p->avpkt = *avpkt;
519     if (avpkt->buf)
520         p->avpkt.buf = av_buffer_ref(avpkt->buf);
521     else {
522         av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
523         p->avpkt.data = p->buf;
524         memcpy(p->buf, avpkt->data, avpkt->size);
525         memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
526     }
527
528     p->state = STATE_SETTING_UP;
529     pthread_cond_signal(&p->input_cond);
530     pthread_mutex_unlock(&p->mutex);
531
532     /*
533      * If the client doesn't have a thread-safe get_buffer(),
534      * then decoding threads call back to the main thread,
535      * and it calls back to the client here.
536      */
537
538     if (!p->avctx->thread_safe_callbacks && (
539          p->avctx->get_format != avcodec_default_get_format ||
540 #if FF_API_GET_BUFFER
541          p->avctx->get_buffer ||
542 #endif
543          p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
544         while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
545             int call_done = 1;
546             pthread_mutex_lock(&p->progress_mutex);
547             while (p->state == STATE_SETTING_UP)
548                 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
549
550             switch (p->state) {
551             case STATE_GET_BUFFER:
552                 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
553                 break;
554             case STATE_GET_FORMAT:
555                 p->result_format = p->avctx->get_format(p->avctx, p->available_formats);
556                 break;
557             default:
558                 call_done = 0;
559                 break;
560             }
561             if (call_done) {
562                 p->state  = STATE_SETTING_UP;
563                 pthread_cond_signal(&p->progress_cond);
564             }
565             pthread_mutex_unlock(&p->progress_mutex);
566         }
567     }
568
569     fctx->prev_thread = p;
570     fctx->next_decoding++;
571
572     return 0;
573 }
574
575 int ff_thread_decode_frame(AVCodecContext *avctx,
576                            AVFrame *picture, int *got_picture_ptr,
577                            AVPacket *avpkt)
578 {
579     FrameThreadContext *fctx = avctx->thread_opaque;
580     int finished = fctx->next_finished;
581     PerThreadContext *p;
582     int err;
583
584     /*
585      * Submit a packet to the next decoding thread.
586      */
587
588     p = &fctx->threads[fctx->next_decoding];
589     err = update_context_from_user(p->avctx, avctx);
590     if (err) return err;
591     err = submit_packet(p, avpkt);
592     if (err) return err;
593
594     /*
595      * If we're still receiving the initial packets, don't return a frame.
596      */
597
598     if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
599         fctx->delaying = 0;
600
601     if (fctx->delaying) {
602         *got_picture_ptr=0;
603         if (avpkt->size)
604             return avpkt->size;
605     }
606
607     /*
608      * Return the next available frame from the oldest thread.
609      * If we're at the end of the stream, then we have to skip threads that
610      * didn't output a frame, because we don't want to accidentally signal
611      * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
612      */
613
614     do {
615         p = &fctx->threads[finished++];
616
617         if (p->state != STATE_INPUT_READY) {
618             pthread_mutex_lock(&p->progress_mutex);
619             while (p->state != STATE_INPUT_READY)
620                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
621             pthread_mutex_unlock(&p->progress_mutex);
622         }
623
624         av_frame_move_ref(picture, &p->frame);
625         *got_picture_ptr = p->got_frame;
626         picture->pkt_dts = p->avpkt.dts;
627
628         /*
629          * A later call with avkpt->size == 0 may loop over all threads,
630          * including this one, searching for a frame to return before being
631          * stopped by the "finished != fctx->next_finished" condition.
632          * Make sure we don't mistakenly return the same frame again.
633          */
634         p->got_frame = 0;
635
636         if (finished >= avctx->thread_count) finished = 0;
637     } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
638
639     update_context_from_thread(avctx, p->avctx, 1);
640
641     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
642
643     fctx->next_finished = finished;
644
645     /* return the size of the consumed packet if no error occurred */
646     return (p->result >= 0) ? avpkt->size : p->result;
647 }
648
649 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
650 {
651     PerThreadContext *p;
652     volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
653
654     if (!progress || progress[field] >= n) return;
655
656     p = f->owner->thread_opaque;
657
658     if (f->owner->debug&FF_DEBUG_THREADS)
659         av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
660
661     pthread_mutex_lock(&p->progress_mutex);
662     progress[field] = n;
663     pthread_cond_broadcast(&p->progress_cond);
664     pthread_mutex_unlock(&p->progress_mutex);
665 }
666
667 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
668 {
669     PerThreadContext *p;
670     volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
671
672     if (!progress || progress[field] >= n) return;
673
674     p = f->owner->thread_opaque;
675
676     if (f->owner->debug&FF_DEBUG_THREADS)
677         av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
678
679     pthread_mutex_lock(&p->progress_mutex);
680     while (progress[field] < n)
681         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
682     pthread_mutex_unlock(&p->progress_mutex);
683 }
684
685 void ff_thread_finish_setup(AVCodecContext *avctx) {
686     PerThreadContext *p = avctx->thread_opaque;
687
688     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
689
690     if(p->state == STATE_SETUP_FINISHED){
691         av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
692     }
693
694     pthread_mutex_lock(&p->progress_mutex);
695     p->state = STATE_SETUP_FINISHED;
696     pthread_cond_broadcast(&p->progress_cond);
697     pthread_mutex_unlock(&p->progress_mutex);
698 }
699
700 /// Waits for all threads to finish.
701 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
702 {
703     int i;
704
705     for (i = 0; i < thread_count; i++) {
706         PerThreadContext *p = &fctx->threads[i];
707
708         if (p->state != STATE_INPUT_READY) {
709             pthread_mutex_lock(&p->progress_mutex);
710             while (p->state != STATE_INPUT_READY)
711                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
712             pthread_mutex_unlock(&p->progress_mutex);
713         }
714         p->got_frame = 0;
715     }
716 }
717
718 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
719 {
720     FrameThreadContext *fctx = avctx->thread_opaque;
721     const AVCodec *codec = avctx->codec;
722     int i;
723
724     park_frame_worker_threads(fctx, thread_count);
725
726     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
727         if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
728             av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
729             fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
730             fctx->threads->avctx->internal->is_copy = 1;
731         }
732
733     fctx->die = 1;
734
735     for (i = 0; i < thread_count; i++) {
736         PerThreadContext *p = &fctx->threads[i];
737
738         pthread_mutex_lock(&p->mutex);
739         pthread_cond_signal(&p->input_cond);
740         pthread_mutex_unlock(&p->mutex);
741
742         if (p->thread_init)
743             pthread_join(p->thread, NULL);
744         p->thread_init=0;
745
746         if (codec->close)
747             codec->close(p->avctx);
748
749         avctx->codec = NULL;
750
751         release_delayed_buffers(p);
752         av_frame_unref(&p->frame);
753     }
754
755     for (i = 0; i < thread_count; i++) {
756         PerThreadContext *p = &fctx->threads[i];
757
758         pthread_mutex_destroy(&p->mutex);
759         pthread_mutex_destroy(&p->progress_mutex);
760         pthread_cond_destroy(&p->input_cond);
761         pthread_cond_destroy(&p->progress_cond);
762         pthread_cond_destroy(&p->output_cond);
763         av_buffer_unref(&p->avpkt.buf);
764         av_freep(&p->buf);
765         av_freep(&p->released_buffers);
766
767         if (i) {
768             av_freep(&p->avctx->priv_data);
769             av_freep(&p->avctx->internal);
770             av_freep(&p->avctx->slice_offset);
771         }
772
773         av_freep(&p->avctx);
774     }
775
776     av_freep(&fctx->threads);
777     pthread_mutex_destroy(&fctx->buffer_mutex);
778     av_freep(&avctx->thread_opaque);
779 }
780
781 static int frame_thread_init(AVCodecContext *avctx)
782 {
783     int thread_count = avctx->thread_count;
784     const AVCodec *codec = avctx->codec;
785     AVCodecContext *src = avctx;
786     FrameThreadContext *fctx;
787     int i, err = 0;
788
789     if (!thread_count) {
790         int nb_cpus = av_cpu_count();
791         if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
792             nb_cpus = 1;
793         // use number of cores + 1 as thread count if there is more than one
794         if (nb_cpus > 1)
795             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
796         else
797             thread_count = avctx->thread_count = 1;
798     }
799
800     if (thread_count <= 1) {
801         avctx->active_thread_type = 0;
802         return 0;
803     }
804
805     avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
806
807     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
808     pthread_mutex_init(&fctx->buffer_mutex, NULL);
809     fctx->delaying = 1;
810
811     for (i = 0; i < thread_count; i++) {
812         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
813         PerThreadContext *p  = &fctx->threads[i];
814
815         pthread_mutex_init(&p->mutex, NULL);
816         pthread_mutex_init(&p->progress_mutex, NULL);
817         pthread_cond_init(&p->input_cond, NULL);
818         pthread_cond_init(&p->progress_cond, NULL);
819         pthread_cond_init(&p->output_cond, NULL);
820
821         p->parent = fctx;
822         p->avctx  = copy;
823
824         if (!copy) {
825             err = AVERROR(ENOMEM);
826             goto error;
827         }
828
829         *copy = *src;
830         copy->thread_opaque = p;
831         copy->pkt = &p->avpkt;
832
833         if (!i) {
834             src = copy;
835
836             if (codec->init)
837                 err = codec->init(copy);
838
839             update_context_from_thread(avctx, copy, 1);
840         } else {
841             copy->priv_data = av_malloc(codec->priv_data_size);
842             if (!copy->priv_data) {
843                 err = AVERROR(ENOMEM);
844                 goto error;
845             }
846             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
847             copy->internal = av_malloc(sizeof(AVCodecInternal));
848             if (!copy->internal) {
849                 err = AVERROR(ENOMEM);
850                 goto error;
851             }
852             *copy->internal = *src->internal;
853             copy->internal->is_copy = 1;
854
855             if (codec->init_thread_copy)
856                 err = codec->init_thread_copy(copy);
857         }
858
859         if (err) goto error;
860
861         err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
862         p->thread_init= !err;
863         if(!p->thread_init)
864             goto error;
865     }
866
867     return 0;
868
869 error:
870     frame_thread_free(avctx, i+1);
871
872     return err;
873 }
874
875 void ff_thread_flush(AVCodecContext *avctx)
876 {
877     int i;
878     FrameThreadContext *fctx = avctx->thread_opaque;
879
880     if (!avctx->thread_opaque) return;
881
882     park_frame_worker_threads(fctx, avctx->thread_count);
883     if (fctx->prev_thread) {
884         if (fctx->prev_thread != &fctx->threads[0])
885             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
886         if (avctx->codec->flush)
887             avctx->codec->flush(fctx->threads[0].avctx);
888     }
889
890     fctx->next_decoding = fctx->next_finished = 0;
891     fctx->delaying = 1;
892     fctx->prev_thread = NULL;
893     for (i = 0; i < avctx->thread_count; i++) {
894         PerThreadContext *p = &fctx->threads[i];
895         // Make sure decode flush calls with size=0 won't return old frames
896         p->got_frame = 0;
897         av_frame_unref(&p->frame);
898
899         release_delayed_buffers(p);
900     }
901 }
902
903 int ff_thread_can_start_frame(AVCodecContext *avctx)
904 {
905     PerThreadContext *p = avctx->thread_opaque;
906     if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
907         (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
908         return 0;
909     }
910     return 1;
911 }
912
913 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
914 {
915     PerThreadContext *p = avctx->thread_opaque;
916     int err;
917
918     f->owner = avctx;
919
920     ff_init_buffer_info(avctx, f->f);
921
922     if (!(avctx->active_thread_type & FF_THREAD_FRAME))
923         return ff_get_buffer(avctx, f->f, flags);
924
925     if (p->state != STATE_SETTING_UP &&
926         (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
927         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
928         return -1;
929     }
930
931     if (avctx->internal->allocate_progress) {
932         int *progress;
933         f->progress = av_buffer_alloc(2 * sizeof(int));
934         if (!f->progress) {
935             return AVERROR(ENOMEM);
936         }
937         progress = (int*)f->progress->data;
938
939         progress[0] = progress[1] = -1;
940     }
941
942     pthread_mutex_lock(&p->parent->buffer_mutex);
943
944     if (avctx->thread_safe_callbacks || (
945 #if FF_API_GET_BUFFER
946         !avctx->get_buffer &&
947 #endif
948         avctx->get_buffer2 == avcodec_default_get_buffer2)) {
949         err = ff_get_buffer(avctx, f->f, flags);
950     } else {
951         pthread_mutex_lock(&p->progress_mutex);
952         p->requested_frame = f->f;
953         p->requested_flags = flags;
954         p->state = STATE_GET_BUFFER;
955         pthread_cond_broadcast(&p->progress_cond);
956
957         while (p->state != STATE_SETTING_UP)
958             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
959
960         err = p->result;
961
962         pthread_mutex_unlock(&p->progress_mutex);
963
964     }
965     if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
966         ff_thread_finish_setup(avctx);
967
968     if (err)
969         av_buffer_unref(&f->progress);
970
971     pthread_mutex_unlock(&p->parent->buffer_mutex);
972
973     return err;
974 }
975
976 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
977 {
978     enum AVPixelFormat res;
979     PerThreadContext *p = avctx->thread_opaque;
980     if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
981         avctx->get_format == avcodec_default_get_format)
982         return avctx->get_format(avctx, fmt);
983     if (p->state != STATE_SETTING_UP) {
984         av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
985         return -1;
986     }
987     pthread_mutex_lock(&p->progress_mutex);
988     p->available_formats = fmt;
989     p->state = STATE_GET_FORMAT;
990     pthread_cond_broadcast(&p->progress_cond);
991
992     while (p->state != STATE_SETTING_UP)
993         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
994
995     res = p->result_format;
996
997     pthread_mutex_unlock(&p->progress_mutex);
998
999     return res;
1000 }
1001
1002 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1003 {
1004     int ret = thread_get_buffer_internal(avctx, f, flags);
1005     if (ret < 0)
1006         av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1007     return ret;
1008 }
1009
1010 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1011 {
1012     PerThreadContext *p = avctx->thread_opaque;
1013     FrameThreadContext *fctx;
1014     AVFrame *dst, *tmp;
1015     int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1016                           avctx->thread_safe_callbacks                   ||
1017                           (
1018 #if FF_API_GET_BUFFER
1019                            !avctx->get_buffer &&
1020 #endif
1021                            avctx->get_buffer2 == avcodec_default_get_buffer2);
1022
1023     if (!f->f->data[0])
1024         return;
1025
1026     if (avctx->debug & FF_DEBUG_BUFFERS)
1027         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1028
1029     av_buffer_unref(&f->progress);
1030     f->owner    = NULL;
1031
1032     if (can_direct_free) {
1033         av_frame_unref(f->f);
1034         return;
1035     }
1036
1037     fctx = p->parent;
1038     pthread_mutex_lock(&fctx->buffer_mutex);
1039
1040     if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
1041         goto fail;
1042     tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
1043                           (p->num_released_buffers + 1) *
1044                           sizeof(*p->released_buffers));
1045     if (!tmp)
1046         goto fail;
1047     p->released_buffers = tmp;
1048
1049     dst = &p->released_buffers[p->num_released_buffers];
1050     av_frame_move_ref(dst, f->f);
1051
1052     p->num_released_buffers++;
1053
1054 fail:
1055     pthread_mutex_unlock(&fctx->buffer_mutex);
1056 }
1057
1058 /**
1059  * Set the threading algorithms used.
1060  *
1061  * Threading requires more than one thread.
1062  * Frame threading requires entire frames to be passed to the codec,
1063  * and introduces extra decoding delay, so is incompatible with low_delay.
1064  *
1065  * @param avctx The context.
1066  */
1067 static void validate_thread_parameters(AVCodecContext *avctx)
1068 {
1069     int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1070                                 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1071                                 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1072                                 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1073     if (avctx->thread_count == 1) {
1074         avctx->active_thread_type = 0;
1075     } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1076         avctx->active_thread_type = FF_THREAD_FRAME;
1077     } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1078                avctx->thread_type & FF_THREAD_SLICE) {
1079         avctx->active_thread_type = FF_THREAD_SLICE;
1080     } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1081         avctx->thread_count       = 1;
1082         avctx->active_thread_type = 0;
1083     }
1084
1085     if (avctx->thread_count > MAX_AUTO_THREADS)
1086         av_log(avctx, AV_LOG_WARNING,
1087                "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1088                avctx->thread_count, MAX_AUTO_THREADS);
1089 }
1090
1091 int ff_thread_init(AVCodecContext *avctx)
1092 {
1093 #if HAVE_W32THREADS
1094     w32thread_init();
1095 #endif
1096
1097     validate_thread_parameters(avctx);
1098
1099     if (avctx->active_thread_type&FF_THREAD_SLICE)
1100         return thread_init(avctx);
1101     else if (avctx->active_thread_type&FF_THREAD_FRAME)
1102         return frame_thread_init(avctx);
1103
1104     return 0;
1105 }
1106
1107 void ff_thread_free(AVCodecContext *avctx)
1108 {
1109     if (avctx->active_thread_type&FF_THREAD_FRAME)
1110         frame_thread_free(avctx, avctx->thread_count);
1111     else
1112         thread_free(avctx);
1113 }