]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread.c
pthread: unref the decoded but not returned frames on close.
[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 "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
433     if (for_user) {
434         dst->coded_frame = src->coded_frame;
435     } else {
436         if (dst->codec->update_thread_context)
437             err = dst->codec->update_thread_context(dst, src);
438     }
439
440     return err;
441 }
442
443 /**
444  * Update the next thread's AVCodecContext with values set by the user.
445  *
446  * @param dst The destination context.
447  * @param src The source context.
448  * @return 0 on success, negative error code on failure
449  */
450 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
451 {
452 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
453     dst->flags          = src->flags;
454
455     dst->draw_horiz_band= src->draw_horiz_band;
456     dst->get_buffer2    = src->get_buffer2;
457 #if FF_API_GET_BUFFER
458     dst->get_buffer     = src->get_buffer;
459     dst->release_buffer = src->release_buffer;
460 #endif
461
462     dst->opaque   = src->opaque;
463     dst->debug    = src->debug;
464     dst->debug_mv = src->debug_mv;
465
466     dst->slice_flags = src->slice_flags;
467     dst->flags2      = src->flags2;
468
469     copy_fields(skip_loop_filter, subtitle_header);
470
471     dst->frame_number     = src->frame_number;
472     dst->reordered_opaque = src->reordered_opaque;
473
474     if (src->slice_count && src->slice_offset) {
475         if (dst->slice_count < src->slice_count) {
476             int *tmp = av_realloc(dst->slice_offset, src->slice_count *
477                                   sizeof(*dst->slice_offset));
478             if (!tmp) {
479                 av_free(dst->slice_offset);
480                 return AVERROR(ENOMEM);
481             }
482             dst->slice_offset = tmp;
483         }
484         memcpy(dst->slice_offset, src->slice_offset,
485                src->slice_count * sizeof(*dst->slice_offset));
486     }
487     dst->slice_count = src->slice_count;
488     return 0;
489 #undef copy_fields
490 }
491
492 /// Releases the buffers that this decoding thread was the last user of.
493 static void release_delayed_buffers(PerThreadContext *p)
494 {
495     FrameThreadContext *fctx = p->parent;
496
497     while (p->num_released_buffers > 0) {
498         AVFrame *f;
499
500         pthread_mutex_lock(&fctx->buffer_mutex);
501
502         // fix extended data in case the caller screwed it up
503         av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
504         f = &p->released_buffers[--p->num_released_buffers];
505         f->extended_data = f->data;
506         av_frame_unref(f);
507
508         pthread_mutex_unlock(&fctx->buffer_mutex);
509     }
510 }
511
512 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
513 {
514     FrameThreadContext *fctx = p->parent;
515     PerThreadContext *prev_thread = fctx->prev_thread;
516     const AVCodec *codec = p->avctx->codec;
517
518     if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
519
520     pthread_mutex_lock(&p->mutex);
521
522     release_delayed_buffers(p);
523
524     if (prev_thread) {
525         int err;
526         if (prev_thread->state == STATE_SETTING_UP) {
527             pthread_mutex_lock(&prev_thread->progress_mutex);
528             while (prev_thread->state == STATE_SETTING_UP)
529                 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
530             pthread_mutex_unlock(&prev_thread->progress_mutex);
531         }
532
533         err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
534         if (err) {
535             pthread_mutex_unlock(&p->mutex);
536             return err;
537         }
538     }
539
540     av_buffer_unref(&p->avpkt.buf);
541     p->avpkt = *avpkt;
542     if (avpkt->buf)
543         p->avpkt.buf = av_buffer_ref(avpkt->buf);
544     else {
545         av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
546         p->avpkt.data = p->buf;
547         memcpy(p->buf, avpkt->data, avpkt->size);
548         memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
549     }
550
551     p->state = STATE_SETTING_UP;
552     pthread_cond_signal(&p->input_cond);
553     pthread_mutex_unlock(&p->mutex);
554
555     /*
556      * If the client doesn't have a thread-safe get_buffer(),
557      * then decoding threads call back to the main thread,
558      * and it calls back to the client here.
559      */
560
561     if (!p->avctx->thread_safe_callbacks && (
562 #if FF_API_GET_BUFFER
563          p->avctx->get_buffer ||
564 #endif
565          p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
566         while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
567             pthread_mutex_lock(&p->progress_mutex);
568             while (p->state == STATE_SETTING_UP)
569                 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
570
571             if (p->state == STATE_GET_BUFFER) {
572                 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
573                 p->state  = STATE_SETTING_UP;
574                 pthread_cond_signal(&p->progress_cond);
575             }
576             pthread_mutex_unlock(&p->progress_mutex);
577         }
578     }
579
580     fctx->prev_thread = p;
581     fctx->next_decoding++;
582
583     return 0;
584 }
585
586 int ff_thread_decode_frame(AVCodecContext *avctx,
587                            AVFrame *picture, int *got_picture_ptr,
588                            AVPacket *avpkt)
589 {
590     FrameThreadContext *fctx = avctx->thread_opaque;
591     int finished = fctx->next_finished;
592     PerThreadContext *p;
593     int err;
594
595     /*
596      * Submit a packet to the next decoding thread.
597      */
598
599     p = &fctx->threads[fctx->next_decoding];
600     err = update_context_from_user(p->avctx, avctx);
601     if (err) return err;
602     err = submit_packet(p, avpkt);
603     if (err) return err;
604
605     /*
606      * If we're still receiving the initial packets, don't return a frame.
607      */
608
609     if (fctx->delaying) {
610         if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
611
612         *got_picture_ptr=0;
613         if (avpkt->size)
614             return avpkt->size;
615     }
616
617     /*
618      * Return the next available frame from the oldest thread.
619      * If we're at the end of the stream, then we have to skip threads that
620      * didn't output a frame, because we don't want to accidentally signal
621      * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
622      */
623
624     do {
625         p = &fctx->threads[finished++];
626
627         if (p->state != STATE_INPUT_READY) {
628             pthread_mutex_lock(&p->progress_mutex);
629             while (p->state != STATE_INPUT_READY)
630                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
631             pthread_mutex_unlock(&p->progress_mutex);
632         }
633
634         av_frame_move_ref(picture, &p->frame);
635         *got_picture_ptr = p->got_frame;
636         picture->pkt_dts = p->avpkt.dts;
637
638         /*
639          * A later call with avkpt->size == 0 may loop over all threads,
640          * including this one, searching for a frame to return before being
641          * stopped by the "finished != fctx->next_finished" condition.
642          * Make sure we don't mistakenly return the same frame again.
643          */
644         p->got_frame = 0;
645
646         if (finished >= avctx->thread_count) finished = 0;
647     } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
648
649     update_context_from_thread(avctx, p->avctx, 1);
650
651     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
652
653     fctx->next_finished = finished;
654
655     /* return the size of the consumed packet if no error occurred */
656     return (p->result >= 0) ? avpkt->size : p->result;
657 }
658
659 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
660 {
661     PerThreadContext *p;
662     int *progress = f->progress ? (int*)f->progress->data : NULL;
663
664     if (!progress || progress[field] >= n) return;
665
666     p = f->owner->thread_opaque;
667
668     if (f->owner->debug&FF_DEBUG_THREADS)
669         av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
670
671     pthread_mutex_lock(&p->progress_mutex);
672     progress[field] = n;
673     pthread_cond_broadcast(&p->progress_cond);
674     pthread_mutex_unlock(&p->progress_mutex);
675 }
676
677 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
678 {
679     PerThreadContext *p;
680     int *progress = f->progress ? (int*)f->progress->data : NULL;
681
682     if (!progress || progress[field] >= n) return;
683
684     p = f->owner->thread_opaque;
685
686     if (f->owner->debug&FF_DEBUG_THREADS)
687         av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
688
689     pthread_mutex_lock(&p->progress_mutex);
690     while (progress[field] < n)
691         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
692     pthread_mutex_unlock(&p->progress_mutex);
693 }
694
695 void ff_thread_finish_setup(AVCodecContext *avctx) {
696     PerThreadContext *p = avctx->thread_opaque;
697
698     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
699
700     pthread_mutex_lock(&p->progress_mutex);
701     p->state = STATE_SETUP_FINISHED;
702     pthread_cond_broadcast(&p->progress_cond);
703     pthread_mutex_unlock(&p->progress_mutex);
704 }
705
706 /// Waits for all threads to finish.
707 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
708 {
709     int i;
710
711     for (i = 0; i < thread_count; i++) {
712         PerThreadContext *p = &fctx->threads[i];
713
714         if (p->state != STATE_INPUT_READY) {
715             pthread_mutex_lock(&p->progress_mutex);
716             while (p->state != STATE_INPUT_READY)
717                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
718             pthread_mutex_unlock(&p->progress_mutex);
719         }
720     }
721 }
722
723 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
724 {
725     FrameThreadContext *fctx = avctx->thread_opaque;
726     const AVCodec *codec = avctx->codec;
727     int i;
728
729     park_frame_worker_threads(fctx, thread_count);
730
731     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
732         update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
733
734     fctx->die = 1;
735
736     for (i = 0; i < thread_count; i++) {
737         PerThreadContext *p = &fctx->threads[i];
738
739         pthread_mutex_lock(&p->mutex);
740         pthread_cond_signal(&p->input_cond);
741         pthread_mutex_unlock(&p->mutex);
742
743         if (p->thread_init)
744             pthread_join(p->thread, NULL);
745
746         if (codec->close)
747             codec->close(p->avctx);
748
749         avctx->codec = NULL;
750
751         release_delayed_buffers(p);
752         av_frame_unref(&p->frame);
753     }
754
755     for (i = 0; i < thread_count; i++) {
756         PerThreadContext *p = &fctx->threads[i];
757
758         pthread_mutex_destroy(&p->mutex);
759         pthread_mutex_destroy(&p->progress_mutex);
760         pthread_cond_destroy(&p->input_cond);
761         pthread_cond_destroy(&p->progress_cond);
762         pthread_cond_destroy(&p->output_cond);
763         av_buffer_unref(&p->avpkt.buf);
764         av_freep(&p->buf);
765         av_freep(&p->released_buffers);
766
767         if (i) {
768             av_freep(&p->avctx->priv_data);
769             av_freep(&p->avctx->internal);
770             av_freep(&p->avctx->slice_offset);
771         }
772
773         av_freep(&p->avctx);
774     }
775
776     av_freep(&fctx->threads);
777     pthread_mutex_destroy(&fctx->buffer_mutex);
778     av_freep(&avctx->thread_opaque);
779 }
780
781 static int frame_thread_init(AVCodecContext *avctx)
782 {
783     int thread_count = avctx->thread_count;
784     const AVCodec *codec = avctx->codec;
785     AVCodecContext *src = avctx;
786     FrameThreadContext *fctx;
787     int i, err = 0;
788
789     if (!thread_count) {
790         int nb_cpus = get_logical_cpus(avctx);
791         // use number of cores + 1 as thread count if there is more than one
792         if (nb_cpus > 1)
793             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
794         else
795             thread_count = avctx->thread_count = 1;
796     }
797
798     if (thread_count <= 1) {
799         avctx->active_thread_type = 0;
800         return 0;
801     }
802
803     avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
804
805     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
806     pthread_mutex_init(&fctx->buffer_mutex, NULL);
807     fctx->delaying = 1;
808
809     for (i = 0; i < thread_count; i++) {
810         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
811         PerThreadContext *p  = &fctx->threads[i];
812
813         pthread_mutex_init(&p->mutex, NULL);
814         pthread_mutex_init(&p->progress_mutex, NULL);
815         pthread_cond_init(&p->input_cond, NULL);
816         pthread_cond_init(&p->progress_cond, NULL);
817         pthread_cond_init(&p->output_cond, NULL);
818
819         p->parent = fctx;
820         p->avctx  = copy;
821
822         if (!copy) {
823             err = AVERROR(ENOMEM);
824             goto error;
825         }
826
827         *copy = *src;
828         copy->thread_opaque = p;
829         copy->pkt = &p->avpkt;
830
831         if (!i) {
832             src = copy;
833
834             if (codec->init)
835                 err = codec->init(copy);
836
837             update_context_from_thread(avctx, copy, 1);
838         } else {
839             copy->priv_data = av_malloc(codec->priv_data_size);
840             if (!copy->priv_data) {
841                 err = AVERROR(ENOMEM);
842                 goto error;
843             }
844             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
845             copy->internal = av_malloc(sizeof(AVCodecInternal));
846             if (!copy->internal) {
847                 err = AVERROR(ENOMEM);
848                 goto error;
849             }
850             *copy->internal = *src->internal;
851             copy->internal->is_copy = 1;
852
853             if (codec->init_thread_copy)
854                 err = codec->init_thread_copy(copy);
855         }
856
857         if (err) goto error;
858
859         if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
860             p->thread_init = 1;
861     }
862
863     return 0;
864
865 error:
866     frame_thread_free(avctx, i+1);
867
868     return err;
869 }
870
871 void ff_thread_flush(AVCodecContext *avctx)
872 {
873     int i;
874     FrameThreadContext *fctx = avctx->thread_opaque;
875
876     if (!avctx->thread_opaque) return;
877
878     park_frame_worker_threads(fctx, avctx->thread_count);
879     if (fctx->prev_thread) {
880         if (fctx->prev_thread != &fctx->threads[0])
881             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
882         if (avctx->codec->flush)
883             avctx->codec->flush(fctx->threads[0].avctx);
884     }
885
886     fctx->next_decoding = fctx->next_finished = 0;
887     fctx->delaying = 1;
888     fctx->prev_thread = NULL;
889     for (i = 0; i < avctx->thread_count; i++) {
890         PerThreadContext *p = &fctx->threads[i];
891         // Make sure decode flush calls with size=0 won't return old frames
892         p->got_frame = 0;
893
894         release_delayed_buffers(p);
895     }
896 }
897
898 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
899 {
900     PerThreadContext *p = avctx->thread_opaque;
901     int err;
902
903     f->owner = avctx;
904
905     if (!(avctx->active_thread_type & FF_THREAD_FRAME))
906         return ff_get_buffer(avctx, f->f, flags);
907
908     if (p->state != STATE_SETTING_UP &&
909         (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
910         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
911         return -1;
912     }
913
914     if (avctx->internal->allocate_progress) {
915         int *progress;
916         f->progress = av_buffer_alloc(2 * sizeof(int));
917         if (!f->progress) {
918             return AVERROR(ENOMEM);
919         }
920         progress = (int*)f->progress->data;
921
922         progress[0] = progress[1] = -1;
923     }
924
925     pthread_mutex_lock(&p->parent->buffer_mutex);
926     if (avctx->thread_safe_callbacks || (
927 #if FF_API_GET_BUFFER
928         !avctx->get_buffer &&
929 #endif
930         avctx->get_buffer2 == avcodec_default_get_buffer2)) {
931         err = ff_get_buffer(avctx, f->f, flags);
932     } else {
933         p->requested_frame = f->f;
934         p->requested_flags = flags;
935         p->state = STATE_GET_BUFFER;
936         pthread_mutex_lock(&p->progress_mutex);
937         pthread_cond_signal(&p->progress_cond);
938
939         while (p->state != STATE_SETTING_UP)
940             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
941
942         err = p->result;
943
944         pthread_mutex_unlock(&p->progress_mutex);
945
946         if (!avctx->codec->update_thread_context)
947             ff_thread_finish_setup(avctx);
948     }
949
950     if (err)
951         av_buffer_unref(&f->progress);
952
953     pthread_mutex_unlock(&p->parent->buffer_mutex);
954
955     return err;
956 }
957
958 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
959 {
960     PerThreadContext *p = avctx->thread_opaque;
961     FrameThreadContext *fctx;
962     AVFrame *dst, *tmp;
963     int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
964                           avctx->thread_safe_callbacks                   ||
965                           (
966 #if FF_API_GET_BUFFER
967                            !avctx->get_buffer &&
968 #endif
969                            avctx->get_buffer2 == avcodec_default_get_buffer2);
970
971     if (!f->f->data[0])
972         return;
973
974     if (avctx->debug & FF_DEBUG_BUFFERS)
975         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
976
977     av_buffer_unref(&f->progress);
978     f->owner    = NULL;
979
980     if (can_direct_free) {
981         av_frame_unref(f->f);
982         return;
983     }
984
985     fctx = p->parent;
986     pthread_mutex_lock(&fctx->buffer_mutex);
987
988     if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
989         goto fail;
990     tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
991                           (p->num_released_buffers + 1) *
992                           sizeof(*p->released_buffers));
993     if (!tmp)
994         goto fail;
995     p->released_buffers = tmp;
996
997     dst = &p->released_buffers[p->num_released_buffers];
998     av_frame_move_ref(dst, f->f);
999
1000     p->num_released_buffers++;
1001
1002 fail:
1003     pthread_mutex_unlock(&fctx->buffer_mutex);
1004 }
1005
1006 /**
1007  * Set the threading algorithms used.
1008  *
1009  * Threading requires more than one thread.
1010  * Frame threading requires entire frames to be passed to the codec,
1011  * and introduces extra decoding delay, so is incompatible with low_delay.
1012  *
1013  * @param avctx The context.
1014  */
1015 static void validate_thread_parameters(AVCodecContext *avctx)
1016 {
1017     int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
1018                                 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
1019                                 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
1020                                 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
1021     if (avctx->thread_count == 1) {
1022         avctx->active_thread_type = 0;
1023     } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
1024         avctx->active_thread_type = FF_THREAD_FRAME;
1025     } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
1026                avctx->thread_type & FF_THREAD_SLICE) {
1027         avctx->active_thread_type = FF_THREAD_SLICE;
1028     } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
1029         avctx->thread_count       = 1;
1030         avctx->active_thread_type = 0;
1031     }
1032
1033     if (avctx->thread_count > MAX_AUTO_THREADS)
1034         av_log(avctx, AV_LOG_WARNING,
1035                "Application has requested %d threads. Using a thread count greater than %d is not recommended.\n",
1036                avctx->thread_count, MAX_AUTO_THREADS);
1037 }
1038
1039 int ff_thread_init(AVCodecContext *avctx)
1040 {
1041     if (avctx->thread_opaque) {
1042         av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
1043         return -1;
1044     }
1045
1046 #if HAVE_W32THREADS
1047     w32thread_init();
1048 #endif
1049
1050     if (avctx->codec) {
1051         validate_thread_parameters(avctx);
1052
1053         if (avctx->active_thread_type&FF_THREAD_SLICE)
1054             return thread_init(avctx);
1055         else if (avctx->active_thread_type&FF_THREAD_FRAME)
1056             return frame_thread_init(avctx);
1057     }
1058
1059     return 0;
1060 }
1061
1062 void ff_thread_free(AVCodecContext *avctx)
1063 {
1064     if (avctx->active_thread_type&FF_THREAD_FRAME)
1065         frame_thread_free(avctx, avctx->thread_count);
1066     else
1067         thread_free(avctx);
1068 }