lavc: add width and height fields to AVFrame
[libav.git] / 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 picture->width = avctx->width;
604 picture->height = avctx->height;
605
606 /*
607 * A later call with avkpt->size == 0 may loop over all threads,
608 * including this one, searching for a frame to return before being
609 * stopped by the "finished != fctx->next_finished" condition.
610 * Make sure we don't mistakenly return the same frame again.
611 */
612 p->got_frame = 0;
613
614 if (finished >= avctx->thread_count) finished = 0;
615 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
616
617 update_context_from_thread(avctx, p->avctx, 1);
618
619 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
620
621 fctx->next_finished = finished;
622
623 /* return the size of the consumed packet if no error occurred */
624 return (p->result >= 0) ? avpkt->size : p->result;
625 }
626
627 void ff_thread_report_progress(AVFrame *f, int n, int field)
628 {
629 PerThreadContext *p;
630 int *progress = f->thread_opaque;
631
632 if (!progress || progress[field] >= n) return;
633
634 p = f->owner->thread_opaque;
635
636 if (f->owner->debug&FF_DEBUG_THREADS)
637 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
638
639 pthread_mutex_lock(&p->progress_mutex);
640 progress[field] = n;
641 pthread_cond_broadcast(&p->progress_cond);
642 pthread_mutex_unlock(&p->progress_mutex);
643 }
644
645 void ff_thread_await_progress(AVFrame *f, int n, int field)
646 {
647 PerThreadContext *p;
648 int *progress = f->thread_opaque;
649
650 if (!progress || progress[field] >= n) return;
651
652 p = f->owner->thread_opaque;
653
654 if (f->owner->debug&FF_DEBUG_THREADS)
655 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
656
657 pthread_mutex_lock(&p->progress_mutex);
658 while (progress[field] < n)
659 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
660 pthread_mutex_unlock(&p->progress_mutex);
661 }
662
663 void ff_thread_finish_setup(AVCodecContext *avctx) {
664 PerThreadContext *p = avctx->thread_opaque;
665
666 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
667
668 pthread_mutex_lock(&p->progress_mutex);
669 p->state = STATE_SETUP_FINISHED;
670 pthread_cond_broadcast(&p->progress_cond);
671 pthread_mutex_unlock(&p->progress_mutex);
672 }
673
674 /// Waits for all threads to finish.
675 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
676 {
677 int i;
678
679 for (i = 0; i < thread_count; i++) {
680 PerThreadContext *p = &fctx->threads[i];
681
682 if (p->state != STATE_INPUT_READY) {
683 pthread_mutex_lock(&p->progress_mutex);
684 while (p->state != STATE_INPUT_READY)
685 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
686 pthread_mutex_unlock(&p->progress_mutex);
687 }
688 }
689 }
690
691 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
692 {
693 FrameThreadContext *fctx = avctx->thread_opaque;
694 AVCodec *codec = avctx->codec;
695 int i;
696
697 park_frame_worker_threads(fctx, thread_count);
698
699 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
700 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
701
702 fctx->die = 1;
703
704 for (i = 0; i < thread_count; i++) {
705 PerThreadContext *p = &fctx->threads[i];
706
707 pthread_mutex_lock(&p->mutex);
708 pthread_cond_signal(&p->input_cond);
709 pthread_mutex_unlock(&p->mutex);
710
711 if (p->thread_init)
712 pthread_join(p->thread, NULL);
713
714 if (codec->close)
715 codec->close(p->avctx);
716
717 avctx->codec = NULL;
718
719 release_delayed_buffers(p);
720 }
721
722 for (i = 0; i < thread_count; i++) {
723 PerThreadContext *p = &fctx->threads[i];
724
725 avcodec_default_free_buffers(p->avctx);
726
727 pthread_mutex_destroy(&p->mutex);
728 pthread_mutex_destroy(&p->progress_mutex);
729 pthread_cond_destroy(&p->input_cond);
730 pthread_cond_destroy(&p->progress_cond);
731 pthread_cond_destroy(&p->output_cond);
732 av_freep(&p->avpkt.data);
733
734 if (i) {
735 av_freep(&p->avctx->priv_data);
736 av_freep(&p->avctx->internal);
737 }
738
739 av_freep(&p->avctx);
740 }
741
742 av_freep(&fctx->threads);
743 pthread_mutex_destroy(&fctx->buffer_mutex);
744 av_freep(&avctx->thread_opaque);
745 }
746
747 static int frame_thread_init(AVCodecContext *avctx)
748 {
749 int thread_count = avctx->thread_count;
750 AVCodec *codec = avctx->codec;
751 AVCodecContext *src = avctx;
752 FrameThreadContext *fctx;
753 int i, err = 0;
754
755 if (!thread_count) {
756 int nb_cpus = get_logical_cpus(avctx);
757 // use number of cores + 1 as thread count if there is motre than one
758 if (nb_cpus > 1)
759 thread_count = avctx->thread_count = nb_cpus + 1;
760 }
761
762 if (thread_count <= 1) {
763 avctx->active_thread_type = 0;
764 return 0;
765 }
766
767 avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
768
769 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
770 pthread_mutex_init(&fctx->buffer_mutex, NULL);
771 fctx->delaying = 1;
772
773 for (i = 0; i < thread_count; i++) {
774 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
775 PerThreadContext *p = &fctx->threads[i];
776
777 pthread_mutex_init(&p->mutex, NULL);
778 pthread_mutex_init(&p->progress_mutex, NULL);
779 pthread_cond_init(&p->input_cond, NULL);
780 pthread_cond_init(&p->progress_cond, NULL);
781 pthread_cond_init(&p->output_cond, NULL);
782
783 p->parent = fctx;
784 p->avctx = copy;
785
786 if (!copy) {
787 err = AVERROR(ENOMEM);
788 goto error;
789 }
790
791 *copy = *src;
792 copy->thread_opaque = p;
793 copy->pkt = &p->avpkt;
794
795 if (!i) {
796 src = copy;
797
798 if (codec->init)
799 err = codec->init(copy);
800
801 update_context_from_thread(avctx, copy, 1);
802 } else {
803 copy->priv_data = av_malloc(codec->priv_data_size);
804 if (!copy->priv_data) {
805 err = AVERROR(ENOMEM);
806 goto error;
807 }
808 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
809 copy->internal = av_malloc(sizeof(AVCodecInternal));
810 if (!copy->internal) {
811 err = AVERROR(ENOMEM);
812 goto error;
813 }
814 *(copy->internal) = *(src->internal);
815 copy->internal->is_copy = 1;
816
817 if (codec->init_thread_copy)
818 err = codec->init_thread_copy(copy);
819 }
820
821 if (err) goto error;
822
823 if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
824 p->thread_init = 1;
825 }
826
827 return 0;
828
829 error:
830 frame_thread_free(avctx, i+1);
831
832 return err;
833 }
834
835 void ff_thread_flush(AVCodecContext *avctx)
836 {
837 FrameThreadContext *fctx = avctx->thread_opaque;
838
839 if (!avctx->thread_opaque) return;
840
841 park_frame_worker_threads(fctx, avctx->thread_count);
842 if (fctx->prev_thread) {
843 if (fctx->prev_thread != &fctx->threads[0])
844 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
845 if (avctx->codec->flush)
846 avctx->codec->flush(fctx->threads[0].avctx);
847 }
848
849 fctx->next_decoding = fctx->next_finished = 0;
850 fctx->delaying = 1;
851 fctx->prev_thread = NULL;
852 }
853
854 static int *allocate_progress(PerThreadContext *p)
855 {
856 int i;
857
858 for (i = 0; i < MAX_BUFFERS; i++)
859 if (!p->progress_used[i]) break;
860
861 if (i == MAX_BUFFERS) {
862 av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
863 return NULL;
864 }
865
866 p->progress_used[i] = 1;
867
868 return p->progress[i];
869 }
870
871 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
872 {
873 PerThreadContext *p = avctx->thread_opaque;
874 int *progress, err;
875
876 f->owner = avctx;
877
878 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
879 f->thread_opaque = NULL;
880 return avctx->get_buffer(avctx, f);
881 }
882
883 if (p->state != STATE_SETTING_UP &&
884 (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
885 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
886 return -1;
887 }
888
889 pthread_mutex_lock(&p->parent->buffer_mutex);
890 f->thread_opaque = progress = allocate_progress(p);
891
892 if (!progress) {
893 pthread_mutex_unlock(&p->parent->buffer_mutex);
894 return -1;
895 }
896
897 progress[0] =
898 progress[1] = -1;
899
900 if (avctx->thread_safe_callbacks ||
901 avctx->get_buffer == avcodec_default_get_buffer) {
902 err = avctx->get_buffer(avctx, f);
903 } else {
904 p->requested_frame = f;
905 p->state = STATE_GET_BUFFER;
906 pthread_mutex_lock(&p->progress_mutex);
907 pthread_cond_signal(&p->progress_cond);
908
909 while (p->state != STATE_SETTING_UP)
910 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
911
912 err = p->result;
913
914 pthread_mutex_unlock(&p->progress_mutex);
915
916 if (!avctx->codec->update_thread_context)
917 ff_thread_finish_setup(avctx);
918 }
919
920 pthread_mutex_unlock(&p->parent->buffer_mutex);
921
922 return err;
923 }
924
925 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
926 {
927 PerThreadContext *p = avctx->thread_opaque;
928 FrameThreadContext *fctx;
929
930 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
931 avctx->release_buffer(avctx, f);
932 return;
933 }
934
935 if (p->num_released_buffers >= MAX_BUFFERS) {
936 av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
937 return;
938 }
939
940 if(avctx->debug & FF_DEBUG_BUFFERS)
941 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
942
943 fctx = p->parent;
944 pthread_mutex_lock(&fctx->buffer_mutex);
945 p->released_buffers[p->num_released_buffers++] = *f;
946 pthread_mutex_unlock(&fctx->buffer_mutex);
947 memset(f->data, 0, sizeof(f->data));
948 }
949
950 /**
951 * Set the threading algorithms used.
952 *
953 * Threading requires more than one thread.
954 * Frame threading requires entire frames to be passed to the codec,
955 * and introduces extra decoding delay, so is incompatible with low_delay.
956 *
957 * @param avctx The context.
958 */
959 static void validate_thread_parameters(AVCodecContext *avctx)
960 {
961 int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
962 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
963 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
964 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
965 if (avctx->thread_count == 1) {
966 avctx->active_thread_type = 0;
967 } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
968 avctx->active_thread_type = FF_THREAD_FRAME;
969 } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
970 avctx->thread_type & FF_THREAD_SLICE) {
971 avctx->active_thread_type = FF_THREAD_SLICE;
972 }
973 }
974
975 int ff_thread_init(AVCodecContext *avctx)
976 {
977 if (avctx->thread_opaque) {
978 av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
979 return -1;
980 }
981
982 #if HAVE_W32THREADS
983 w32thread_init();
984 #endif
985
986 if (avctx->codec) {
987 validate_thread_parameters(avctx);
988
989 if (avctx->active_thread_type&FF_THREAD_SLICE)
990 return thread_init(avctx);
991 else if (avctx->active_thread_type&FF_THREAD_FRAME)
992 return frame_thread_init(avctx);
993 }
994
995 return 0;
996 }
997
998 void ff_thread_free(AVCodecContext *avctx)
999 {
1000 if (avctx->active_thread_type&FF_THREAD_FRAME)
1001 frame_thread_free(avctx, avctx->thread_count);
1002 else
1003 thread_free(avctx);
1004 }