]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread.c
pthread: drop avcodec_ prefixes from static functions
[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
34 #include "avcodec.h"
35 #include "internal.h"
36 #include "thread.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/common.h"
39 #include "libavutil/cpu.h"
40 #include "libavutil/internal.h"
41
42 #if HAVE_PTHREADS
43 #include <pthread.h>
44 #elif HAVE_W32THREADS
45 #include "compat/w32pthreads.h"
46 #endif
47
48 typedef int (action_func)(AVCodecContext *c, void *arg);
49 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
50
51 typedef struct ThreadContext {
52     pthread_t *workers;
53     action_func *func;
54     action_func2 *func2;
55     void *args;
56     int *rets;
57     int rets_count;
58     int job_count;
59     int job_size;
60
61     pthread_cond_t last_job_cond;
62     pthread_cond_t current_job_cond;
63     pthread_mutex_t current_job_lock;
64     unsigned current_execute;
65     int current_job;
66     int done;
67 } ThreadContext;
68
69 /**
70  * Context used by codec threads and stored in their AVCodecContext thread_opaque.
71  */
72 typedef struct PerThreadContext {
73     struct FrameThreadContext *parent;
74
75     pthread_t      thread;
76     int            thread_init;
77     pthread_cond_t input_cond;      ///< Used to wait for a new packet from the main thread.
78     pthread_cond_t progress_cond;   ///< Used by child threads to wait for progress to change.
79     pthread_cond_t output_cond;     ///< Used by the main thread to wait for frames to finish.
80
81     pthread_mutex_t mutex;          ///< Mutex used to protect the contents of the PerThreadContext.
82     pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
83
84     AVCodecContext *avctx;          ///< Context used to decode packets passed to this thread.
85
86     AVPacket       avpkt;           ///< Input packet (for decoding) or output (for encoding).
87     uint8_t       *buf;             ///< backup storage for packet data when the input packet is not refcounted
88     int            allocated_buf_size; ///< Size allocated for buf
89
90     AVFrame frame;                  ///< Output frame (for decoding) or input (for encoding).
91     int     got_frame;              ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
92     int     result;                 ///< The result of the last codec decode/encode() call.
93
94     enum {
95         STATE_INPUT_READY,          ///< Set when the thread is awaiting a packet.
96         STATE_SETTING_UP,           ///< Set before the codec has called ff_thread_finish_setup().
97         STATE_GET_BUFFER,           /**<
98                                      * Set when the codec calls get_buffer().
99                                      * State is returned to STATE_SETTING_UP afterwards.
100                                      */
101         STATE_SETUP_FINISHED        ///< Set after the codec has called ff_thread_finish_setup().
102     } state;
103
104     /**
105      * Array of frames passed to ff_thread_release_buffer().
106      * Frames are released after all threads referencing them are finished.
107      */
108     AVFrame *released_buffers;
109     int  num_released_buffers;
110     int      released_buffers_allocated;
111
112     AVFrame *requested_frame;       ///< AVFrame the codec passed to get_buffer()
113     int      requested_flags;       ///< flags passed to get_buffer() for requested_frame
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
137 /* H264 slice threading seems to be buggy with more than 16 threads,
138  * limit the number of threads to 16 for automatic detection */
139 #define MAX_AUTO_THREADS 16
140
141 static void* attribute_align_arg worker(void *v)
142 {
143     AVCodecContext *avctx = v;
144     ThreadContext *c = avctx->thread_opaque;
145     unsigned last_execute = 0;
146     int our_job = c->job_count;
147     int thread_count = avctx->thread_count;
148     int self_id;
149
150     pthread_mutex_lock(&c->current_job_lock);
151     self_id = c->current_job++;
152     for (;;){
153         while (our_job >= c->job_count) {
154             if (c->current_job == thread_count + c->job_count)
155                 pthread_cond_signal(&c->last_job_cond);
156
157             while (last_execute == c->current_execute && !c->done)
158                 pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
159             last_execute = c->current_execute;
160             our_job = self_id;
161
162             if (c->done) {
163                 pthread_mutex_unlock(&c->current_job_lock);
164                 return NULL;
165             }
166         }
167         pthread_mutex_unlock(&c->current_job_lock);
168
169         c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
170                                                    c->func2(avctx, c->args, our_job, self_id);
171
172         pthread_mutex_lock(&c->current_job_lock);
173         our_job = c->current_job++;
174     }
175 }
176
177 static av_always_inline void thread_park_workers(ThreadContext *c, int thread_count)
178 {
179     while (c->current_job != thread_count + c->job_count)
180         pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
181     pthread_mutex_unlock(&c->current_job_lock);
182 }
183
184 static void thread_free(AVCodecContext *avctx)
185 {
186     ThreadContext *c = avctx->thread_opaque;
187     int i;
188
189     pthread_mutex_lock(&c->current_job_lock);
190     c->done = 1;
191     pthread_cond_broadcast(&c->current_job_cond);
192     pthread_mutex_unlock(&c->current_job_lock);
193
194     for (i=0; i<avctx->thread_count; i++)
195          pthread_join(c->workers[i], NULL);
196
197     pthread_mutex_destroy(&c->current_job_lock);
198     pthread_cond_destroy(&c->current_job_cond);
199     pthread_cond_destroy(&c->last_job_cond);
200     av_free(c->workers);
201     av_freep(&avctx->thread_opaque);
202 }
203
204 static int thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
205 {
206     ThreadContext *c= avctx->thread_opaque;
207     int dummy_ret;
208
209     if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
210         return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
211
212     if (job_count <= 0)
213         return 0;
214
215     pthread_mutex_lock(&c->current_job_lock);
216
217     c->current_job = avctx->thread_count;
218     c->job_count = job_count;
219     c->job_size = job_size;
220     c->args = arg;
221     c->func = func;
222     if (ret) {
223         c->rets = ret;
224         c->rets_count = job_count;
225     } else {
226         c->rets = &dummy_ret;
227         c->rets_count = 1;
228     }
229     c->current_execute++;
230     pthread_cond_broadcast(&c->current_job_cond);
231
232     thread_park_workers(c, avctx->thread_count);
233
234     return 0;
235 }
236
237 static int thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
238 {
239     ThreadContext *c= avctx->thread_opaque;
240     c->func2 = func2;
241     return thread_execute(avctx, NULL, arg, ret, job_count, 0);
242 }
243
244 static int thread_init_internal(AVCodecContext *avctx)
245 {
246     int i;
247     ThreadContext *c;
248     int thread_count = avctx->thread_count;
249
250     if (!thread_count) {
251         int nb_cpus = av_cpu_count();
252         av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
253         // use number of cores + 1 as thread count if there is more than one
254         if (nb_cpus > 1)
255             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
256         else
257             thread_count = avctx->thread_count = 1;
258     }
259
260     if (thread_count <= 1) {
261         avctx->active_thread_type = 0;
262         return 0;
263     }
264
265     c = av_mallocz(sizeof(ThreadContext));
266     if (!c)
267         return -1;
268
269     c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
270     if (!c->workers) {
271         av_free(c);
272         return -1;
273     }
274
275     avctx->thread_opaque = c;
276     c->current_job = 0;
277     c->job_count = 0;
278     c->job_size = 0;
279     c->done = 0;
280     pthread_cond_init(&c->current_job_cond, NULL);
281     pthread_cond_init(&c->last_job_cond, NULL);
282     pthread_mutex_init(&c->current_job_lock, NULL);
283     pthread_mutex_lock(&c->current_job_lock);
284     for (i=0; i<thread_count; i++) {
285         if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
286            avctx->thread_count = i;
287            pthread_mutex_unlock(&c->current_job_lock);
288            ff_thread_free(avctx);
289            return -1;
290         }
291     }
292
293     thread_park_workers(c, thread_count);
294
295     avctx->execute = thread_execute;
296     avctx->execute2 = thread_execute2;
297     return 0;
298 }
299
300 /**
301  * Codec worker thread.
302  *
303  * Automatically calls ff_thread_finish_setup() if the codec does
304  * not provide an update_thread_context method, or if the codec returns
305  * before calling it.
306  */
307 static attribute_align_arg void *frame_worker_thread(void *arg)
308 {
309     PerThreadContext *p = arg;
310     FrameThreadContext *fctx = p->parent;
311     AVCodecContext *avctx = p->avctx;
312     const AVCodec *codec = avctx->codec;
313
314     while (1) {
315         if (p->state == STATE_INPUT_READY && !fctx->die) {
316             pthread_mutex_lock(&p->mutex);
317             while (p->state == STATE_INPUT_READY && !fctx->die)
318                 pthread_cond_wait(&p->input_cond, &p->mutex);
319             pthread_mutex_unlock(&p->mutex);
320         }
321
322         if (fctx->die) break;
323
324         if (!codec->update_thread_context && avctx->thread_safe_callbacks)
325             ff_thread_finish_setup(avctx);
326
327         pthread_mutex_lock(&p->mutex);
328         avcodec_get_frame_defaults(&p->frame);
329         p->got_frame = 0;
330         p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
331
332         /* many decoders assign whole AVFrames, thus overwriting extended_data;
333          * make sure it's set correctly */
334         p->frame.extended_data = p->frame.data;
335
336         if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
337
338         p->state = STATE_INPUT_READY;
339
340         pthread_mutex_lock(&p->progress_mutex);
341         pthread_cond_signal(&p->output_cond);
342         pthread_mutex_unlock(&p->progress_mutex);
343
344         pthread_mutex_unlock(&p->mutex);
345     }
346
347     return NULL;
348 }
349
350 /**
351  * Update the next thread's AVCodecContext with values from the reference thread's context.
352  *
353  * @param dst The destination context.
354  * @param src The source context.
355  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
356  */
357 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
358 {
359     int err = 0;
360
361     if (dst != src) {
362         dst->time_base = src->time_base;
363         dst->width     = src->width;
364         dst->height    = src->height;
365         dst->pix_fmt   = src->pix_fmt;
366
367         dst->coded_width  = src->coded_width;
368         dst->coded_height = src->coded_height;
369
370         dst->has_b_frames = src->has_b_frames;
371         dst->idct_algo    = src->idct_algo;
372
373         dst->bits_per_coded_sample = src->bits_per_coded_sample;
374         dst->sample_aspect_ratio   = src->sample_aspect_ratio;
375         dst->dtg_active_format     = src->dtg_active_format;
376
377         dst->profile = src->profile;
378         dst->level   = src->level;
379
380         dst->bits_per_raw_sample = src->bits_per_raw_sample;
381         dst->ticks_per_frame     = src->ticks_per_frame;
382         dst->color_primaries     = src->color_primaries;
383
384         dst->color_trc   = src->color_trc;
385         dst->colorspace  = src->colorspace;
386         dst->color_range = src->color_range;
387         dst->chroma_sample_location = src->chroma_sample_location;
388
389         dst->hwaccel = src->hwaccel;
390         dst->hwaccel_context = src->hwaccel_context;
391     }
392
393     if (for_user) {
394         dst->coded_frame = src->coded_frame;
395     } else {
396         if (dst->codec->update_thread_context)
397             err = dst->codec->update_thread_context(dst, src);
398     }
399
400     return err;
401 }
402
403 /**
404  * Update the next thread's AVCodecContext with values set by the user.
405  *
406  * @param dst The destination context.
407  * @param src The source context.
408  * @return 0 on success, negative error code on failure
409  */
410 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
411 {
412 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
413     dst->flags          = src->flags;
414
415     dst->draw_horiz_band= src->draw_horiz_band;
416     dst->get_buffer2    = src->get_buffer2;
417 #if FF_API_GET_BUFFER
418 FF_DISABLE_DEPRECATION_WARNINGS
419     dst->get_buffer     = src->get_buffer;
420     dst->release_buffer = src->release_buffer;
421 FF_ENABLE_DEPRECATION_WARNINGS
422 #endif
423
424     dst->opaque   = src->opaque;
425     dst->debug    = src->debug;
426
427     dst->slice_flags = src->slice_flags;
428     dst->flags2      = src->flags2;
429
430     copy_fields(skip_loop_filter, subtitle_header);
431
432     dst->frame_number     = src->frame_number;
433     dst->reordered_opaque = src->reordered_opaque;
434
435     if (src->slice_count && src->slice_offset) {
436         if (dst->slice_count < src->slice_count) {
437             int *tmp = av_realloc(dst->slice_offset, src->slice_count *
438                                   sizeof(*dst->slice_offset));
439             if (!tmp) {
440                 av_free(dst->slice_offset);
441                 return AVERROR(ENOMEM);
442             }
443             dst->slice_offset = tmp;
444         }
445         memcpy(dst->slice_offset, src->slice_offset,
446                src->slice_count * sizeof(*dst->slice_offset));
447     }
448     dst->slice_count = src->slice_count;
449     return 0;
450 #undef copy_fields
451 }
452
453 /// Releases the buffers that this decoding thread was the last user of.
454 static void release_delayed_buffers(PerThreadContext *p)
455 {
456     FrameThreadContext *fctx = p->parent;
457
458     while (p->num_released_buffers > 0) {
459         AVFrame *f;
460
461         pthread_mutex_lock(&fctx->buffer_mutex);
462
463         // fix extended data in case the caller screwed it up
464         av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
465         f = &p->released_buffers[--p->num_released_buffers];
466         f->extended_data = f->data;
467         av_frame_unref(f);
468
469         pthread_mutex_unlock(&fctx->buffer_mutex);
470     }
471 }
472
473 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
474 {
475     FrameThreadContext *fctx = p->parent;
476     PerThreadContext *prev_thread = fctx->prev_thread;
477     const AVCodec *codec = p->avctx->codec;
478
479     if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
480
481     pthread_mutex_lock(&p->mutex);
482
483     release_delayed_buffers(p);
484
485     if (prev_thread) {
486         int err;
487         if (prev_thread->state == STATE_SETTING_UP) {
488             pthread_mutex_lock(&prev_thread->progress_mutex);
489             while (prev_thread->state == STATE_SETTING_UP)
490                 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
491             pthread_mutex_unlock(&prev_thread->progress_mutex);
492         }
493
494         err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
495         if (err) {
496             pthread_mutex_unlock(&p->mutex);
497             return err;
498         }
499     }
500
501     av_buffer_unref(&p->avpkt.buf);
502     p->avpkt = *avpkt;
503     if (avpkt->buf)
504         p->avpkt.buf = av_buffer_ref(avpkt->buf);
505     else {
506         av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
507         p->avpkt.data = p->buf;
508         memcpy(p->buf, avpkt->data, avpkt->size);
509         memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
510     }
511
512     p->state = STATE_SETTING_UP;
513     pthread_cond_signal(&p->input_cond);
514     pthread_mutex_unlock(&p->mutex);
515
516     /*
517      * If the client doesn't have a thread-safe get_buffer(),
518      * then decoding threads call back to the main thread,
519      * and it calls back to the client here.
520      */
521
522 FF_DISABLE_DEPRECATION_WARNINGS
523     if (!p->avctx->thread_safe_callbacks && (
524 #if FF_API_GET_BUFFER
525          p->avctx->get_buffer ||
526 #endif
527          p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
528 FF_ENABLE_DEPRECATION_WARNINGS
529         while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
530             pthread_mutex_lock(&p->progress_mutex);
531             while (p->state == STATE_SETTING_UP)
532                 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
533
534             if (p->state == STATE_GET_BUFFER) {
535                 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
536                 p->state  = STATE_SETTING_UP;
537                 pthread_cond_signal(&p->progress_cond);
538             }
539             pthread_mutex_unlock(&p->progress_mutex);
540         }
541     }
542
543     fctx->prev_thread = p;
544     fctx->next_decoding++;
545
546     return 0;
547 }
548
549 int ff_thread_decode_frame(AVCodecContext *avctx,
550                            AVFrame *picture, int *got_picture_ptr,
551                            AVPacket *avpkt)
552 {
553     FrameThreadContext *fctx = avctx->thread_opaque;
554     int finished = fctx->next_finished;
555     PerThreadContext *p;
556     int err;
557
558     /*
559      * Submit a packet to the next decoding thread.
560      */
561
562     p = &fctx->threads[fctx->next_decoding];
563     err = update_context_from_user(p->avctx, avctx);
564     if (err) return err;
565     err = submit_packet(p, avpkt);
566     if (err) return err;
567
568     /*
569      * If we're still receiving the initial packets, don't return a frame.
570      */
571
572     if (fctx->delaying) {
573         if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
574
575         *got_picture_ptr=0;
576         if (avpkt->size)
577             return avpkt->size;
578     }
579
580     /*
581      * Return the next available frame from the oldest thread.
582      * If we're at the end of the stream, then we have to skip threads that
583      * didn't output a frame, because we don't want to accidentally signal
584      * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
585      */
586
587     do {
588         p = &fctx->threads[finished++];
589
590         if (p->state != STATE_INPUT_READY) {
591             pthread_mutex_lock(&p->progress_mutex);
592             while (p->state != STATE_INPUT_READY)
593                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
594             pthread_mutex_unlock(&p->progress_mutex);
595         }
596
597         av_frame_move_ref(picture, &p->frame);
598         *got_picture_ptr = p->got_frame;
599         picture->pkt_dts = p->avpkt.dts;
600
601         /*
602          * A later call with avkpt->size == 0 may loop over all threads,
603          * including this one, searching for a frame to return before being
604          * stopped by the "finished != fctx->next_finished" condition.
605          * Make sure we don't mistakenly return the same frame again.
606          */
607         p->got_frame = 0;
608
609         if (finished >= avctx->thread_count) finished = 0;
610     } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
611
612     update_context_from_thread(avctx, p->avctx, 1);
613
614     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
615
616     fctx->next_finished = finished;
617
618     /* return the size of the consumed packet if no error occurred */
619     return (p->result >= 0) ? avpkt->size : p->result;
620 }
621
622 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
623 {
624     PerThreadContext *p;
625     int *progress = f->progress ? (int*)f->progress->data : NULL;
626
627     if (!progress || progress[field] >= n) return;
628
629     p = f->owner->thread_opaque;
630
631     if (f->owner->debug&FF_DEBUG_THREADS)
632         av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
633
634     pthread_mutex_lock(&p->progress_mutex);
635     progress[field] = n;
636     pthread_cond_broadcast(&p->progress_cond);
637     pthread_mutex_unlock(&p->progress_mutex);
638 }
639
640 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
641 {
642     PerThreadContext *p;
643     int *progress = f->progress ? (int*)f->progress->data : NULL;
644
645     if (!progress || progress[field] >= n) return;
646
647     p = f->owner->thread_opaque;
648
649     if (f->owner->debug&FF_DEBUG_THREADS)
650         av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
651
652     pthread_mutex_lock(&p->progress_mutex);
653     while (progress[field] < n)
654         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
655     pthread_mutex_unlock(&p->progress_mutex);
656 }
657
658 void ff_thread_finish_setup(AVCodecContext *avctx) {
659     PerThreadContext *p = avctx->thread_opaque;
660
661     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
662
663     pthread_mutex_lock(&p->progress_mutex);
664     p->state = STATE_SETUP_FINISHED;
665     pthread_cond_broadcast(&p->progress_cond);
666     pthread_mutex_unlock(&p->progress_mutex);
667 }
668
669 /// Waits for all threads to finish.
670 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
671 {
672     int i;
673
674     for (i = 0; i < thread_count; i++) {
675         PerThreadContext *p = &fctx->threads[i];
676
677         if (p->state != STATE_INPUT_READY) {
678             pthread_mutex_lock(&p->progress_mutex);
679             while (p->state != STATE_INPUT_READY)
680                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
681             pthread_mutex_unlock(&p->progress_mutex);
682         }
683     }
684 }
685
686 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
687 {
688     FrameThreadContext *fctx = avctx->thread_opaque;
689     const AVCodec *codec = avctx->codec;
690     int i;
691
692     park_frame_worker_threads(fctx, thread_count);
693
694     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
695         update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
696
697     fctx->die = 1;
698
699     for (i = 0; i < thread_count; i++) {
700         PerThreadContext *p = &fctx->threads[i];
701
702         pthread_mutex_lock(&p->mutex);
703         pthread_cond_signal(&p->input_cond);
704         pthread_mutex_unlock(&p->mutex);
705
706         if (p->thread_init)
707             pthread_join(p->thread, NULL);
708
709         if (codec->close)
710             codec->close(p->avctx);
711
712         avctx->codec = NULL;
713
714         release_delayed_buffers(p);
715         av_frame_unref(&p->frame);
716     }
717
718     for (i = 0; i < thread_count; i++) {
719         PerThreadContext *p = &fctx->threads[i];
720
721         pthread_mutex_destroy(&p->mutex);
722         pthread_mutex_destroy(&p->progress_mutex);
723         pthread_cond_destroy(&p->input_cond);
724         pthread_cond_destroy(&p->progress_cond);
725         pthread_cond_destroy(&p->output_cond);
726         av_buffer_unref(&p->avpkt.buf);
727         av_freep(&p->buf);
728         av_freep(&p->released_buffers);
729
730         if (i) {
731             av_freep(&p->avctx->priv_data);
732             av_freep(&p->avctx->internal);
733             av_freep(&p->avctx->slice_offset);
734         }
735
736         av_freep(&p->avctx);
737     }
738
739     av_freep(&fctx->threads);
740     pthread_mutex_destroy(&fctx->buffer_mutex);
741     av_freep(&avctx->thread_opaque);
742 }
743
744 static int frame_thread_init(AVCodecContext *avctx)
745 {
746     int thread_count = avctx->thread_count;
747     const AVCodec *codec = avctx->codec;
748     AVCodecContext *src = avctx;
749     FrameThreadContext *fctx;
750     int i, err = 0;
751
752     if (!thread_count) {
753         int nb_cpus = av_cpu_count();
754         av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
755         // use number of cores + 1 as thread count if there is more than one
756         if (nb_cpus > 1)
757             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
758         else
759             thread_count = avctx->thread_count = 1;
760     }
761
762     if (thread_count <= 1) {
763         avctx->active_thread_type = 0;
764         return 0;
765     }
766
767     avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
768
769     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
770     pthread_mutex_init(&fctx->buffer_mutex, NULL);
771     fctx->delaying = 1;
772
773     for (i = 0; i < thread_count; i++) {
774         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
775         PerThreadContext *p  = &fctx->threads[i];
776
777         pthread_mutex_init(&p->mutex, NULL);
778         pthread_mutex_init(&p->progress_mutex, NULL);
779         pthread_cond_init(&p->input_cond, NULL);
780         pthread_cond_init(&p->progress_cond, NULL);
781         pthread_cond_init(&p->output_cond, NULL);
782
783         p->parent = fctx;
784         p->avctx  = copy;
785
786         if (!copy) {
787             err = AVERROR(ENOMEM);
788             goto error;
789         }
790
791         *copy = *src;
792         copy->thread_opaque = p;
793         copy->pkt = &p->avpkt;
794
795         if (!i) {
796             src = copy;
797
798             if (codec->init)
799                 err = codec->init(copy);
800
801             update_context_from_thread(avctx, copy, 1);
802         } else {
803             copy->priv_data = av_malloc(codec->priv_data_size);
804             if (!copy->priv_data) {
805                 err = AVERROR(ENOMEM);
806                 goto error;
807             }
808             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
809             copy->internal = av_malloc(sizeof(AVCodecInternal));
810             if (!copy->internal) {
811                 err = AVERROR(ENOMEM);
812                 goto error;
813             }
814             *copy->internal = *src->internal;
815             copy->internal->is_copy = 1;
816
817             if (codec->init_thread_copy)
818                 err = codec->init_thread_copy(copy);
819         }
820
821         if (err) goto error;
822
823         if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
824             p->thread_init = 1;
825     }
826
827     return 0;
828
829 error:
830     frame_thread_free(avctx, i+1);
831
832     return err;
833 }
834
835 void ff_thread_flush(AVCodecContext *avctx)
836 {
837     int i;
838     FrameThreadContext *fctx = avctx->thread_opaque;
839
840     if (!avctx->thread_opaque) return;
841
842     park_frame_worker_threads(fctx, avctx->thread_count);
843     if (fctx->prev_thread) {
844         if (fctx->prev_thread != &fctx->threads[0])
845             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
846         if (avctx->codec->flush)
847             avctx->codec->flush(fctx->threads[0].avctx);
848     }
849
850     fctx->next_decoding = fctx->next_finished = 0;
851     fctx->delaying = 1;
852     fctx->prev_thread = NULL;
853     for (i = 0; i < avctx->thread_count; i++) {
854         PerThreadContext *p = &fctx->threads[i];
855         // Make sure decode flush calls with size=0 won't return old frames
856         p->got_frame = 0;
857         av_frame_unref(&p->frame);
858
859         release_delayed_buffers(p);
860     }
861 }
862
863 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
864 {
865     PerThreadContext *p = avctx->thread_opaque;
866     int err;
867
868     f->owner = avctx;
869
870     if (!(avctx->active_thread_type & FF_THREAD_FRAME))
871         return ff_get_buffer(avctx, f->f, flags);
872
873     if (p->state != STATE_SETTING_UP &&
874         (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
875         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
876         return -1;
877     }
878
879     if (avctx->internal->allocate_progress) {
880         int *progress;
881         f->progress = av_buffer_alloc(2 * sizeof(int));
882         if (!f->progress) {
883             return AVERROR(ENOMEM);
884         }
885         progress = (int*)f->progress->data;
886
887         progress[0] = progress[1] = -1;
888     }
889
890     pthread_mutex_lock(&p->parent->buffer_mutex);
891 FF_DISABLE_DEPRECATION_WARNINGS
892     if (avctx->thread_safe_callbacks || (
893 #if FF_API_GET_BUFFER
894         !avctx->get_buffer &&
895 #endif
896         avctx->get_buffer2 == avcodec_default_get_buffer2)) {
897 FF_ENABLE_DEPRECATION_WARNINGS
898         err = ff_get_buffer(avctx, f->f, flags);
899     } else {
900         p->requested_frame = f->f;
901         p->requested_flags = flags;
902         p->state = STATE_GET_BUFFER;
903         pthread_mutex_lock(&p->progress_mutex);
904         pthread_cond_signal(&p->progress_cond);
905
906         while (p->state != STATE_SETTING_UP)
907             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
908
909         err = p->result;
910
911         pthread_mutex_unlock(&p->progress_mutex);
912
913     }
914     if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
915         ff_thread_finish_setup(avctx);
916
917     if (err)
918         av_buffer_unref(&f->progress);
919
920     pthread_mutex_unlock(&p->parent->buffer_mutex);
921
922     return err;
923 }
924
925 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
926 {
927     PerThreadContext *p = avctx->thread_opaque;
928     FrameThreadContext *fctx;
929     AVFrame *dst, *tmp;
930 FF_DISABLE_DEPRECATION_WARNINGS
931     int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
932                           avctx->thread_safe_callbacks                   ||
933                           (
934 #if FF_API_GET_BUFFER
935                            !avctx->get_buffer &&
936 #endif
937                            avctx->get_buffer2 == avcodec_default_get_buffer2);
938 FF_ENABLE_DEPRECATION_WARNINGS
939
940     if (!f->f->data[0])
941         return;
942
943     if (avctx->debug & FF_DEBUG_BUFFERS)
944         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
945
946     av_buffer_unref(&f->progress);
947     f->owner    = NULL;
948
949     if (can_direct_free) {
950         av_frame_unref(f->f);
951         return;
952     }
953
954     fctx = p->parent;
955     pthread_mutex_lock(&fctx->buffer_mutex);
956
957     if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
958         goto fail;
959     tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
960                           (p->num_released_buffers + 1) *
961                           sizeof(*p->released_buffers));
962     if (!tmp)
963         goto fail;
964     p->released_buffers = tmp;
965
966     dst = &p->released_buffers[p->num_released_buffers];
967     av_frame_move_ref(dst, f->f);
968
969     p->num_released_buffers++;
970
971 fail:
972     pthread_mutex_unlock(&fctx->buffer_mutex);
973 }
974
975 /**
976  * Set the threading algorithms used.
977  *
978  * Threading requires more than one thread.
979  * Frame threading requires entire frames to be passed to the codec,
980  * and introduces extra decoding delay, so is incompatible with low_delay.
981  *
982  * @param avctx The context.
983  */
984 static void validate_thread_parameters(AVCodecContext *avctx)
985 {
986     int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
987                                 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
988                                 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
989                                 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
990     if (avctx->thread_count == 1) {
991         avctx->active_thread_type = 0;
992     } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
993         avctx->active_thread_type = FF_THREAD_FRAME;
994     } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
995                avctx->thread_type & FF_THREAD_SLICE) {
996         avctx->active_thread_type = FF_THREAD_SLICE;
997     } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
998         avctx->thread_count       = 1;
999         avctx->active_thread_type = 0;
1000     }
1001
1002     if (avctx->thread_count > MAX_AUTO_THREADS)
1003         av_log(avctx, AV_LOG_WARNING,
1004                "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1005                avctx->thread_count, MAX_AUTO_THREADS);
1006 }
1007
1008 int ff_thread_init(AVCodecContext *avctx)
1009 {
1010 #if HAVE_W32THREADS
1011     w32thread_init();
1012 #endif
1013
1014     validate_thread_parameters(avctx);
1015
1016     if (avctx->active_thread_type&FF_THREAD_SLICE)
1017         return thread_init_internal(avctx);
1018     else if (avctx->active_thread_type&FF_THREAD_FRAME)
1019         return frame_thread_init(avctx);
1020
1021     return 0;
1022 }
1023
1024 void ff_thread_free(AVCodecContext *avctx)
1025 {
1026     if (avctx->active_thread_type&FF_THREAD_FRAME)
1027         frame_thread_free(avctx, avctx->thread_count);
1028     else
1029         thread_free(avctx);
1030 }