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