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