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