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