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