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