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