]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread.c
frame-mt: return consumed packet size in ff_thread_decode_frame
[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 #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->coded_frame = src->coded_frame;
367     } else {
368         if (dst->codec->update_thread_context)
369             err = dst->codec->update_thread_context(dst, src);
370     }
371
372     return err;
373 }
374
375 /**
376  * Update the next thread's AVCodecContext with values set by the user.
377  *
378  * @param dst The destination context.
379  * @param src The source context.
380  */
381 static void update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
382 {
383 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
384     dst->flags          = src->flags;
385
386     dst->draw_horiz_band= src->draw_horiz_band;
387     dst->get_buffer     = src->get_buffer;
388     dst->release_buffer = src->release_buffer;
389
390     dst->opaque   = src->opaque;
391     dst->dsp_mask = src->dsp_mask;
392     dst->debug    = src->debug;
393     dst->debug_mv = src->debug_mv;
394
395     dst->slice_flags = src->slice_flags;
396     dst->flags2      = src->flags2;
397
398     copy_fields(skip_loop_filter, bidir_refine);
399
400     dst->frame_number     = src->frame_number;
401     dst->reordered_opaque = src->reordered_opaque;
402 #undef copy_fields
403 }
404
405 static void free_progress(AVFrame *f)
406 {
407     PerThreadContext *p = f->owner->thread_opaque;
408     int *progress = f->thread_opaque;
409
410     p->progress_used[(progress - p->progress[0]) / 2] = 0;
411 }
412
413 /// Releases the buffers that this decoding thread was the last user of.
414 static void release_delayed_buffers(PerThreadContext *p)
415 {
416     FrameThreadContext *fctx = p->parent;
417
418     while (p->num_released_buffers > 0) {
419         AVFrame *f;
420
421         pthread_mutex_lock(&fctx->buffer_mutex);
422         f = &p->released_buffers[--p->num_released_buffers];
423         free_progress(f);
424         f->thread_opaque = NULL;
425
426         f->owner->release_buffer(f->owner, f);
427         pthread_mutex_unlock(&fctx->buffer_mutex);
428     }
429 }
430
431 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
432 {
433     FrameThreadContext *fctx = p->parent;
434     PerThreadContext *prev_thread = fctx->prev_thread;
435     AVCodec *codec = p->avctx->codec;
436     uint8_t *buf = p->avpkt.data;
437
438     if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
439
440     pthread_mutex_lock(&p->mutex);
441
442     release_delayed_buffers(p);
443
444     if (prev_thread) {
445         int err;
446         if (prev_thread->state == STATE_SETTING_UP) {
447             pthread_mutex_lock(&prev_thread->progress_mutex);
448             while (prev_thread->state == STATE_SETTING_UP)
449                 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
450             pthread_mutex_unlock(&prev_thread->progress_mutex);
451         }
452
453         err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
454         if (err) {
455             pthread_mutex_unlock(&p->mutex);
456             return err;
457         }
458     }
459
460     av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
461     p->avpkt = *avpkt;
462     p->avpkt.data = buf;
463     memcpy(buf, avpkt->data, avpkt->size);
464     memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
465
466     p->state = STATE_SETTING_UP;
467     pthread_cond_signal(&p->input_cond);
468     pthread_mutex_unlock(&p->mutex);
469
470     /*
471      * If the client doesn't have a thread-safe get_buffer(),
472      * then decoding threads call back to the main thread,
473      * and it calls back to the client here.
474      */
475
476     if (!p->avctx->thread_safe_callbacks &&
477          p->avctx->get_buffer != avcodec_default_get_buffer) {
478         while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
479             pthread_mutex_lock(&p->progress_mutex);
480             while (p->state == STATE_SETTING_UP)
481                 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
482
483             if (p->state == STATE_GET_BUFFER) {
484                 p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
485                 p->state  = STATE_SETTING_UP;
486                 pthread_cond_signal(&p->progress_cond);
487             }
488             pthread_mutex_unlock(&p->progress_mutex);
489         }
490     }
491
492     fctx->prev_thread = p;
493
494     return 0;
495 }
496
497 int ff_thread_decode_frame(AVCodecContext *avctx,
498                            AVFrame *picture, int *got_picture_ptr,
499                            AVPacket *avpkt)
500 {
501     FrameThreadContext *fctx = avctx->thread_opaque;
502     int finished = fctx->next_finished;
503     PerThreadContext *p;
504     int err;
505
506     /*
507      * Submit a packet to the next decoding thread.
508      */
509
510     p = &fctx->threads[fctx->next_decoding];
511     update_context_from_user(p->avctx, avctx);
512     err = submit_packet(p, avpkt);
513     if (err) return err;
514
515     fctx->next_decoding++;
516
517     /*
518      * If we're still receiving the initial packets, don't return a frame.
519      */
520
521     if (fctx->delaying && avpkt->size) {
522         if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
523
524         *got_picture_ptr=0;
525         return avpkt->size;
526     }
527
528     /*
529      * Return the next available frame from the oldest thread.
530      * If we're at the end of the stream, then we have to skip threads that
531      * didn't output a frame, because we don't want to accidentally signal
532      * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
533      */
534
535     do {
536         p = &fctx->threads[finished++];
537
538         if (p->state != STATE_INPUT_READY) {
539             pthread_mutex_lock(&p->progress_mutex);
540             while (p->state != STATE_INPUT_READY)
541                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
542             pthread_mutex_unlock(&p->progress_mutex);
543         }
544
545         *picture = p->frame;
546         *got_picture_ptr = p->got_frame;
547         picture->pkt_dts = p->avpkt.dts;
548
549         /*
550          * A later call with avkpt->size == 0 may loop over all threads,
551          * including this one, searching for a frame to return before being
552          * stopped by the "finished != fctx->next_finished" condition.
553          * Make sure we don't mistakenly return the same frame again.
554          */
555         p->got_frame = 0;
556
557         if (finished >= avctx->thread_count) finished = 0;
558     } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
559
560     update_context_from_thread(avctx, p->avctx, 1);
561
562     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
563
564     fctx->next_finished = finished;
565
566     /* return the size of the consumed packet if no error occurred */
567     return (p->result >= 0) ? avpkt->size : 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     pthread_mutex_lock(&p->progress_mutex);
612     p->state = STATE_SETUP_FINISHED;
613     pthread_cond_broadcast(&p->progress_cond);
614     pthread_mutex_unlock(&p->progress_mutex);
615 }
616
617 /// Waits for all threads to finish.
618 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
619 {
620     int i;
621
622     for (i = 0; i < thread_count; i++) {
623         PerThreadContext *p = &fctx->threads[i];
624
625         if (p->state != STATE_INPUT_READY) {
626             pthread_mutex_lock(&p->progress_mutex);
627             while (p->state != STATE_INPUT_READY)
628                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
629             pthread_mutex_unlock(&p->progress_mutex);
630         }
631     }
632 }
633
634 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
635 {
636     FrameThreadContext *fctx = avctx->thread_opaque;
637     AVCodec *codec = avctx->codec;
638     int i;
639
640     park_frame_worker_threads(fctx, thread_count);
641
642     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
643         update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
644
645     fctx->die = 1;
646
647     for (i = 0; i < thread_count; i++) {
648         PerThreadContext *p = &fctx->threads[i];
649
650         pthread_mutex_lock(&p->mutex);
651         pthread_cond_signal(&p->input_cond);
652         pthread_mutex_unlock(&p->mutex);
653
654         pthread_join(p->thread, NULL);
655
656         if (codec->close)
657             codec->close(p->avctx);
658
659         avctx->codec = NULL;
660
661         release_delayed_buffers(p);
662     }
663
664     for (i = 0; i < thread_count; i++) {
665         PerThreadContext *p = &fctx->threads[i];
666
667         avcodec_default_free_buffers(p->avctx);
668
669         pthread_mutex_destroy(&p->mutex);
670         pthread_mutex_destroy(&p->progress_mutex);
671         pthread_cond_destroy(&p->input_cond);
672         pthread_cond_destroy(&p->progress_cond);
673         pthread_cond_destroy(&p->output_cond);
674         av_freep(&p->avpkt.data);
675
676         if (i) {
677             av_freep(&p->avctx->priv_data);
678             av_freep(&p->avctx->internal);
679         }
680
681         av_freep(&p->avctx);
682     }
683
684     av_freep(&fctx->threads);
685     pthread_mutex_destroy(&fctx->buffer_mutex);
686     av_freep(&avctx->thread_opaque);
687 }
688
689 static int frame_thread_init(AVCodecContext *avctx)
690 {
691     int thread_count = avctx->thread_count;
692     AVCodec *codec = avctx->codec;
693     AVCodecContext *src = avctx;
694     FrameThreadContext *fctx;
695     int i, err = 0;
696
697     if (thread_count <= 1) {
698         avctx->active_thread_type = 0;
699         return 0;
700     }
701
702     avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
703
704     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
705     pthread_mutex_init(&fctx->buffer_mutex, NULL);
706     fctx->delaying = 1;
707
708     for (i = 0; i < thread_count; i++) {
709         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
710         PerThreadContext *p  = &fctx->threads[i];
711
712         pthread_mutex_init(&p->mutex, NULL);
713         pthread_mutex_init(&p->progress_mutex, NULL);
714         pthread_cond_init(&p->input_cond, NULL);
715         pthread_cond_init(&p->progress_cond, NULL);
716         pthread_cond_init(&p->output_cond, NULL);
717
718         p->parent = fctx;
719         p->avctx  = copy;
720
721         if (!copy) {
722             err = AVERROR(ENOMEM);
723             goto error;
724         }
725
726         *copy = *src;
727         copy->thread_opaque = p;
728         copy->pkt = &p->avpkt;
729
730         if (!i) {
731             src = copy;
732
733             if (codec->init)
734                 err = codec->init(copy);
735
736             update_context_from_thread(avctx, copy, 1);
737         } else {
738             copy->priv_data = av_malloc(codec->priv_data_size);
739             if (!copy->priv_data) {
740                 err = AVERROR(ENOMEM);
741                 goto error;
742             }
743             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
744             copy->internal = av_malloc(sizeof(AVCodecInternal));
745             if (!copy->internal) {
746                 err = AVERROR(ENOMEM);
747                 goto error;
748             }
749             *(copy->internal) = *(src->internal);
750             copy->internal->is_copy = 1;
751
752             if (codec->init_thread_copy)
753                 err = codec->init_thread_copy(copy);
754         }
755
756         if (err) goto error;
757
758         pthread_create(&p->thread, NULL, frame_worker_thread, p);
759     }
760
761     return 0;
762
763 error:
764     frame_thread_free(avctx, i+1);
765
766     return err;
767 }
768
769 void ff_thread_flush(AVCodecContext *avctx)
770 {
771     FrameThreadContext *fctx = avctx->thread_opaque;
772
773     if (!avctx->thread_opaque) return;
774
775     park_frame_worker_threads(fctx, avctx->thread_count);
776     if (fctx->prev_thread) {
777         if (fctx->prev_thread != &fctx->threads[0])
778             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
779         if (avctx->codec->flush)
780             avctx->codec->flush(fctx->threads[0].avctx);
781     }
782
783     fctx->next_decoding = fctx->next_finished = 0;
784     fctx->delaying = 1;
785     fctx->prev_thread = NULL;
786 }
787
788 static int *allocate_progress(PerThreadContext *p)
789 {
790     int i;
791
792     for (i = 0; i < MAX_BUFFERS; i++)
793         if (!p->progress_used[i]) break;
794
795     if (i == MAX_BUFFERS) {
796         av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
797         return NULL;
798     }
799
800     p->progress_used[i] = 1;
801
802     return p->progress[i];
803 }
804
805 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
806 {
807     PerThreadContext *p = avctx->thread_opaque;
808     int *progress, err;
809
810     f->owner = avctx;
811
812     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
813         f->thread_opaque = NULL;
814         return avctx->get_buffer(avctx, f);
815     }
816
817     if (p->state != STATE_SETTING_UP &&
818         (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
819         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
820         return -1;
821     }
822
823     pthread_mutex_lock(&p->parent->buffer_mutex);
824     f->thread_opaque = progress = allocate_progress(p);
825
826     if (!progress) {
827         pthread_mutex_unlock(&p->parent->buffer_mutex);
828         return -1;
829     }
830
831     progress[0] =
832     progress[1] = -1;
833
834     if (avctx->thread_safe_callbacks ||
835         avctx->get_buffer == avcodec_default_get_buffer) {
836         err = avctx->get_buffer(avctx, f);
837     } else {
838         p->requested_frame = f;
839         p->state = STATE_GET_BUFFER;
840         pthread_mutex_lock(&p->progress_mutex);
841         pthread_cond_signal(&p->progress_cond);
842
843         while (p->state != STATE_SETTING_UP)
844             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
845
846         err = p->result;
847
848         pthread_mutex_unlock(&p->progress_mutex);
849
850         if (!avctx->codec->update_thread_context)
851             ff_thread_finish_setup(avctx);
852     }
853
854     pthread_mutex_unlock(&p->parent->buffer_mutex);
855
856     /*
857      * Buffer age is difficult to keep track of between
858      * multiple threads, and the optimizations it allows
859      * are not worth the effort. It is disabled for now.
860      */
861     f->age = INT_MAX;
862
863     return err;
864 }
865
866 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
867 {
868     PerThreadContext *p = avctx->thread_opaque;
869     FrameThreadContext *fctx;
870
871     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
872         avctx->release_buffer(avctx, f);
873         return;
874     }
875
876     if (p->num_released_buffers >= MAX_BUFFERS) {
877         av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
878         return;
879     }
880
881     if(avctx->debug & FF_DEBUG_BUFFERS)
882         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
883
884     fctx = p->parent;
885     pthread_mutex_lock(&fctx->buffer_mutex);
886     p->released_buffers[p->num_released_buffers++] = *f;
887     pthread_mutex_unlock(&fctx->buffer_mutex);
888     memset(f->data, 0, sizeof(f->data));
889 }
890
891 /**
892  * Set the threading algorithms used.
893  *
894  * Threading requires more than one thread.
895  * Frame threading requires entire frames to be passed to the codec,
896  * and introduces extra decoding delay, so is incompatible with low_delay.
897  *
898  * @param avctx The context.
899  */
900 static void validate_thread_parameters(AVCodecContext *avctx)
901 {
902     int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
903                                 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
904                                 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
905                                 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
906     if (avctx->thread_count == 1) {
907         avctx->active_thread_type = 0;
908     } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
909         avctx->active_thread_type = FF_THREAD_FRAME;
910     } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
911                avctx->thread_type & FF_THREAD_SLICE) {
912         avctx->active_thread_type = FF_THREAD_SLICE;
913     }
914 }
915
916 int ff_thread_init(AVCodecContext *avctx)
917 {
918     if (avctx->thread_opaque) {
919         av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
920         return -1;
921     }
922
923 #if HAVE_W32THREADS
924     w32thread_init();
925 #endif
926
927     if (avctx->codec) {
928         validate_thread_parameters(avctx);
929
930         if (avctx->active_thread_type&FF_THREAD_SLICE)
931             return thread_init(avctx);
932         else if (avctx->active_thread_type&FF_THREAD_FRAME)
933             return frame_thread_init(avctx);
934     }
935
936     return 0;
937 }
938
939 void ff_thread_free(AVCodecContext *avctx)
940 {
941     if (avctx->active_thread_type&FF_THREAD_FRAME)
942         frame_thread_free(avctx, avctx->thread_count);
943     else
944         thread_free(avctx);
945 }