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