pthread_frame: Unreference hw_frames_ctx on per-thread codec contexts
[libav.git] / libavcodec / pthread_frame.c
CommitLineData
cc14ee03
AK
1/*
2 * This file is part of Libav.
3 *
4 * Libav is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * Libav is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with Libav; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18
19/**
20 * @file
21 * Frame multithreading support functions
22 * @see doc/multithreading.txt
23 */
24
25#include "config.h"
26
64a31b28 27#include <stdatomic.h>
cc14ee03
AK
28#include <stdint.h>
29
30#if HAVE_PTHREADS
31#include <pthread.h>
32#elif HAVE_W32THREADS
33#include "compat/w32pthreads.h"
34#endif
35
36#include "avcodec.h"
37#include "internal.h"
38#include "pthread_internal.h"
39#include "thread.h"
990e2f35 40#include "version.h"
cc14ee03
AK
41
42#include "libavutil/avassert.h"
43#include "libavutil/buffer.h"
44#include "libavutil/common.h"
45#include "libavutil/cpu.h"
46#include "libavutil/frame.h"
990e2f35 47#include "libavutil/internal.h"
cc14ee03
AK
48#include "libavutil/log.h"
49#include "libavutil/mem.h"
50
64a31b28
AK
51enum {
52 ///< Set when the thread is awaiting a packet.
53 STATE_INPUT_READY,
54 ///< Set before the codec has called ff_thread_finish_setup().
55 STATE_SETTING_UP,
56 /**
57 * Set when the codec calls get_buffer().
58 * State is returned to STATE_SETTING_UP afterwards.
59 */
60 STATE_GET_BUFFER,
61 ///< Set after the codec has called ff_thread_finish_setup().
62 STATE_SETUP_FINISHED,
63};
64
cc14ee03 65/**
38ecc370 66 * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
cc14ee03
AK
67 */
68typedef struct PerThreadContext {
69 struct FrameThreadContext *parent;
70
71 pthread_t thread;
72 int thread_init;
73 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
74 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
75 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
76
77 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
78 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
79
80 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
81
82 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
cc14ee03 83
d351ef47 84 AVFrame *frame; ///< Output frame (for decoding) or input (for encoding).
cc14ee03
AK
85 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
86 int result; ///< The result of the last codec decode/encode() call.
87
64a31b28 88 atomic_int state;
cc14ee03
AK
89
90 /**
91 * Array of frames passed to ff_thread_release_buffer().
92 * Frames are released after all threads referencing them are finished.
93 */
94 AVFrame *released_buffers;
95 int num_released_buffers;
96 int released_buffers_allocated;
97
98 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
99 int requested_flags; ///< flags passed to get_buffer() for requested_frame
db273325
AK
100
101 int die; ///< Set when the thread should exit.
cc14ee03
AK
102} PerThreadContext;
103
104/**
38ecc370 105 * Context stored in the client AVCodecInternal thread_ctx.
cc14ee03
AK
106 */
107typedef struct FrameThreadContext {
108 PerThreadContext *threads; ///< The contexts for each thread.
109 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
110
111 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
112
113 int next_decoding; ///< The next context to submit a packet to.
114 int next_finished; ///< The next context to return output from.
115
116 int delaying; /**<
117 * Set for the first N packets, where N is the number of threads.
118 * While it is set, ff_thread_en/decode_frame won't return any results.
119 */
cc14ee03
AK
120} FrameThreadContext;
121
122/**
123 * Codec worker thread.
124 *
125 * Automatically calls ff_thread_finish_setup() if the codec does
126 * not provide an update_thread_context method, or if the codec returns
127 * before calling it.
128 */
129static attribute_align_arg void *frame_worker_thread(void *arg)
130{
131 PerThreadContext *p = arg;
cc14ee03
AK
132 AVCodecContext *avctx = p->avctx;
133 const AVCodec *codec = avctx->codec;
134
135 while (1) {
64a31b28 136 if (atomic_load(&p->state) == STATE_INPUT_READY) {
cc14ee03 137 pthread_mutex_lock(&p->mutex);
64a31b28 138 while (atomic_load(&p->state) == STATE_INPUT_READY) {
db273325
AK
139 if (p->die) {
140 pthread_mutex_unlock(&p->mutex);
141 goto die;
142 }
cc14ee03 143 pthread_cond_wait(&p->input_cond, &p->mutex);
db273325 144 }
cc14ee03
AK
145 pthread_mutex_unlock(&p->mutex);
146 }
147
cc14ee03
AK
148 if (!codec->update_thread_context && avctx->thread_safe_callbacks)
149 ff_thread_finish_setup(avctx);
150
151 pthread_mutex_lock(&p->mutex);
d351ef47 152 av_frame_unref(p->frame);
cc14ee03 153 p->got_frame = 0;
d351ef47 154 p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
cc14ee03 155
9cbf2d78
AK
156 if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
157 if (avctx->internal->allocate_progress)
158 av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
159 "free the frame on failure. This is a bug, please report it.\n");
160 av_frame_unref(p->frame);
161 }
162
64a31b28
AK
163 if (atomic_load(&p->state) == STATE_SETTING_UP)
164 ff_thread_finish_setup(avctx);
cc14ee03 165
64a31b28 166 atomic_store(&p->state, STATE_INPUT_READY);
cc14ee03
AK
167
168 pthread_mutex_lock(&p->progress_mutex);
169 pthread_cond_signal(&p->output_cond);
170 pthread_mutex_unlock(&p->progress_mutex);
171
172 pthread_mutex_unlock(&p->mutex);
173 }
db273325 174die:
cc14ee03
AK
175
176 return NULL;
177}
178
179/**
180 * Update the next thread's AVCodecContext with values from the reference thread's context.
181 *
182 * @param dst The destination context.
183 * @param src The source context.
184 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
185 */
186static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
187{
188 int err = 0;
189
190 if (dst != src) {
191 dst->time_base = src->time_base;
7ea1b347 192 dst->framerate = src->framerate;
cc14ee03
AK
193 dst->width = src->width;
194 dst->height = src->height;
195 dst->pix_fmt = src->pix_fmt;
196
197 dst->coded_width = src->coded_width;
198 dst->coded_height = src->coded_height;
199
200 dst->has_b_frames = src->has_b_frames;
201 dst->idct_algo = src->idct_algo;
202
203 dst->bits_per_coded_sample = src->bits_per_coded_sample;
204 dst->sample_aspect_ratio = src->sample_aspect_ratio;
990e2f35
DB
205#if FF_API_AFD
206FF_DISABLE_DEPRECATION_WARNINGS
cc14ee03 207 dst->dtg_active_format = src->dtg_active_format;
990e2f35
DB
208FF_ENABLE_DEPRECATION_WARNINGS
209#endif /* FF_API_AFD */
cc14ee03
AK
210
211 dst->profile = src->profile;
212 dst->level = src->level;
213
214 dst->bits_per_raw_sample = src->bits_per_raw_sample;
215 dst->ticks_per_frame = src->ticks_per_frame;
216 dst->color_primaries = src->color_primaries;
217
218 dst->color_trc = src->color_trc;
219 dst->colorspace = src->colorspace;
220 dst->color_range = src->color_range;
221 dst->chroma_sample_location = src->chroma_sample_location;
222
223 dst->hwaccel = src->hwaccel;
224 dst->hwaccel_context = src->hwaccel_context;
dd2d3b76 225 dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
84f22568
AK
226
227 if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
228 (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
229 av_buffer_unref(&dst->hw_frames_ctx);
230
231 if (src->hw_frames_ctx) {
232 dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
233 if (!dst->hw_frames_ctx)
234 return AVERROR(ENOMEM);
235 }
236 }
cc14ee03
AK
237 }
238
239 if (for_user) {
40cf1bba
VG
240#if FF_API_CODED_FRAME
241FF_DISABLE_DEPRECATION_WARNINGS
cc14ee03 242 dst->coded_frame = src->coded_frame;
40cf1bba
VG
243FF_ENABLE_DEPRECATION_WARNINGS
244#endif
cc14ee03
AK
245 } else {
246 if (dst->codec->update_thread_context)
247 err = dst->codec->update_thread_context(dst, src);
248 }
249
250 return err;
251}
252
253/**
254 * Update the next thread's AVCodecContext with values set by the user.
255 *
256 * @param dst The destination context.
257 * @param src The source context.
258 * @return 0 on success, negative error code on failure
259 */
260static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
261{
262#define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
263 dst->flags = src->flags;
264
265 dst->draw_horiz_band= src->draw_horiz_band;
266 dst->get_buffer2 = src->get_buffer2;
cc14ee03
AK
267
268 dst->opaque = src->opaque;
269 dst->debug = src->debug;
270
271 dst->slice_flags = src->slice_flags;
272 dst->flags2 = src->flags2;
273
274 copy_fields(skip_loop_filter, subtitle_header);
275
276 dst->frame_number = src->frame_number;
277 dst->reordered_opaque = src->reordered_opaque;
278
279 if (src->slice_count && src->slice_offset) {
280 if (dst->slice_count < src->slice_count) {
281 int *tmp = av_realloc(dst->slice_offset, src->slice_count *
282 sizeof(*dst->slice_offset));
283 if (!tmp) {
284 av_free(dst->slice_offset);
285 return AVERROR(ENOMEM);
286 }
287 dst->slice_offset = tmp;
288 }
289 memcpy(dst->slice_offset, src->slice_offset,
290 src->slice_count * sizeof(*dst->slice_offset));
291 }
292 dst->slice_count = src->slice_count;
293 return 0;
294#undef copy_fields
295}
296
297/// Releases the buffers that this decoding thread was the last user of.
298static void release_delayed_buffers(PerThreadContext *p)
299{
300 FrameThreadContext *fctx = p->parent;
301
302 while (p->num_released_buffers > 0) {
303 AVFrame *f;
304
305 pthread_mutex_lock(&fctx->buffer_mutex);
306
307 // fix extended data in case the caller screwed it up
308 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO);
309 f = &p->released_buffers[--p->num_released_buffers];
310 f->extended_data = f->data;
311 av_frame_unref(f);
312
313 pthread_mutex_unlock(&fctx->buffer_mutex);
314 }
315}
316
317static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
318{
319 FrameThreadContext *fctx = p->parent;
320 PerThreadContext *prev_thread = fctx->prev_thread;
321 const AVCodec *codec = p->avctx->codec;
322
def97856
VG
323 if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
324 return 0;
cc14ee03
AK
325
326 pthread_mutex_lock(&p->mutex);
327
328 release_delayed_buffers(p);
329
330 if (prev_thread) {
331 int err;
64a31b28 332 if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
cc14ee03 333 pthread_mutex_lock(&prev_thread->progress_mutex);
64a31b28 334 while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
cc14ee03
AK
335 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
336 pthread_mutex_unlock(&prev_thread->progress_mutex);
337 }
338
339 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
340 if (err) {
341 pthread_mutex_unlock(&p->mutex);
342 return err;
343 }
344 }
345
9929b356
AK
346 av_packet_unref(&p->avpkt);
347 av_packet_ref(&p->avpkt, avpkt);
cc14ee03 348
64a31b28 349 atomic_store(&p->state, STATE_SETTING_UP);
cc14ee03
AK
350 pthread_cond_signal(&p->input_cond);
351 pthread_mutex_unlock(&p->mutex);
352
353 /*
354 * If the client doesn't have a thread-safe get_buffer(),
355 * then decoding threads call back to the main thread,
356 * and it calls back to the client here.
357 */
358
9f90b248
VG
359 if (!p->avctx->thread_safe_callbacks &&
360 p->avctx->get_buffer2 != avcodec_default_get_buffer2) {
64a31b28
AK
361 while (atomic_load(&p->state) != STATE_SETUP_FINISHED &&
362 atomic_load(&p->state) != STATE_INPUT_READY) {
cc14ee03 363 pthread_mutex_lock(&p->progress_mutex);
64a31b28 364 while (atomic_load(&p->state) == STATE_SETTING_UP)
cc14ee03
AK
365 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
366
64a31b28 367 if (atomic_load_explicit(&p->state, memory_order_acquire) == STATE_GET_BUFFER) {
cc14ee03 368 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
64a31b28 369 atomic_store(&p->state, STATE_SETTING_UP);
cc14ee03
AK
370 pthread_cond_signal(&p->progress_cond);
371 }
372 pthread_mutex_unlock(&p->progress_mutex);
373 }
374 }
375
376 fctx->prev_thread = p;
377 fctx->next_decoding++;
378
379 return 0;
380}
381
382int ff_thread_decode_frame(AVCodecContext *avctx,
383 AVFrame *picture, int *got_picture_ptr,
384 AVPacket *avpkt)
385{
38ecc370 386 FrameThreadContext *fctx = avctx->internal->thread_ctx;
cc14ee03
AK
387 int finished = fctx->next_finished;
388 PerThreadContext *p;
389 int err;
390
391 /*
392 * Submit a packet to the next decoding thread.
393 */
394
395 p = &fctx->threads[fctx->next_decoding];
396 err = update_context_from_user(p->avctx, avctx);
397 if (err) return err;
398 err = submit_packet(p, avpkt);
399 if (err) return err;
400
401 /*
402 * If we're still receiving the initial packets, don't return a frame.
403 */
404
405 if (fctx->delaying) {
406 if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
407
408 *got_picture_ptr=0;
409 if (avpkt->size)
410 return avpkt->size;
411 }
412
413 /*
414 * Return the next available frame from the oldest thread.
415 * If we're at the end of the stream, then we have to skip threads that
416 * didn't output a frame, because we don't want to accidentally signal
417 * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
418 */
419
420 do {
421 p = &fctx->threads[finished++];
422
64a31b28 423 if (atomic_load(&p->state) != STATE_INPUT_READY) {
cc14ee03 424 pthread_mutex_lock(&p->progress_mutex);
64a31b28 425 while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
cc14ee03
AK
426 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
427 pthread_mutex_unlock(&p->progress_mutex);
428 }
429
d351ef47 430 av_frame_move_ref(picture, p->frame);
cc14ee03
AK
431 *got_picture_ptr = p->got_frame;
432 picture->pkt_dts = p->avpkt.dts;
433
434 /*
435 * A later call with avkpt->size == 0 may loop over all threads,
436 * including this one, searching for a frame to return before being
437 * stopped by the "finished != fctx->next_finished" condition.
438 * Make sure we don't mistakenly return the same frame again.
439 */
440 p->got_frame = 0;
441
442 if (finished >= avctx->thread_count) finished = 0;
443 } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
444
445 update_context_from_thread(avctx, p->avctx, 1);
446
447 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
448
449 fctx->next_finished = finished;
450
451 /* return the size of the consumed packet if no error occurred */
452 return (p->result >= 0) ? avpkt->size : p->result;
453}
454
455void ff_thread_report_progress(ThreadFrame *f, int n, int field)
456{
457 PerThreadContext *p;
59c70227 458 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
cc14ee03 459
59c70227
AK
460 if (!progress ||
461 atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
462 return;
cc14ee03 463
38ecc370 464 p = f->owner->internal->thread_ctx;
cc14ee03
AK
465
466 if (f->owner->debug&FF_DEBUG_THREADS)
467 av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
468
469 pthread_mutex_lock(&p->progress_mutex);
59c70227
AK
470
471 atomic_store(&progress[field], n);
472
cc14ee03
AK
473 pthread_cond_broadcast(&p->progress_cond);
474 pthread_mutex_unlock(&p->progress_mutex);
475}
476
477void ff_thread_await_progress(ThreadFrame *f, int n, int field)
478{
479 PerThreadContext *p;
59c70227 480 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
cc14ee03 481
59c70227
AK
482 if (!progress ||
483 atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
484 return;
cc14ee03 485
38ecc370 486 p = f->owner->internal->thread_ctx;
cc14ee03
AK
487
488 if (f->owner->debug&FF_DEBUG_THREADS)
489 av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
490
491 pthread_mutex_lock(&p->progress_mutex);
59c70227 492 while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
cc14ee03
AK
493 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
494 pthread_mutex_unlock(&p->progress_mutex);
495}
496
497void ff_thread_finish_setup(AVCodecContext *avctx) {
38ecc370 498 PerThreadContext *p = avctx->internal->thread_ctx;
cc14ee03
AK
499
500 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
501
502 pthread_mutex_lock(&p->progress_mutex);
64a31b28
AK
503
504 atomic_store(&p->state, STATE_SETUP_FINISHED);
505
cc14ee03
AK
506 pthread_cond_broadcast(&p->progress_cond);
507 pthread_mutex_unlock(&p->progress_mutex);
508}
509
510/// Waits for all threads to finish.
511static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
512{
513 int i;
514
515 for (i = 0; i < thread_count; i++) {
516 PerThreadContext *p = &fctx->threads[i];
517
64a31b28 518 if (atomic_load(&p->state) != STATE_INPUT_READY) {
cc14ee03 519 pthread_mutex_lock(&p->progress_mutex);
64a31b28 520 while (atomic_load(&p->state) != STATE_INPUT_READY)
cc14ee03
AK
521 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
522 pthread_mutex_unlock(&p->progress_mutex);
523 }
524 }
525}
526
527void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
528{
38ecc370 529 FrameThreadContext *fctx = avctx->internal->thread_ctx;
cc14ee03
AK
530 const AVCodec *codec = avctx->codec;
531 int i;
532
533 park_frame_worker_threads(fctx, thread_count);
534
535 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
536 update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
537
cc14ee03
AK
538 for (i = 0; i < thread_count; i++) {
539 PerThreadContext *p = &fctx->threads[i];
540
541 pthread_mutex_lock(&p->mutex);
db273325 542 p->die = 1;
cc14ee03
AK
543 pthread_cond_signal(&p->input_cond);
544 pthread_mutex_unlock(&p->mutex);
545
546 if (p->thread_init)
547 pthread_join(p->thread, NULL);
548
549 if (codec->close)
550 codec->close(p->avctx);
551
552 avctx->codec = NULL;
553
554 release_delayed_buffers(p);
d351ef47 555 av_frame_free(&p->frame);
cc14ee03
AK
556 }
557
558 for (i = 0; i < thread_count; i++) {
559 PerThreadContext *p = &fctx->threads[i];
560
561 pthread_mutex_destroy(&p->mutex);
562 pthread_mutex_destroy(&p->progress_mutex);
563 pthread_cond_destroy(&p->input_cond);
564 pthread_cond_destroy(&p->progress_cond);
565 pthread_cond_destroy(&p->output_cond);
9929b356 566 av_packet_unref(&p->avpkt);
cc14ee03
AK
567 av_freep(&p->released_buffers);
568
569 if (i) {
570 av_freep(&p->avctx->priv_data);
cc14ee03
AK
571 av_freep(&p->avctx->slice_offset);
572 }
573
fd0fae60
MT
574 av_buffer_unref(&p->avctx->hw_frames_ctx);
575
38ecc370 576 av_freep(&p->avctx->internal);
cc14ee03
AK
577 av_freep(&p->avctx);
578 }
579
580 av_freep(&fctx->threads);
581 pthread_mutex_destroy(&fctx->buffer_mutex);
38ecc370 582 av_freep(&avctx->internal->thread_ctx);
cc14ee03
AK
583}
584
585int ff_frame_thread_init(AVCodecContext *avctx)
586{
587 int thread_count = avctx->thread_count;
588 const AVCodec *codec = avctx->codec;
589 AVCodecContext *src = avctx;
590 FrameThreadContext *fctx;
591 int i, err = 0;
592
593#if HAVE_W32THREADS
594 w32thread_init();
595#endif
596
597 if (!thread_count) {
598 int nb_cpus = av_cpu_count();
599 av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
600 // use number of cores + 1 as thread count if there is more than one
601 if (nb_cpus > 1)
602 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
603 else
604 thread_count = avctx->thread_count = 1;
605 }
606
607 if (thread_count <= 1) {
608 avctx->active_thread_type = 0;
609 return 0;
610 }
611
38ecc370 612 avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
0994e142
VG
613 if (!fctx)
614 return AVERROR(ENOMEM);
cc14ee03
AK
615
616 fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
0994e142
VG
617 if (!fctx->threads) {
618 av_freep(&avctx->internal->thread_ctx);
619 return AVERROR(ENOMEM);
620 }
621
cc14ee03
AK
622 pthread_mutex_init(&fctx->buffer_mutex, NULL);
623 fctx->delaying = 1;
624
625 for (i = 0; i < thread_count; i++) {
626 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
627 PerThreadContext *p = &fctx->threads[i];
628
629 pthread_mutex_init(&p->mutex, NULL);
630 pthread_mutex_init(&p->progress_mutex, NULL);
631 pthread_cond_init(&p->input_cond, NULL);
632 pthread_cond_init(&p->progress_cond, NULL);
633 pthread_cond_init(&p->output_cond, NULL);
634
d351ef47
AK
635 p->frame = av_frame_alloc();
636 if (!p->frame) {
ac4a5e3a 637 av_freep(&copy);
d351ef47
AK
638 err = AVERROR(ENOMEM);
639 goto error;
640 }
641
cc14ee03
AK
642 p->parent = fctx;
643 p->avctx = copy;
644
645 if (!copy) {
646 err = AVERROR(ENOMEM);
647 goto error;
648 }
649
650 *copy = *src;
cc14ee03 651
38ecc370
AK
652 copy->internal = av_malloc(sizeof(AVCodecInternal));
653 if (!copy->internal) {
654 err = AVERROR(ENOMEM);
655 goto error;
656 }
657 *copy->internal = *src->internal;
658 copy->internal->thread_ctx = p;
da6506c6 659 copy->internal->pkt = &p->avpkt;
38ecc370 660
cc14ee03
AK
661 if (!i) {
662 src = copy;
663
664 if (codec->init)
665 err = codec->init(copy);
666
667 update_context_from_thread(avctx, copy, 1);
668 } else {
669 copy->priv_data = av_malloc(codec->priv_data_size);
670 if (!copy->priv_data) {
671 err = AVERROR(ENOMEM);
672 goto error;
673 }
674 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
cc14ee03
AK
675 copy->internal->is_copy = 1;
676
677 if (codec->init_thread_copy)
678 err = codec->init_thread_copy(copy);
679 }
680
681 if (err) goto error;
682
683 if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
684 p->thread_init = 1;
685 }
686
687 return 0;
688
689error:
690 ff_frame_thread_free(avctx, i+1);
691
692 return err;
693}
694
695void ff_thread_flush(AVCodecContext *avctx)
696{
697 int i;
38ecc370 698 FrameThreadContext *fctx = avctx->internal->thread_ctx;
cc14ee03 699
38ecc370 700 if (!fctx) return;
cc14ee03
AK
701
702 park_frame_worker_threads(fctx, avctx->thread_count);
703 if (fctx->prev_thread) {
704 if (fctx->prev_thread != &fctx->threads[0])
705 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
cc14ee03
AK
706 }
707
708 fctx->next_decoding = fctx->next_finished = 0;
709 fctx->delaying = 1;
710 fctx->prev_thread = NULL;
711 for (i = 0; i < avctx->thread_count; i++) {
712 PerThreadContext *p = &fctx->threads[i];
713 // Make sure decode flush calls with size=0 won't return old frames
714 p->got_frame = 0;
d351ef47 715 av_frame_unref(p->frame);
cc14ee03
AK
716
717 release_delayed_buffers(p);
d1f9563d
AK
718
719 if (avctx->codec->flush)
720 avctx->codec->flush(p->avctx);
cc14ee03
AK
721 }
722}
723
724int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
725{
38ecc370 726 PerThreadContext *p = avctx->internal->thread_ctx;
cc14ee03
AK
727 int err;
728
729 f->owner = avctx;
730
731 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
732 return ff_get_buffer(avctx, f->f, flags);
733
64a31b28 734 if (atomic_load(&p->state) != STATE_SETTING_UP &&
cc14ee03
AK
735 (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
736 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
737 return -1;
738 }
739
740 if (avctx->internal->allocate_progress) {
59c70227
AK
741 atomic_int *progress;
742 f->progress = av_buffer_alloc(2 * sizeof(*progress));
cc14ee03
AK
743 if (!f->progress) {
744 return AVERROR(ENOMEM);
745 }
59c70227 746 progress = (atomic_int*)f->progress->data;
cc14ee03 747
59c70227
AK
748 atomic_store(&progress[0], -1);
749 atomic_store(&progress[1], -1);
cc14ee03
AK
750 }
751
752 pthread_mutex_lock(&p->parent->buffer_mutex);
9f90b248
VG
753 if (avctx->thread_safe_callbacks ||
754 avctx->get_buffer2 == avcodec_default_get_buffer2) {
cc14ee03
AK
755 err = ff_get_buffer(avctx, f->f, flags);
756 } else {
757 p->requested_frame = f->f;
758 p->requested_flags = flags;
64a31b28 759 atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
cc14ee03
AK
760 pthread_mutex_lock(&p->progress_mutex);
761 pthread_cond_signal(&p->progress_cond);
762
64a31b28 763 while (atomic_load(&p->state) != STATE_SETTING_UP)
cc14ee03
AK
764 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
765
766 err = p->result;
767
768 pthread_mutex_unlock(&p->progress_mutex);
769
770 }
771 if (!avctx->thread_safe_callbacks && !avctx->codec->update_thread_context)
772 ff_thread_finish_setup(avctx);
773
774 if (err)
775 av_buffer_unref(&f->progress);
776
777 pthread_mutex_unlock(&p->parent->buffer_mutex);
778
779 return err;
780}
781
782void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
783{
38ecc370 784 PerThreadContext *p = avctx->internal->thread_ctx;
cc14ee03
AK
785 FrameThreadContext *fctx;
786 AVFrame *dst, *tmp;
cc14ee03
AK
787 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
788 avctx->thread_safe_callbacks ||
9f90b248 789 avctx->get_buffer2 == avcodec_default_get_buffer2;
cc14ee03 790
f6774f90 791 if (!f->f || !f->f->buf[0])
cc14ee03
AK
792 return;
793
794 if (avctx->debug & FF_DEBUG_BUFFERS)
795 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
796
797 av_buffer_unref(&f->progress);
798 f->owner = NULL;
799
800 if (can_direct_free) {
801 av_frame_unref(f->f);
802 return;
803 }
804
805 fctx = p->parent;
806 pthread_mutex_lock(&fctx->buffer_mutex);
807
808 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
809 goto fail;
810 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
811 (p->num_released_buffers + 1) *
812 sizeof(*p->released_buffers));
813 if (!tmp)
814 goto fail;
815 p->released_buffers = tmp;
816
817 dst = &p->released_buffers[p->num_released_buffers];
818 av_frame_move_ref(dst, f->f);
819
820 p->num_released_buffers++;
821
822fail:
823 pthread_mutex_unlock(&fctx->buffer_mutex);
824}