]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread.c
5f427c03906835c1e914fe9b3b79c516dabc4000
[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     int            thread_init;
74     pthread_cond_t input_cond;      ///< Used to wait for a new packet from the main thread.
75     pthread_cond_t progress_cond;   ///< Used by child threads to wait for progress to change.
76     pthread_cond_t output_cond;     ///< Used by the main thread to wait for frames to finish.
77
78     pthread_mutex_t mutex;          ///< Mutex used to protect the contents of the PerThreadContext.
79     pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
80
81     AVCodecContext *avctx;          ///< Context used to decode packets passed to this thread.
82
83     AVPacket       avpkt;           ///< Input packet (for decoding) or output (for encoding).
84     int            allocated_buf_size; ///< Size allocated for avpkt.data
85
86     AVFrame frame;                  ///< Output frame (for decoding) or input (for encoding).
87     int     got_frame;              ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
88     int     result;                 ///< The result of the last codec decode/encode() call.
89
90     enum {
91         STATE_INPUT_READY,          ///< Set when the thread is awaiting a packet.
92         STATE_SETTING_UP,           ///< Set before the codec has called ff_thread_finish_setup().
93         STATE_GET_BUFFER,           /**<
94                                      * Set when the codec calls get_buffer().
95                                      * State is returned to STATE_SETTING_UP afterwards.
96                                      */
97         STATE_SETUP_FINISHED        ///< Set after the codec has called ff_thread_finish_setup().
98     } state;
99
100     /**
101      * Array of frames passed to ff_thread_release_buffer().
102      * Frames are released after all threads referencing them are finished.
103      */
104     AVFrame released_buffers[MAX_BUFFERS];
105     int     num_released_buffers;
106
107     /**
108      * Array of progress values used by ff_thread_get_buffer().
109      */
110     int     progress[MAX_BUFFERS][2];
111     uint8_t progress_used[MAX_BUFFERS];
112
113     AVFrame *requested_frame;       ///< AVFrame the codec passed to get_buffer()
114 } PerThreadContext;
115
116 /**
117  * Context stored in the client AVCodecContext thread_opaque.
118  */
119 typedef struct FrameThreadContext {
120     PerThreadContext *threads;     ///< The contexts for each thread.
121     PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
122
123     pthread_mutex_t buffer_mutex;  ///< Mutex used to protect get/release_buffer().
124
125     int next_decoding;             ///< The next context to submit a packet to.
126     int next_finished;             ///< The next context to return output from.
127
128     int delaying;                  /**<
129                                     * Set for the first N packets, where N is the number of threads.
130                                     * While it is set, ff_thread_en/decode_frame won't return any results.
131                                     */
132
133     int die;                       ///< Set when threads should exit.
134 } FrameThreadContext;
135
136 static void* attribute_align_arg worker(void *v)
137 {
138     AVCodecContext *avctx = v;
139     ThreadContext *c = avctx->thread_opaque;
140     int our_job = c->job_count;
141     int thread_count = avctx->thread_count;
142     int self_id;
143
144     pthread_mutex_lock(&c->current_job_lock);
145     self_id = c->current_job++;
146     for (;;){
147         while (our_job >= c->job_count) {
148             if (c->current_job == thread_count + c->job_count)
149                 pthread_cond_signal(&c->last_job_cond);
150
151             pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
152             our_job = self_id;
153
154             if (c->done) {
155                 pthread_mutex_unlock(&c->current_job_lock);
156                 return NULL;
157             }
158         }
159         pthread_mutex_unlock(&c->current_job_lock);
160
161         c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
162                                                    c->func2(avctx, c->args, our_job, self_id);
163
164         pthread_mutex_lock(&c->current_job_lock);
165         our_job = c->current_job++;
166     }
167 }
168
169 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
170 {
171     pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
172     pthread_mutex_unlock(&c->current_job_lock);
173 }
174
175 static void thread_free(AVCodecContext *avctx)
176 {
177     ThreadContext *c = avctx->thread_opaque;
178     int i;
179
180     pthread_mutex_lock(&c->current_job_lock);
181     c->done = 1;
182     pthread_cond_broadcast(&c->current_job_cond);
183     pthread_mutex_unlock(&c->current_job_lock);
184
185     for (i=0; i<avctx->thread_count; i++)
186          pthread_join(c->workers[i], NULL);
187
188     pthread_mutex_destroy(&c->current_job_lock);
189     pthread_cond_destroy(&c->current_job_cond);
190     pthread_cond_destroy(&c->last_job_cond);
191     av_free(c->workers);
192     av_freep(&avctx->thread_opaque);
193 }
194
195 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
196 {
197     ThreadContext *c= avctx->thread_opaque;
198     int dummy_ret;
199
200     if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
201         return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
202
203     if (job_count <= 0)
204         return 0;
205
206     pthread_mutex_lock(&c->current_job_lock);
207
208     c->current_job = avctx->thread_count;
209     c->job_count = job_count;
210     c->job_size = job_size;
211     c->args = arg;
212     c->func = func;
213     if (ret) {
214         c->rets = ret;
215         c->rets_count = job_count;
216     } else {
217         c->rets = &dummy_ret;
218         c->rets_count = 1;
219     }
220     pthread_cond_broadcast(&c->current_job_cond);
221
222     avcodec_thread_park_workers(c, avctx->thread_count);
223
224     return 0;
225 }
226
227 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
228 {
229     ThreadContext *c= avctx->thread_opaque;
230     c->func2 = func2;
231     return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
232 }
233
234 static int thread_init(AVCodecContext *avctx)
235 {
236     int i;
237     ThreadContext *c;
238     int thread_count = avctx->thread_count;
239
240     if (thread_count <= 1)
241         return 0;
242
243     c = av_mallocz(sizeof(ThreadContext));
244     if (!c)
245         return -1;
246
247     c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
248     if (!c->workers) {
249         av_free(c);
250         return -1;
251     }
252
253     avctx->thread_opaque = c;
254     c->current_job = 0;
255     c->job_count = 0;
256     c->job_size = 0;
257     c->done = 0;
258     pthread_cond_init(&c->current_job_cond, NULL);
259     pthread_cond_init(&c->last_job_cond, NULL);
260     pthread_mutex_init(&c->current_job_lock, NULL);
261     pthread_mutex_lock(&c->current_job_lock);
262     for (i=0; i<thread_count; i++) {
263         if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
264            avctx->thread_count = i;
265            pthread_mutex_unlock(&c->current_job_lock);
266            ff_thread_free(avctx);
267            return -1;
268         }
269     }
270
271     avcodec_thread_park_workers(c, thread_count);
272
273     avctx->execute = avcodec_thread_execute;
274     avctx->execute2 = avcodec_thread_execute2;
275     return 0;
276 }
277
278 /**
279  * Codec worker thread.
280  *
281  * Automatically calls ff_thread_finish_setup() if the codec does
282  * not provide an update_thread_context method, or if the codec returns
283  * before calling it.
284  */
285 static attribute_align_arg void *frame_worker_thread(void *arg)
286 {
287     PerThreadContext *p = arg;
288     FrameThreadContext *fctx = p->parent;
289     AVCodecContext *avctx = p->avctx;
290     AVCodec *codec = avctx->codec;
291
292     while (1) {
293         if (p->state == STATE_INPUT_READY && !fctx->die) {
294             pthread_mutex_lock(&p->mutex);
295             while (p->state == STATE_INPUT_READY && !fctx->die)
296                 pthread_cond_wait(&p->input_cond, &p->mutex);
297             pthread_mutex_unlock(&p->mutex);
298         }
299
300         if (fctx->die) break;
301
302         if (!codec->update_thread_context && avctx->thread_safe_callbacks)
303             ff_thread_finish_setup(avctx);
304
305         pthread_mutex_lock(&p->mutex);
306         avcodec_get_frame_defaults(&p->frame);
307         p->got_frame = 0;
308         p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
309
310         if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
311
312         p->state = STATE_INPUT_READY;
313
314         pthread_mutex_lock(&p->progress_mutex);
315         pthread_cond_signal(&p->output_cond);
316         pthread_mutex_unlock(&p->progress_mutex);
317
318         pthread_mutex_unlock(&p->mutex);
319     }
320
321     return NULL;
322 }
323
324 /**
325  * Update the next thread's AVCodecContext with values from the reference thread's context.
326  *
327  * @param dst The destination context.
328  * @param src The source context.
329  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
330  */
331 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
332 {
333     int err = 0;
334
335     if (dst != src) {
336         dst->sub_id    = src->sub_id;
337         dst->time_base = src->time_base;
338         dst->width     = src->width;
339         dst->height    = src->height;
340         dst->pix_fmt   = src->pix_fmt;
341
342         dst->coded_width  = src->coded_width;
343         dst->coded_height = src->coded_height;
344
345         dst->has_b_frames = src->has_b_frames;
346         dst->idct_algo    = src->idct_algo;
347         dst->slice_count  = src->slice_count;
348
349         dst->bits_per_coded_sample = src->bits_per_coded_sample;
350         dst->sample_aspect_ratio   = src->sample_aspect_ratio;
351         dst->dtg_active_format     = src->dtg_active_format;
352
353         dst->profile = src->profile;
354         dst->level   = src->level;
355
356         dst->bits_per_raw_sample = src->bits_per_raw_sample;
357         dst->ticks_per_frame     = src->ticks_per_frame;
358         dst->color_primaries     = src->color_primaries;
359
360         dst->color_trc   = src->color_trc;
361         dst->colorspace  = src->colorspace;
362         dst->color_range = src->color_range;
363         dst->chroma_sample_location = src->chroma_sample_location;
364     }
365
366     if (for_user) {
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     fctx->next_decoding++;
495
496     return 0;
497 }
498
499 int ff_thread_decode_frame(AVCodecContext *avctx,
500                            AVFrame *picture, int *got_picture_ptr,
501                            AVPacket *avpkt)
502 {
503     FrameThreadContext *fctx = avctx->thread_opaque;
504     int finished = fctx->next_finished;
505     PerThreadContext *p;
506     int err;
507
508     /*
509      * Submit a packet to the next decoding thread.
510      */
511
512     p = &fctx->threads[fctx->next_decoding];
513     update_context_from_user(p->avctx, avctx);
514     err = submit_packet(p, avpkt);
515     if (err) return err;
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         if (p->thread_init)
655             pthread_join(p->thread, NULL);
656
657         if (codec->close)
658             codec->close(p->avctx);
659
660         avctx->codec = NULL;
661
662         release_delayed_buffers(p);
663     }
664
665     for (i = 0; i < thread_count; i++) {
666         PerThreadContext *p = &fctx->threads[i];
667
668         avcodec_default_free_buffers(p->avctx);
669
670         pthread_mutex_destroy(&p->mutex);
671         pthread_mutex_destroy(&p->progress_mutex);
672         pthread_cond_destroy(&p->input_cond);
673         pthread_cond_destroy(&p->progress_cond);
674         pthread_cond_destroy(&p->output_cond);
675         av_freep(&p->avpkt.data);
676
677         if (i) {
678             av_freep(&p->avctx->priv_data);
679             av_freep(&p->avctx->internal);
680         }
681
682         av_freep(&p->avctx);
683     }
684
685     av_freep(&fctx->threads);
686     pthread_mutex_destroy(&fctx->buffer_mutex);
687     av_freep(&avctx->thread_opaque);
688 }
689
690 static int frame_thread_init(AVCodecContext *avctx)
691 {
692     int thread_count = avctx->thread_count;
693     AVCodec *codec = avctx->codec;
694     AVCodecContext *src = avctx;
695     FrameThreadContext *fctx;
696     int i, err = 0;
697
698     if (thread_count <= 1) {
699         avctx->active_thread_type = 0;
700         return 0;
701     }
702
703     avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
704
705     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
706     pthread_mutex_init(&fctx->buffer_mutex, NULL);
707     fctx->delaying = 1;
708
709     for (i = 0; i < thread_count; i++) {
710         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
711         PerThreadContext *p  = &fctx->threads[i];
712
713         pthread_mutex_init(&p->mutex, NULL);
714         pthread_mutex_init(&p->progress_mutex, NULL);
715         pthread_cond_init(&p->input_cond, NULL);
716         pthread_cond_init(&p->progress_cond, NULL);
717         pthread_cond_init(&p->output_cond, NULL);
718
719         p->parent = fctx;
720         p->avctx  = copy;
721
722         if (!copy) {
723             err = AVERROR(ENOMEM);
724             goto error;
725         }
726
727         *copy = *src;
728         copy->thread_opaque = p;
729         copy->pkt = &p->avpkt;
730
731         if (!i) {
732             src = copy;
733
734             if (codec->init)
735                 err = codec->init(copy);
736
737             update_context_from_thread(avctx, copy, 1);
738         } else {
739             copy->priv_data = av_malloc(codec->priv_data_size);
740             if (!copy->priv_data) {
741                 err = AVERROR(ENOMEM);
742                 goto error;
743             }
744             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
745             copy->internal = av_malloc(sizeof(AVCodecInternal));
746             if (!copy->internal) {
747                 err = AVERROR(ENOMEM);
748                 goto error;
749             }
750             *(copy->internal) = *(src->internal);
751             copy->internal->is_copy = 1;
752
753             if (codec->init_thread_copy)
754                 err = codec->init_thread_copy(copy);
755         }
756
757         if (err) goto error;
758
759         if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
760             p->thread_init = 1;
761     }
762
763     return 0;
764
765 error:
766     frame_thread_free(avctx, i+1);
767
768     return err;
769 }
770
771 void ff_thread_flush(AVCodecContext *avctx)
772 {
773     FrameThreadContext *fctx = avctx->thread_opaque;
774
775     if (!avctx->thread_opaque) return;
776
777     park_frame_worker_threads(fctx, avctx->thread_count);
778     if (fctx->prev_thread) {
779         if (fctx->prev_thread != &fctx->threads[0])
780             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
781         if (avctx->codec->flush)
782             avctx->codec->flush(fctx->threads[0].avctx);
783     }
784
785     fctx->next_decoding = fctx->next_finished = 0;
786     fctx->delaying = 1;
787     fctx->prev_thread = NULL;
788 }
789
790 static int *allocate_progress(PerThreadContext *p)
791 {
792     int i;
793
794     for (i = 0; i < MAX_BUFFERS; i++)
795         if (!p->progress_used[i]) break;
796
797     if (i == MAX_BUFFERS) {
798         av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
799         return NULL;
800     }
801
802     p->progress_used[i] = 1;
803
804     return p->progress[i];
805 }
806
807 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
808 {
809     PerThreadContext *p = avctx->thread_opaque;
810     int *progress, err;
811
812     f->owner = avctx;
813
814     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
815         f->thread_opaque = NULL;
816         return avctx->get_buffer(avctx, f);
817     }
818
819     if (p->state != STATE_SETTING_UP &&
820         (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
821         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
822         return -1;
823     }
824
825     pthread_mutex_lock(&p->parent->buffer_mutex);
826     f->thread_opaque = progress = allocate_progress(p);
827
828     if (!progress) {
829         pthread_mutex_unlock(&p->parent->buffer_mutex);
830         return -1;
831     }
832
833     progress[0] =
834     progress[1] = -1;
835
836     if (avctx->thread_safe_callbacks ||
837         avctx->get_buffer == avcodec_default_get_buffer) {
838         err = avctx->get_buffer(avctx, f);
839     } else {
840         p->requested_frame = f;
841         p->state = STATE_GET_BUFFER;
842         pthread_mutex_lock(&p->progress_mutex);
843         pthread_cond_signal(&p->progress_cond);
844
845         while (p->state != STATE_SETTING_UP)
846             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
847
848         err = p->result;
849
850         pthread_mutex_unlock(&p->progress_mutex);
851
852         if (!avctx->codec->update_thread_context)
853             ff_thread_finish_setup(avctx);
854     }
855
856     pthread_mutex_unlock(&p->parent->buffer_mutex);
857
858     /*
859      * Buffer age is difficult to keep track of between
860      * multiple threads, and the optimizations it allows
861      * are not worth the effort. It is disabled for now.
862      */
863     f->age = INT_MAX;
864
865     return err;
866 }
867
868 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
869 {
870     PerThreadContext *p = avctx->thread_opaque;
871     FrameThreadContext *fctx;
872
873     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
874         avctx->release_buffer(avctx, f);
875         return;
876     }
877
878     if (p->num_released_buffers >= MAX_BUFFERS) {
879         av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
880         return;
881     }
882
883     if(avctx->debug & FF_DEBUG_BUFFERS)
884         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
885
886     fctx = p->parent;
887     pthread_mutex_lock(&fctx->buffer_mutex);
888     p->released_buffers[p->num_released_buffers++] = *f;
889     pthread_mutex_unlock(&fctx->buffer_mutex);
890     memset(f->data, 0, sizeof(f->data));
891 }
892
893 /**
894  * Set the threading algorithms used.
895  *
896  * Threading requires more than one thread.
897  * Frame threading requires entire frames to be passed to the codec,
898  * and introduces extra decoding delay, so is incompatible with low_delay.
899  *
900  * @param avctx The context.
901  */
902 static void validate_thread_parameters(AVCodecContext *avctx)
903 {
904     int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
905                                 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
906                                 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
907                                 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
908     if (avctx->thread_count == 1) {
909         avctx->active_thread_type = 0;
910     } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
911         avctx->active_thread_type = FF_THREAD_FRAME;
912     } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
913                avctx->thread_type & FF_THREAD_SLICE) {
914         avctx->active_thread_type = FF_THREAD_SLICE;
915     }
916 }
917
918 int ff_thread_init(AVCodecContext *avctx)
919 {
920     if (avctx->thread_opaque) {
921         av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
922         return -1;
923     }
924
925 #if HAVE_W32THREADS
926     w32thread_init();
927 #endif
928
929     if (avctx->codec) {
930         validate_thread_parameters(avctx);
931
932         if (avctx->active_thread_type&FF_THREAD_SLICE)
933             return thread_init(avctx);
934         else if (avctx->active_thread_type&FF_THREAD_FRAME)
935             return frame_thread_init(avctx);
936     }
937
938     return 0;
939 }
940
941 void ff_thread_free(AVCodecContext *avctx)
942 {
943     if (avctx->active_thread_type&FF_THREAD_FRAME)
944         frame_thread_free(avctx, avctx->thread_count);
945     else
946         thread_free(avctx);
947 }