]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread.c
h264: rewrite has_b_frame calculation code,
[ffmpeg] / libavcodec / pthread.c
1 /*
2  * Copyright (c) 2004 Roman Shaposhnik
3  * Copyright (c) 2008 Alexander Strange (astrange@ithinksw.com)
4  *
5  * Many thanks to Steven M. Schultz for providing clever ideas and
6  * to Michael Niedermayer <michaelni@gmx.at> for writing initial
7  * implementation.
8  *
9  * This file is part of FFmpeg.
10  *
11  * FFmpeg is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * FFmpeg is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with FFmpeg; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24  */
25
26 /**
27  * @file
28  * Multithreading support functions
29  * @see doc/multithreading.txt
30  */
31
32 #include "config.h"
33 #include "avcodec.h"
34 #include "internal.h"
35 #include "thread.h"
36
37 #if HAVE_PTHREADS
38 #include <pthread.h>
39 #elif HAVE_W32THREADS
40 #include "w32pthreads.h"
41 #elif HAVE_OS2THREADS
42 #include "os2threads.h"
43 #endif
44
45 typedef int (action_func)(AVCodecContext *c, void *arg);
46 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
47
48 typedef struct ThreadContext {
49     pthread_t *workers;
50     action_func *func;
51     action_func2 *func2;
52     void *args;
53     int *rets;
54     int rets_count;
55     int job_count;
56     int job_size;
57
58     pthread_cond_t last_job_cond;
59     pthread_cond_t current_job_cond;
60     pthread_mutex_t current_job_lock;
61     int current_job;
62     int done;
63 } ThreadContext;
64
65 /// Max number of frame buffers that can be allocated when using frame threads.
66 #define MAX_BUFFERS (32+1)
67
68 /**
69  * Context used by codec threads and stored in their AVCodecContext thread_opaque.
70  */
71 typedef struct PerThreadContext {
72     struct FrameThreadContext *parent;
73
74     pthread_t      thread;
75     pthread_cond_t input_cond;      ///< Used to wait for a new packet from the main thread.
76     pthread_cond_t progress_cond;   ///< Used by child threads to wait for progress to change.
77     pthread_cond_t output_cond;     ///< Used by the main thread to wait for frames to finish.
78
79     pthread_mutex_t mutex;          ///< Mutex used to protect the contents of the PerThreadContext.
80     pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
81
82     AVCodecContext *avctx;          ///< Context used to decode packets passed to this thread.
83
84     AVPacket       avpkt;           ///< Input packet (for decoding) or output (for encoding).
85     int            allocated_buf_size; ///< Size allocated for avpkt.data
86
87     AVFrame frame;                  ///< Output frame (for decoding) or input (for encoding).
88     int     got_frame;              ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
89     int     result;                 ///< The result of the last codec decode/encode() call.
90
91     enum {
92         STATE_INPUT_READY,          ///< Set when the thread is awaiting a packet.
93         STATE_SETTING_UP,           ///< Set before the codec has called ff_thread_finish_setup().
94         STATE_GET_BUFFER,           /**<
95                                      * Set when the codec calls get_buffer().
96                                      * State is returned to STATE_SETTING_UP afterwards.
97                                      */
98         STATE_SETUP_FINISHED        ///< Set after the codec has called ff_thread_finish_setup().
99     } state;
100
101     /**
102      * Array of frames passed to ff_thread_release_buffer().
103      * Frames are released after all threads referencing them are finished.
104      */
105     AVFrame released_buffers[MAX_BUFFERS];
106     int     num_released_buffers;
107
108     /**
109      * Array of progress values used by ff_thread_get_buffer().
110      */
111     int     progress[MAX_BUFFERS][2];
112     uint8_t progress_used[MAX_BUFFERS];
113
114     AVFrame *requested_frame;       ///< AVFrame the codec passed to get_buffer()
115 } PerThreadContext;
116
117 /**
118  * Context stored in the client AVCodecContext thread_opaque.
119  */
120 typedef struct FrameThreadContext {
121     PerThreadContext *threads;     ///< The contexts for each thread.
122     PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
123
124     pthread_mutex_t buffer_mutex;  ///< Mutex used to protect get/release_buffer().
125
126     int next_decoding;             ///< The next context to submit a packet to.
127     int next_finished;             ///< The next context to return output from.
128
129     int delaying;                  /**<
130                                     * Set for the first N packets, where N is the number of threads.
131                                     * While it is set, ff_thread_en/decode_frame won't return any results.
132                                     */
133
134     int die;                       ///< Set when threads should exit.
135 } FrameThreadContext;
136
137 static void* attribute_align_arg worker(void *v)
138 {
139     AVCodecContext *avctx = v;
140     ThreadContext *c = avctx->thread_opaque;
141     int our_job = c->job_count;
142     int thread_count = avctx->thread_count;
143     int self_id;
144
145     pthread_mutex_lock(&c->current_job_lock);
146     self_id = c->current_job++;
147     for (;;){
148         while (our_job >= c->job_count) {
149             if (c->current_job == thread_count + c->job_count)
150                 pthread_cond_signal(&c->last_job_cond);
151
152             pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
153             our_job = self_id;
154
155             if (c->done) {
156                 pthread_mutex_unlock(&c->current_job_lock);
157                 return NULL;
158             }
159         }
160         pthread_mutex_unlock(&c->current_job_lock);
161
162         c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
163                                                    c->func2(avctx, c->args, our_job, self_id);
164
165         pthread_mutex_lock(&c->current_job_lock);
166         our_job = c->current_job++;
167     }
168 }
169
170 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
171 {
172     pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
173     pthread_mutex_unlock(&c->current_job_lock);
174 }
175
176 static void thread_free(AVCodecContext *avctx)
177 {
178     ThreadContext *c = avctx->thread_opaque;
179     int i;
180
181     pthread_mutex_lock(&c->current_job_lock);
182     c->done = 1;
183     pthread_cond_broadcast(&c->current_job_cond);
184     pthread_mutex_unlock(&c->current_job_lock);
185
186     for (i=0; i<avctx->thread_count; i++)
187          pthread_join(c->workers[i], NULL);
188
189     pthread_mutex_destroy(&c->current_job_lock);
190     pthread_cond_destroy(&c->current_job_cond);
191     pthread_cond_destroy(&c->last_job_cond);
192     av_free(c->workers);
193     av_freep(&avctx->thread_opaque);
194 }
195
196 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
197 {
198     ThreadContext *c= avctx->thread_opaque;
199     int dummy_ret;
200
201     if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
202         return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
203
204     if (job_count <= 0)
205         return 0;
206
207     pthread_mutex_lock(&c->current_job_lock);
208
209     c->current_job = avctx->thread_count;
210     c->job_count = job_count;
211     c->job_size = job_size;
212     c->args = arg;
213     c->func = func;
214     if (ret) {
215         c->rets = ret;
216         c->rets_count = job_count;
217     } else {
218         c->rets = &dummy_ret;
219         c->rets_count = 1;
220     }
221     pthread_cond_broadcast(&c->current_job_cond);
222
223     avcodec_thread_park_workers(c, avctx->thread_count);
224
225     return 0;
226 }
227
228 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
229 {
230     ThreadContext *c= avctx->thread_opaque;
231     c->func2 = func2;
232     return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
233 }
234
235 static int thread_init(AVCodecContext *avctx)
236 {
237     int i;
238     ThreadContext *c;
239     int thread_count = avctx->thread_count;
240
241     if (thread_count <= 1)
242         return 0;
243
244     c = av_mallocz(sizeof(ThreadContext));
245     if (!c)
246         return -1;
247
248     c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
249     if (!c->workers) {
250         av_free(c);
251         return -1;
252     }
253
254     avctx->thread_opaque = c;
255     c->current_job = 0;
256     c->job_count = 0;
257     c->job_size = 0;
258     c->done = 0;
259     pthread_cond_init(&c->current_job_cond, NULL);
260     pthread_cond_init(&c->last_job_cond, NULL);
261     pthread_mutex_init(&c->current_job_lock, NULL);
262     pthread_mutex_lock(&c->current_job_lock);
263     for (i=0; i<thread_count; i++) {
264         if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
265            avctx->thread_count = i;
266            pthread_mutex_unlock(&c->current_job_lock);
267            ff_thread_free(avctx);
268            return -1;
269         }
270     }
271
272     avcodec_thread_park_workers(c, thread_count);
273
274     avctx->execute = avcodec_thread_execute;
275     avctx->execute2 = avcodec_thread_execute2;
276     return 0;
277 }
278
279 /**
280  * Codec worker thread.
281  *
282  * Automatically calls ff_thread_finish_setup() if the codec does
283  * not provide an update_thread_context method, or if the codec returns
284  * before calling it.
285  */
286 static attribute_align_arg void *frame_worker_thread(void *arg)
287 {
288     PerThreadContext *p = arg;
289     FrameThreadContext *fctx = p->parent;
290     AVCodecContext *avctx = p->avctx;
291     AVCodec *codec = avctx->codec;
292
293     while (1) {
294         if (p->state == STATE_INPUT_READY && !fctx->die) {
295             pthread_mutex_lock(&p->mutex);
296             while (p->state == STATE_INPUT_READY && !fctx->die)
297                 pthread_cond_wait(&p->input_cond, &p->mutex);
298             pthread_mutex_unlock(&p->mutex);
299         }
300
301         if (fctx->die) break;
302
303         if (!codec->update_thread_context && avctx->thread_safe_callbacks)
304             ff_thread_finish_setup(avctx);
305
306         pthread_mutex_lock(&p->mutex);
307         avcodec_get_frame_defaults(&p->frame);
308         p->got_frame = 0;
309         p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
310
311         if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
312
313         p->state = STATE_INPUT_READY;
314
315         pthread_mutex_lock(&p->progress_mutex);
316         pthread_cond_signal(&p->output_cond);
317         pthread_mutex_unlock(&p->progress_mutex);
318
319         pthread_mutex_unlock(&p->mutex);
320     }
321
322     return NULL;
323 }
324
325 /**
326  * Updates the next thread's AVCodecContext with values from the reference thread's context.
327  *
328  * @param dst The destination context.
329  * @param src The source context.
330  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
331  */
332 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
333 {
334     int err = 0;
335
336     if (dst != src) {
337         dst->sub_id    = src->sub_id;
338         dst->time_base = src->time_base;
339         dst->width     = src->width;
340         dst->height    = src->height;
341         dst->pix_fmt   = src->pix_fmt;
342
343         dst->coded_width  = src->coded_width;
344         dst->coded_height = src->coded_height;
345
346         dst->has_b_frames = src->has_b_frames;
347         dst->idct_algo    = src->idct_algo;
348         dst->slice_count  = src->slice_count;
349
350         dst->bits_per_coded_sample = src->bits_per_coded_sample;
351         dst->sample_aspect_ratio   = src->sample_aspect_ratio;
352         dst->dtg_active_format     = src->dtg_active_format;
353
354         dst->profile = src->profile;
355         dst->level   = src->level;
356
357         dst->bits_per_raw_sample = src->bits_per_raw_sample;
358         dst->ticks_per_frame     = src->ticks_per_frame;
359         dst->color_primaries     = src->color_primaries;
360
361         dst->color_trc   = src->color_trc;
362         dst->colorspace  = src->colorspace;
363         dst->color_range = src->color_range;
364         dst->chroma_sample_location = src->chroma_sample_location;
365     }
366
367     if (for_user) {
368         dst->delay         = src->thread_count - 1;
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
497     return 0;
498 }
499
500 int ff_thread_decode_frame(AVCodecContext *avctx,
501                            AVFrame *picture, int *got_picture_ptr,
502                            AVPacket *avpkt)
503 {
504     FrameThreadContext *fctx = avctx->thread_opaque;
505     int finished = fctx->next_finished;
506     PerThreadContext *p;
507     int err;
508
509     /*
510      * Submit a packet to the next decoding thread.
511      */
512
513     p = &fctx->threads[fctx->next_decoding];
514     update_context_from_user(p->avctx, avctx);
515     err = submit_packet(p, avpkt);
516     if (err) return err;
517
518     fctx->next_decoding++;
519
520     /*
521      * If we're still receiving the initial packets, don't return a frame.
522      */
523
524     if (fctx->delaying && avpkt->size) {
525         if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
526
527         *got_picture_ptr=0;
528         return 0;
529     }
530
531     /*
532      * Return the next available frame from the oldest thread.
533      * If we're at the end of the stream, then we have to skip threads that
534      * didn't output a frame, because we don't want to accidentally signal
535      * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
536      */
537
538     do {
539         p = &fctx->threads[finished++];
540
541         if (p->state != STATE_INPUT_READY) {
542             pthread_mutex_lock(&p->progress_mutex);
543             while (p->state != STATE_INPUT_READY)
544                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
545             pthread_mutex_unlock(&p->progress_mutex);
546         }
547
548         *picture = p->frame;
549         *got_picture_ptr = p->got_frame;
550         picture->pkt_dts = p->avpkt.dts;
551
552         /*
553          * A later call with avkpt->size == 0 may loop over all threads,
554          * including this one, searching for a frame to return before being
555          * stopped by the "finished != fctx->next_finished" condition.
556          * Make sure we don't mistakenly return the same frame again.
557          */
558         p->got_frame = 0;
559
560         if (finished >= avctx->thread_count) finished = 0;
561     } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
562
563     update_context_from_thread(avctx, p->avctx, 1);
564
565     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
566
567     fctx->next_finished = finished;
568
569     return 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     if(p->state == STATE_SETUP_FINISHED){
614         av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
615     }
616
617     pthread_mutex_lock(&p->progress_mutex);
618     p->state = STATE_SETUP_FINISHED;
619     pthread_cond_broadcast(&p->progress_cond);
620     pthread_mutex_unlock(&p->progress_mutex);
621 }
622
623 /// Waits for all threads to finish.
624 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
625 {
626     int i;
627
628     for (i = 0; i < thread_count; i++) {
629         PerThreadContext *p = &fctx->threads[i];
630
631         if (p->state != STATE_INPUT_READY) {
632             pthread_mutex_lock(&p->progress_mutex);
633             while (p->state != STATE_INPUT_READY)
634                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
635             pthread_mutex_unlock(&p->progress_mutex);
636         }
637     }
638 }
639
640 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
641 {
642     FrameThreadContext *fctx = avctx->thread_opaque;
643     AVCodec *codec = avctx->codec;
644     int i;
645
646     park_frame_worker_threads(fctx, thread_count);
647
648     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
649         update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
650
651     fctx->die = 1;
652
653     for (i = 0; i < thread_count; i++) {
654         PerThreadContext *p = &fctx->threads[i];
655
656         pthread_mutex_lock(&p->mutex);
657         pthread_cond_signal(&p->input_cond);
658         pthread_mutex_unlock(&p->mutex);
659
660         pthread_join(p->thread, NULL);
661
662         if (codec->close)
663             codec->close(p->avctx);
664
665         avctx->codec = NULL;
666
667         release_delayed_buffers(p);
668     }
669
670     for (i = 0; i < thread_count; i++) {
671         PerThreadContext *p = &fctx->threads[i];
672
673         avcodec_default_free_buffers(p->avctx);
674
675         pthread_mutex_destroy(&p->mutex);
676         pthread_mutex_destroy(&p->progress_mutex);
677         pthread_cond_destroy(&p->input_cond);
678         pthread_cond_destroy(&p->progress_cond);
679         pthread_cond_destroy(&p->output_cond);
680         av_freep(&p->avpkt.data);
681
682         if (i)
683             av_freep(&p->avctx->priv_data);
684
685         av_freep(&p->avctx);
686     }
687
688     av_freep(&fctx->threads);
689     pthread_mutex_destroy(&fctx->buffer_mutex);
690     av_freep(&avctx->thread_opaque);
691 }
692
693 static int frame_thread_init(AVCodecContext *avctx)
694 {
695     int thread_count = avctx->thread_count;
696     AVCodec *codec = avctx->codec;
697     AVCodecContext *src = avctx;
698     FrameThreadContext *fctx;
699     int i, err = 0;
700
701     if (thread_count <= 1) {
702         avctx->active_thread_type = 0;
703         return 0;
704     }
705
706     avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
707
708     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
709     pthread_mutex_init(&fctx->buffer_mutex, NULL);
710     fctx->delaying = 1;
711
712     for (i = 0; i < thread_count; i++) {
713         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
714         PerThreadContext *p  = &fctx->threads[i];
715
716         pthread_mutex_init(&p->mutex, NULL);
717         pthread_mutex_init(&p->progress_mutex, NULL);
718         pthread_cond_init(&p->input_cond, NULL);
719         pthread_cond_init(&p->progress_cond, NULL);
720         pthread_cond_init(&p->output_cond, NULL);
721
722         p->parent = fctx;
723         p->avctx  = copy;
724
725         *copy = *src;
726         copy->thread_opaque = p;
727         copy->pkt = &p->avpkt;
728
729         if (!i) {
730             src = copy;
731
732             if (codec->init)
733                 err = codec->init(copy);
734
735             update_context_from_thread(avctx, copy, 1);
736         } else {
737             copy->is_copy   = 1;
738             copy->priv_data = av_malloc(codec->priv_data_size);
739             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
740
741             if (codec->init_thread_copy)
742                 err = codec->init_thread_copy(copy);
743         }
744
745         if (err) goto error;
746
747         pthread_create(&p->thread, NULL, frame_worker_thread, p);
748     }
749
750     return 0;
751
752 error:
753     frame_thread_free(avctx, i+1);
754
755     return err;
756 }
757
758 void ff_thread_flush(AVCodecContext *avctx)
759 {
760     FrameThreadContext *fctx = avctx->thread_opaque;
761
762     if (!avctx->thread_opaque) return;
763
764     park_frame_worker_threads(fctx, avctx->thread_count);
765     if (fctx->prev_thread) {
766         if (fctx->prev_thread != &fctx->threads[0])
767             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
768         if (avctx->codec->flush)
769             avctx->codec->flush(fctx->threads[0].avctx);
770     }
771
772     fctx->next_decoding = fctx->next_finished = 0;
773     fctx->delaying = 1;
774     fctx->prev_thread = NULL;
775 }
776
777 static int *allocate_progress(PerThreadContext *p)
778 {
779     int i;
780
781     for (i = 0; i < MAX_BUFFERS; i++)
782         if (!p->progress_used[i]) break;
783
784     if (i == MAX_BUFFERS) {
785         av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
786         return NULL;
787     }
788
789     p->progress_used[i] = 1;
790
791     return p->progress[i];
792 }
793
794 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
795 {
796     PerThreadContext *p = avctx->thread_opaque;
797     int *progress, err;
798
799     f->owner = avctx;
800
801     ff_init_buffer_info(avctx, f);
802
803     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
804         f->thread_opaque = NULL;
805         return avctx->get_buffer(avctx, f);
806     }
807
808     if (p->state != STATE_SETTING_UP &&
809         (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
810         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
811         return -1;
812     }
813
814     pthread_mutex_lock(&p->parent->buffer_mutex);
815     f->thread_opaque = progress = allocate_progress(p);
816
817     if (!progress) {
818         pthread_mutex_unlock(&p->parent->buffer_mutex);
819         return -1;
820     }
821
822     progress[0] =
823     progress[1] = -1;
824
825     if (avctx->thread_safe_callbacks ||
826         avctx->get_buffer == avcodec_default_get_buffer) {
827         err = avctx->get_buffer(avctx, f);
828     } else {
829         p->requested_frame = f;
830         p->state = STATE_GET_BUFFER;
831         pthread_mutex_lock(&p->progress_mutex);
832         pthread_cond_signal(&p->progress_cond);
833
834         while (p->state != STATE_SETTING_UP)
835             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
836
837         err = p->result;
838
839         pthread_mutex_unlock(&p->progress_mutex);
840
841         if (!avctx->codec->update_thread_context)
842             ff_thread_finish_setup(avctx);
843     }
844
845     pthread_mutex_unlock(&p->parent->buffer_mutex);
846
847     /*
848      * Buffer age is difficult to keep track of between
849      * multiple threads, and the optimizations it allows
850      * are not worth the effort. It is disabled for now.
851      */
852     f->age = INT_MAX;
853
854     return err;
855 }
856
857 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
858 {
859     PerThreadContext *p = avctx->thread_opaque;
860     FrameThreadContext *fctx;
861
862     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
863         avctx->release_buffer(avctx, f);
864         return;
865     }
866
867     if (p->num_released_buffers >= MAX_BUFFERS) {
868         av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
869         return;
870     }
871
872     if(avctx->debug & FF_DEBUG_BUFFERS)
873         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p, %d buffers used\n",
874                                     f, f->owner->internal_buffer_count);
875
876     fctx = p->parent;
877     pthread_mutex_lock(&fctx->buffer_mutex);
878     p->released_buffers[p->num_released_buffers++] = *f;
879     pthread_mutex_unlock(&fctx->buffer_mutex);
880     memset(f->data, 0, sizeof(f->data));
881 }
882
883 /**
884  * Set the threading algorithms used.
885  *
886  * Threading requires more than one thread.
887  * Frame threading requires entire frames to be passed to the codec,
888  * and introduces extra decoding delay, so is incompatible with low_delay.
889  *
890  * @param avctx The context.
891  */
892 static void validate_thread_parameters(AVCodecContext *avctx)
893 {
894     int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
895                                 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
896                                 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
897                                 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
898     if (avctx->thread_count == 1) {
899         avctx->active_thread_type = 0;
900     } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
901         avctx->active_thread_type = FF_THREAD_FRAME;
902     } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
903                avctx->thread_type & FF_THREAD_SLICE) {
904         avctx->active_thread_type = FF_THREAD_SLICE;
905     }
906 }
907
908 int ff_thread_init(AVCodecContext *avctx)
909 {
910     if (avctx->thread_opaque) {
911         av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
912         return -1;
913     }
914
915 #if HAVE_W32THREADS
916     w32thread_init();
917 #endif
918
919     if (avctx->codec) {
920         validate_thread_parameters(avctx);
921
922         if (avctx->active_thread_type&FF_THREAD_SLICE)
923             return thread_init(avctx);
924         else if (avctx->active_thread_type&FF_THREAD_FRAME)
925             return frame_thread_init(avctx);
926     }
927
928     return 0;
929 }
930
931 void ff_thread_free(AVCodecContext *avctx)
932 {
933     if (avctx->active_thread_type&FF_THREAD_FRAME)
934         frame_thread_free(avctx, avctx->thread_count);
935     else
936         thread_free(avctx);
937 }