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