]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread.c
ac15fefd683aad72a30087df13f8e3d524545e23
[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         avctx->active_thread_type = 0;
242         return 0;
243     }
244
245     c = av_mallocz(sizeof(ThreadContext));
246     if (!c)
247         return -1;
248
249     c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
250     if (!c->workers) {
251         av_free(c);
252         return -1;
253     }
254
255     avctx->thread_opaque = c;
256     c->current_job = 0;
257     c->job_count = 0;
258     c->job_size = 0;
259     c->done = 0;
260     pthread_cond_init(&c->current_job_cond, NULL);
261     pthread_cond_init(&c->last_job_cond, NULL);
262     pthread_mutex_init(&c->current_job_lock, NULL);
263     pthread_mutex_lock(&c->current_job_lock);
264     for (i=0; i<thread_count; i++) {
265         if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
266            avctx->thread_count = i;
267            pthread_mutex_unlock(&c->current_job_lock);
268            ff_thread_free(avctx);
269            return -1;
270         }
271     }
272
273     avcodec_thread_park_workers(c, thread_count);
274
275     avctx->execute = avcodec_thread_execute;
276     avctx->execute2 = avcodec_thread_execute2;
277     return 0;
278 }
279
280 /**
281  * Codec worker thread.
282  *
283  * Automatically calls ff_thread_finish_setup() if the codec does
284  * not provide an update_thread_context method, or if the codec returns
285  * before calling it.
286  */
287 static attribute_align_arg void *frame_worker_thread(void *arg)
288 {
289     PerThreadContext *p = arg;
290     FrameThreadContext *fctx = p->parent;
291     AVCodecContext *avctx = p->avctx;
292     AVCodec *codec = avctx->codec;
293
294     while (1) {
295         if (p->state == STATE_INPUT_READY && !fctx->die) {
296             pthread_mutex_lock(&p->mutex);
297             while (p->state == STATE_INPUT_READY && !fctx->die)
298                 pthread_cond_wait(&p->input_cond, &p->mutex);
299             pthread_mutex_unlock(&p->mutex);
300         }
301
302         if (fctx->die) break;
303
304         if (!codec->update_thread_context && avctx->thread_safe_callbacks)
305             ff_thread_finish_setup(avctx);
306
307         pthread_mutex_lock(&p->mutex);
308         avcodec_get_frame_defaults(&p->frame);
309         p->got_frame = 0;
310         p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
311
312         if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
313
314         p->state = STATE_INPUT_READY;
315
316         pthread_mutex_lock(&p->progress_mutex);
317         pthread_cond_signal(&p->output_cond);
318         pthread_mutex_unlock(&p->progress_mutex);
319
320         pthread_mutex_unlock(&p->mutex);
321     }
322
323     return NULL;
324 }
325
326 /**
327  * Update the next thread's AVCodecContext with values from the reference thread's context.
328  *
329  * @param dst The destination context.
330  * @param src The source context.
331  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
332  */
333 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
334 {
335     int err = 0;
336
337     if (dst != src) {
338         dst->sub_id    = src->sub_id;
339         dst->time_base = src->time_base;
340         dst->width     = src->width;
341         dst->height    = src->height;
342         dst->pix_fmt   = src->pix_fmt;
343
344         dst->coded_width  = src->coded_width;
345         dst->coded_height = src->coded_height;
346
347         dst->has_b_frames = src->has_b_frames;
348         dst->idct_algo    = src->idct_algo;
349         dst->slice_count  = src->slice_count;
350
351         dst->bits_per_coded_sample = src->bits_per_coded_sample;
352         dst->sample_aspect_ratio   = src->sample_aspect_ratio;
353         dst->dtg_active_format     = src->dtg_active_format;
354
355         dst->profile = src->profile;
356         dst->level   = src->level;
357
358         dst->bits_per_raw_sample = src->bits_per_raw_sample;
359         dst->ticks_per_frame     = src->ticks_per_frame;
360         dst->color_primaries     = src->color_primaries;
361
362         dst->color_trc   = src->color_trc;
363         dst->colorspace  = src->colorspace;
364         dst->color_range = src->color_range;
365         dst->chroma_sample_location = src->chroma_sample_location;
366     }
367
368     if (for_user) {
369         dst->coded_frame = src->coded_frame;
370     } else {
371         if (dst->codec->update_thread_context)
372             err = dst->codec->update_thread_context(dst, src);
373     }
374
375     return err;
376 }
377
378 /**
379  * Update the next thread's AVCodecContext with values set by the user.
380  *
381  * @param dst The destination context.
382  * @param src The source context.
383  */
384 static void update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
385 {
386 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
387     dst->flags          = src->flags;
388
389     dst->draw_horiz_band= src->draw_horiz_band;
390     dst->get_buffer     = src->get_buffer;
391     dst->release_buffer = src->release_buffer;
392
393     dst->opaque   = src->opaque;
394     dst->dsp_mask = src->dsp_mask;
395     dst->debug    = src->debug;
396     dst->debug_mv = src->debug_mv;
397
398     dst->slice_flags = src->slice_flags;
399     dst->flags2      = src->flags2;
400
401     copy_fields(skip_loop_filter, bidir_refine);
402
403     dst->frame_number     = src->frame_number;
404     dst->reordered_opaque = src->reordered_opaque;
405 #undef copy_fields
406 }
407
408 static void free_progress(AVFrame *f)
409 {
410     PerThreadContext *p = f->owner->thread_opaque;
411     int *progress = f->thread_opaque;
412
413     p->progress_used[(progress - p->progress[0]) / 2] = 0;
414 }
415
416 /// Releases the buffers that this decoding thread was the last user of.
417 static void release_delayed_buffers(PerThreadContext *p)
418 {
419     FrameThreadContext *fctx = p->parent;
420
421     while (p->num_released_buffers > 0) {
422         AVFrame *f;
423
424         pthread_mutex_lock(&fctx->buffer_mutex);
425         f = &p->released_buffers[--p->num_released_buffers];
426         free_progress(f);
427         f->thread_opaque = NULL;
428
429         f->owner->release_buffer(f->owner, f);
430         pthread_mutex_unlock(&fctx->buffer_mutex);
431     }
432 }
433
434 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
435 {
436     FrameThreadContext *fctx = p->parent;
437     PerThreadContext *prev_thread = fctx->prev_thread;
438     AVCodec *codec = p->avctx->codec;
439     uint8_t *buf = p->avpkt.data;
440
441     if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
442
443     pthread_mutex_lock(&p->mutex);
444
445     release_delayed_buffers(p);
446
447     if (prev_thread) {
448         int err;
449         if (prev_thread->state == STATE_SETTING_UP) {
450             pthread_mutex_lock(&prev_thread->progress_mutex);
451             while (prev_thread->state == STATE_SETTING_UP)
452                 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
453             pthread_mutex_unlock(&prev_thread->progress_mutex);
454         }
455
456         err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
457         if (err) {
458             pthread_mutex_unlock(&p->mutex);
459             return err;
460         }
461     }
462
463     av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
464     p->avpkt = *avpkt;
465     p->avpkt.data = buf;
466     memcpy(buf, avpkt->data, avpkt->size);
467     memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
468
469     p->state = STATE_SETTING_UP;
470     pthread_cond_signal(&p->input_cond);
471     pthread_mutex_unlock(&p->mutex);
472
473     /*
474      * If the client doesn't have a thread-safe get_buffer(),
475      * then decoding threads call back to the main thread,
476      * and it calls back to the client here.
477      */
478
479     if (!p->avctx->thread_safe_callbacks &&
480          p->avctx->get_buffer != avcodec_default_get_buffer) {
481         while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
482             pthread_mutex_lock(&p->progress_mutex);
483             while (p->state == STATE_SETTING_UP)
484                 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
485
486             if (p->state == STATE_GET_BUFFER) {
487                 p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
488                 p->state  = STATE_SETTING_UP;
489                 pthread_cond_signal(&p->progress_cond);
490             }
491             pthread_mutex_unlock(&p->progress_mutex);
492         }
493     }
494
495     fctx->prev_thread = p;
496     fctx->next_decoding++;
497
498     return 0;
499 }
500
501 int ff_thread_decode_frame(AVCodecContext *avctx,
502                            AVFrame *picture, int *got_picture_ptr,
503                            AVPacket *avpkt)
504 {
505     FrameThreadContext *fctx = avctx->thread_opaque;
506     int finished = fctx->next_finished;
507     PerThreadContext *p;
508     int err;
509
510     /*
511      * Submit a packet to the next decoding thread.
512      */
513
514     p = &fctx->threads[fctx->next_decoding];
515     update_context_from_user(p->avctx, avctx);
516     err = submit_packet(p, avpkt);
517     if (err) return err;
518
519     /*
520      * If we're still receiving the initial packets, don't return a frame.
521      */
522
523     if (fctx->delaying && avpkt->size) {
524         if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
525
526         *got_picture_ptr=0;
527         return avpkt->size;
528     }
529
530     /*
531      * Return the next available frame from the oldest thread.
532      * If we're at the end of the stream, then we have to skip threads that
533      * didn't output a frame, because we don't want to accidentally signal
534      * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
535      */
536
537     do {
538         p = &fctx->threads[finished++];
539
540         if (p->state != STATE_INPUT_READY) {
541             pthread_mutex_lock(&p->progress_mutex);
542             while (p->state != STATE_INPUT_READY)
543                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
544             pthread_mutex_unlock(&p->progress_mutex);
545         }
546
547         *picture = p->frame;
548         *got_picture_ptr = p->got_frame;
549         picture->pkt_dts = p->avpkt.dts;
550
551         /*
552          * A later call with avkpt->size == 0 may loop over all threads,
553          * including this one, searching for a frame to return before being
554          * stopped by the "finished != fctx->next_finished" condition.
555          * Make sure we don't mistakenly return the same frame again.
556          */
557         p->got_frame = 0;
558
559         if (finished >= avctx->thread_count) finished = 0;
560     } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
561
562     update_context_from_thread(avctx, p->avctx, 1);
563
564     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
565
566     fctx->next_finished = finished;
567
568     /* return the size of the consumed packet if no error occurred */
569     return (p->result >= 0) ? avpkt->size : p->result;
570 }
571
572 void ff_thread_report_progress(AVFrame *f, int n, int field)
573 {
574     PerThreadContext *p;
575     int *progress = f->thread_opaque;
576
577     if (!progress || progress[field] >= n) return;
578
579     p = f->owner->thread_opaque;
580
581     if (f->owner->debug&FF_DEBUG_THREADS)
582         av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
583
584     pthread_mutex_lock(&p->progress_mutex);
585     progress[field] = n;
586     pthread_cond_broadcast(&p->progress_cond);
587     pthread_mutex_unlock(&p->progress_mutex);
588 }
589
590 void ff_thread_await_progress(AVFrame *f, int n, int field)
591 {
592     PerThreadContext *p;
593     int *progress = f->thread_opaque;
594
595     if (!progress || progress[field] >= n) return;
596
597     p = f->owner->thread_opaque;
598
599     if (f->owner->debug&FF_DEBUG_THREADS)
600         av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
601
602     pthread_mutex_lock(&p->progress_mutex);
603     while (progress[field] < n)
604         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
605     pthread_mutex_unlock(&p->progress_mutex);
606 }
607
608 void ff_thread_finish_setup(AVCodecContext *avctx) {
609     PerThreadContext *p = avctx->thread_opaque;
610
611     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
612
613     pthread_mutex_lock(&p->progress_mutex);
614     p->state = STATE_SETUP_FINISHED;
615     pthread_cond_broadcast(&p->progress_cond);
616     pthread_mutex_unlock(&p->progress_mutex);
617 }
618
619 /// Waits for all threads to finish.
620 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
621 {
622     int i;
623
624     for (i = 0; i < thread_count; i++) {
625         PerThreadContext *p = &fctx->threads[i];
626
627         if (p->state != STATE_INPUT_READY) {
628             pthread_mutex_lock(&p->progress_mutex);
629             while (p->state != STATE_INPUT_READY)
630                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
631             pthread_mutex_unlock(&p->progress_mutex);
632         }
633     }
634 }
635
636 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
637 {
638     FrameThreadContext *fctx = avctx->thread_opaque;
639     AVCodec *codec = avctx->codec;
640     int i;
641
642     park_frame_worker_threads(fctx, thread_count);
643
644     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
645         update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
646
647     fctx->die = 1;
648
649     for (i = 0; i < thread_count; i++) {
650         PerThreadContext *p = &fctx->threads[i];
651
652         pthread_mutex_lock(&p->mutex);
653         pthread_cond_signal(&p->input_cond);
654         pthread_mutex_unlock(&p->mutex);
655
656         if (p->thread_init)
657             pthread_join(p->thread, NULL);
658
659         if (codec->close)
660             codec->close(p->avctx);
661
662         avctx->codec = NULL;
663
664         release_delayed_buffers(p);
665     }
666
667     for (i = 0; i < thread_count; i++) {
668         PerThreadContext *p = &fctx->threads[i];
669
670         avcodec_default_free_buffers(p->avctx);
671
672         pthread_mutex_destroy(&p->mutex);
673         pthread_mutex_destroy(&p->progress_mutex);
674         pthread_cond_destroy(&p->input_cond);
675         pthread_cond_destroy(&p->progress_cond);
676         pthread_cond_destroy(&p->output_cond);
677         av_freep(&p->avpkt.data);
678
679         if (i) {
680             av_freep(&p->avctx->priv_data);
681             av_freep(&p->avctx->internal);
682         }
683
684         av_freep(&p->avctx);
685     }
686
687     av_freep(&fctx->threads);
688     pthread_mutex_destroy(&fctx->buffer_mutex);
689     av_freep(&avctx->thread_opaque);
690 }
691
692 static int frame_thread_init(AVCodecContext *avctx)
693 {
694     int thread_count = avctx->thread_count;
695     AVCodec *codec = avctx->codec;
696     AVCodecContext *src = avctx;
697     FrameThreadContext *fctx;
698     int i, err = 0;
699
700     if (thread_count <= 1) {
701         avctx->active_thread_type = 0;
702         return 0;
703     }
704
705     avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
706
707     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
708     pthread_mutex_init(&fctx->buffer_mutex, NULL);
709     fctx->delaying = 1;
710
711     for (i = 0; i < thread_count; i++) {
712         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
713         PerThreadContext *p  = &fctx->threads[i];
714
715         pthread_mutex_init(&p->mutex, NULL);
716         pthread_mutex_init(&p->progress_mutex, NULL);
717         pthread_cond_init(&p->input_cond, NULL);
718         pthread_cond_init(&p->progress_cond, NULL);
719         pthread_cond_init(&p->output_cond, NULL);
720
721         p->parent = fctx;
722         p->avctx  = copy;
723
724         if (!copy) {
725             err = AVERROR(ENOMEM);
726             goto error;
727         }
728
729         *copy = *src;
730         copy->thread_opaque = p;
731         copy->pkt = &p->avpkt;
732
733         if (!i) {
734             src = copy;
735
736             if (codec->init)
737                 err = codec->init(copy);
738
739             update_context_from_thread(avctx, copy, 1);
740         } else {
741             copy->priv_data = av_malloc(codec->priv_data_size);
742             if (!copy->priv_data) {
743                 err = AVERROR(ENOMEM);
744                 goto error;
745             }
746             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
747             copy->internal = av_malloc(sizeof(AVCodecInternal));
748             if (!copy->internal) {
749                 err = AVERROR(ENOMEM);
750                 goto error;
751             }
752             *(copy->internal) = *(src->internal);
753             copy->internal->is_copy = 1;
754
755             if (codec->init_thread_copy)
756                 err = codec->init_thread_copy(copy);
757         }
758
759         if (err) goto error;
760
761         if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
762             p->thread_init = 1;
763     }
764
765     return 0;
766
767 error:
768     frame_thread_free(avctx, i+1);
769
770     return err;
771 }
772
773 void ff_thread_flush(AVCodecContext *avctx)
774 {
775     FrameThreadContext *fctx = avctx->thread_opaque;
776
777     if (!avctx->thread_opaque) return;
778
779     park_frame_worker_threads(fctx, avctx->thread_count);
780     if (fctx->prev_thread) {
781         if (fctx->prev_thread != &fctx->threads[0])
782             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
783         if (avctx->codec->flush)
784             avctx->codec->flush(fctx->threads[0].avctx);
785     }
786
787     fctx->next_decoding = fctx->next_finished = 0;
788     fctx->delaying = 1;
789     fctx->prev_thread = NULL;
790 }
791
792 static int *allocate_progress(PerThreadContext *p)
793 {
794     int i;
795
796     for (i = 0; i < MAX_BUFFERS; i++)
797         if (!p->progress_used[i]) break;
798
799     if (i == MAX_BUFFERS) {
800         av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
801         return NULL;
802     }
803
804     p->progress_used[i] = 1;
805
806     return p->progress[i];
807 }
808
809 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
810 {
811     PerThreadContext *p = avctx->thread_opaque;
812     int *progress, err;
813
814     f->owner = avctx;
815
816     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
817         f->thread_opaque = NULL;
818         return avctx->get_buffer(avctx, f);
819     }
820
821     if (p->state != STATE_SETTING_UP &&
822         (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
823         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
824         return -1;
825     }
826
827     pthread_mutex_lock(&p->parent->buffer_mutex);
828     f->thread_opaque = progress = allocate_progress(p);
829
830     if (!progress) {
831         pthread_mutex_unlock(&p->parent->buffer_mutex);
832         return -1;
833     }
834
835     progress[0] =
836     progress[1] = -1;
837
838     if (avctx->thread_safe_callbacks ||
839         avctx->get_buffer == avcodec_default_get_buffer) {
840         err = avctx->get_buffer(avctx, f);
841     } else {
842         p->requested_frame = f;
843         p->state = STATE_GET_BUFFER;
844         pthread_mutex_lock(&p->progress_mutex);
845         pthread_cond_signal(&p->progress_cond);
846
847         while (p->state != STATE_SETTING_UP)
848             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
849
850         err = p->result;
851
852         pthread_mutex_unlock(&p->progress_mutex);
853
854         if (!avctx->codec->update_thread_context)
855             ff_thread_finish_setup(avctx);
856     }
857
858     pthread_mutex_unlock(&p->parent->buffer_mutex);
859
860     return err;
861 }
862
863 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
864 {
865     PerThreadContext *p = avctx->thread_opaque;
866     FrameThreadContext *fctx;
867
868     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
869         avctx->release_buffer(avctx, f);
870         return;
871     }
872
873     if (p->num_released_buffers >= MAX_BUFFERS) {
874         av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
875         return;
876     }
877
878     if(avctx->debug & FF_DEBUG_BUFFERS)
879         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
880
881     fctx = p->parent;
882     pthread_mutex_lock(&fctx->buffer_mutex);
883     p->released_buffers[p->num_released_buffers++] = *f;
884     pthread_mutex_unlock(&fctx->buffer_mutex);
885     memset(f->data, 0, sizeof(f->data));
886 }
887
888 /**
889  * Set the threading algorithms used.
890  *
891  * Threading requires more than one thread.
892  * Frame threading requires entire frames to be passed to the codec,
893  * and introduces extra decoding delay, so is incompatible with low_delay.
894  *
895  * @param avctx The context.
896  */
897 static void validate_thread_parameters(AVCodecContext *avctx)
898 {
899     int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
900                                 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
901                                 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
902                                 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
903     if (avctx->thread_count == 1) {
904         avctx->active_thread_type = 0;
905     } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
906         avctx->active_thread_type = FF_THREAD_FRAME;
907     } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
908                avctx->thread_type & FF_THREAD_SLICE) {
909         avctx->active_thread_type = FF_THREAD_SLICE;
910     }
911 }
912
913 int ff_thread_init(AVCodecContext *avctx)
914 {
915     if (avctx->thread_opaque) {
916         av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
917         return -1;
918     }
919
920 #if HAVE_W32THREADS
921     w32thread_init();
922 #endif
923
924     if (avctx->codec) {
925         validate_thread_parameters(avctx);
926
927         if (avctx->active_thread_type&FF_THREAD_SLICE)
928             return thread_init(avctx);
929         else if (avctx->active_thread_type&FF_THREAD_FRAME)
930             return frame_thread_init(avctx);
931     }
932
933     return 0;
934 }
935
936 void ff_thread_free(AVCodecContext *avctx)
937 {
938     if (avctx->active_thread_type&FF_THREAD_FRAME)
939         frame_thread_free(avctx, avctx->thread_count);
940     else
941         thread_free(avctx);
942 }