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