1 /*
2 * This file is part of FFmpeg.
3 *
4 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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
27 #include <stdatomic.h>
28 #include <stdint.h>
29
30 #include "avcodec.h"
31 #include "hwaccel.h"
32 #include "internal.h"
33 #include "pthread_internal.h"
34 #include "thread.h"
35 #include "version.h"
36
37 #include "libavutil/avassert.h"
38 #include "libavutil/buffer.h"
39 #include "libavutil/common.h"
40 #include "libavutil/cpu.h"
41 #include "libavutil/frame.h"
42 #include "libavutil/internal.h"
43 #include "libavutil/log.h"
44 #include "libavutil/mem.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/thread.h"
47
48 enum {
49 ///< Set when the thread is awaiting a packet.
50 STATE_INPUT_READY,
51 ///< Set before the codec has called ff_thread_finish_setup().
52 STATE_SETTING_UP,
53 /**
54 * Set when the codec calls get_buffer().
55 * State is returned to STATE_SETTING_UP afterwards.
56 */
57 STATE_GET_BUFFER,
58 /**
59 * Set when the codec calls get_format().
60 * State is returned to STATE_SETTING_UP afterwards.
61 */
62 STATE_GET_FORMAT,
63 ///< Set after the codec has called ff_thread_finish_setup().
64 STATE_SETUP_FINISHED,
65 };
66
67 /**
68 * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
69 */
70 typedef struct PerThreadContext {
71 struct FrameThreadContext *parent;
72
73 pthread_t thread;
74 int thread_init;
75 pthread_cond_t input_cond; ///< Used to wait for a new packet from the main thread.
76 pthread_cond_t progress_cond; ///< Used by child threads to wait for progress to change.
77 pthread_cond_t output_cond; ///< Used by the main thread to wait for frames to finish.
78
79 pthread_mutex_t mutex; ///< Mutex used to protect the contents of the PerThreadContext.
80 pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
81
82 AVCodecContext *avctx; ///< Context used to decode packets passed to this thread.
83
84 AVPacket avpkt; ///< Input packet (for decoding) or output (for encoding).
85
86 AVFrame *frame; ///< Output frame (for decoding) or input (for encoding).
87 int got_frame; ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
88 int result; ///< The result of the last codec decode/encode() call.
89
90 atomic_int state;
91
92 /**
93 * Array of frames passed to ff_thread_release_buffer().
94 * Frames are released after all threads referencing them are finished.
95 */
96 AVFrame *released_buffers;
97 int num_released_buffers;
98 int released_buffers_allocated;
99
100 AVFrame *requested_frame; ///< AVFrame the codec passed to get_buffer()
101 int requested_flags; ///< flags passed to get_buffer() for requested_frame
102
103 const enum AVPixelFormat *available_formats; ///< Format array for get_format()
104 enum AVPixelFormat result_format; ///< get_format() result
105
106 int die; ///< Set when the thread should exit.
107
108 int hwaccel_serializing;
109 int async_serializing;
110
111 atomic_int debug_threads; ///< Set if the FF_DEBUG_THREADS option is set.
112 } PerThreadContext;
113
114 /**
115 * Context stored in the client AVCodecInternal thread_ctx.
116 */
117 typedef struct FrameThreadContext {
118 PerThreadContext *threads; ///< The contexts for each thread.
119 PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
120
121 pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
122 /**
123 * This lock is used for ensuring threads run in serial when hwaccel
124 * is used.
125 */
126 pthread_mutex_t hwaccel_mutex;
127 pthread_mutex_t async_mutex;
128 pthread_cond_t async_cond;
129 int async_lock;
130
131 int next_decoding; ///< The next context to submit a packet to.
132 int next_finished; ///< The next context to return output from.
133
134 int delaying; /**<
135 * Set for the first N packets, where N is the number of threads.
136 * While it is set, ff_thread_en/decode_frame won't return any results.
137 */
138 } FrameThreadContext;
139
140 #define THREAD_SAFE_CALLBACKS(avctx) \
141 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
142
async_lock(FrameThreadContext * fctx)143 static void async_lock(FrameThreadContext *fctx)
144 {
145 pthread_mutex_lock(&fctx->async_mutex);
146 while (fctx->async_lock)
147 pthread_cond_wait(&fctx->async_cond, &fctx->async_mutex);
148 fctx->async_lock = 1;
149 pthread_mutex_unlock(&fctx->async_mutex);
150 }
151
async_unlock(FrameThreadContext * fctx)152 static void async_unlock(FrameThreadContext *fctx)
153 {
154 pthread_mutex_lock(&fctx->async_mutex);
155 av_assert0(fctx->async_lock);
156 fctx->async_lock = 0;
157 pthread_cond_broadcast(&fctx->async_cond);
158 pthread_mutex_unlock(&fctx->async_mutex);
159 }
160
161 /**
162 * Codec worker thread.
163 *
164 * Automatically calls ff_thread_finish_setup() if the codec does
165 * not provide an update_thread_context method, or if the codec returns
166 * before calling it.
167 */
frame_worker_thread(void * arg)168 static attribute_align_arg void *frame_worker_thread(void *arg)
169 {
170 PerThreadContext *p = arg;
171 AVCodecContext *avctx = p->avctx;
172 const AVCodec *codec = avctx->codec;
173
174 pthread_mutex_lock(&p->mutex);
175 while (1) {
176 while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
177 pthread_cond_wait(&p->input_cond, &p->mutex);
178
179 if (p->die) break;
180
181 if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
182 ff_thread_finish_setup(avctx);
183
184 /* If a decoder supports hwaccel, then it must call ff_get_format().
185 * Since that call must happen before ff_thread_finish_setup(), the
186 * decoder is required to implement update_thread_context() and call
187 * ff_thread_finish_setup() manually. Therefore the above
188 * ff_thread_finish_setup() call did not happen and hwaccel_serializing
189 * cannot be true here. */
190 av_assert0(!p->hwaccel_serializing);
191
192 /* if the previous thread uses hwaccel then we take the lock to ensure
193 * the threads don't run concurrently */
194 if (avctx->hwaccel) {
195 pthread_mutex_lock(&p->parent->hwaccel_mutex);
196 p->hwaccel_serializing = 1;
197 }
198
199 av_frame_unref(p->frame);
200 p->got_frame = 0;
201 p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
202
203 if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
204 if (avctx->internal->allocate_progress)
205 av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
206 "free the frame on failure. This is a bug, please report it.\n");
207 av_frame_unref(p->frame);
208 }
209
210 if (atomic_load(&p->state) == STATE_SETTING_UP)
211 ff_thread_finish_setup(avctx);
212
213 if (p->hwaccel_serializing) {
214 p->hwaccel_serializing = 0;
215 pthread_mutex_unlock(&p->parent->hwaccel_mutex);
216 }
217
218 if (p->async_serializing) {
219 p->async_serializing = 0;
220
221 async_unlock(p->parent);
222 }
223
224 pthread_mutex_lock(&p->progress_mutex);
225
226 atomic_store(&p->state, STATE_INPUT_READY);
227
228 pthread_cond_broadcast(&p->progress_cond);
229 pthread_cond_signal(&p->output_cond);
230 pthread_mutex_unlock(&p->progress_mutex);
231 }
232 pthread_mutex_unlock(&p->mutex);
233
234 return NULL;
235 }
236
237 /**
238 * Update the next thread's AVCodecContext with values from the reference thread's context.
239 *
240 * @param dst The destination context.
241 * @param src The source context.
242 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
243 * @return 0 on success, negative error code on failure
244 */
update_context_from_thread(AVCodecContext * dst,AVCodecContext * src,int for_user)245 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
246 {
247 int err = 0;
248
249 if (dst != src && (for_user || !(av_codec_get_codec_descriptor(src)->props & AV_CODEC_PROP_INTRA_ONLY))) {
250 dst->time_base = src->time_base;
251 dst->framerate = src->framerate;
252 dst->width = src->width;
253 dst->height = src->height;
254 dst->pix_fmt = src->pix_fmt;
255 dst->sw_pix_fmt = src->sw_pix_fmt;
256
257 dst->coded_width = src->coded_width;
258 dst->coded_height = src->coded_height;
259
260 dst->has_b_frames = src->has_b_frames;
261 dst->idct_algo = src->idct_algo;
262
263 dst->bits_per_coded_sample = src->bits_per_coded_sample;
264 dst->sample_aspect_ratio = src->sample_aspect_ratio;
265 #if FF_API_AFD
266 FF_DISABLE_DEPRECATION_WARNINGS
267 dst->dtg_active_format = src->dtg_active_format;
268 FF_ENABLE_DEPRECATION_WARNINGS
269 #endif /* FF_API_AFD */
270
271 dst->profile = src->profile;
272 dst->level = src->level;
273
274 dst->bits_per_raw_sample = src->bits_per_raw_sample;
275 dst->ticks_per_frame = src->ticks_per_frame;
276 dst->color_primaries = src->color_primaries;
277
278 dst->color_trc = src->color_trc;
279 dst->colorspace = src->colorspace;
280 dst->color_range = src->color_range;
281 dst->chroma_sample_location = src->chroma_sample_location;
282
283 dst->hwaccel = src->hwaccel;
284 dst->hwaccel_context = src->hwaccel_context;
285
286 dst->channels = src->channels;
287 dst->sample_rate = src->sample_rate;
288 dst->sample_fmt = src->sample_fmt;
289 dst->channel_layout = src->channel_layout;
290 dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
291
292 if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
293 (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
294 av_buffer_unref(&dst->hw_frames_ctx);
295
296 if (src->hw_frames_ctx) {
297 dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
298 if (!dst->hw_frames_ctx)
299 return AVERROR(ENOMEM);
300 }
301 }
302
303 dst->hwaccel_flags = src->hwaccel_flags;
304 }
305
306 if (for_user) {
307 dst->delay = src->thread_count - 1;
308 #if FF_API_CODED_FRAME
309 FF_DISABLE_DEPRECATION_WARNINGS
310 dst->coded_frame = src->coded_frame;
311 FF_ENABLE_DEPRECATION_WARNINGS
312 #endif
313 } else {
314 if (dst->codec->update_thread_context)
315 err = dst->codec->update_thread_context(dst, src);
316 }
317
318 return err;
319 }
320
321 /**
322 * Update the next thread's AVCodecContext with values set by the user.
323 *
324 * @param dst The destination context.
325 * @param src The source context.
326 * @return 0 on success, negative error code on failure
327 */
update_context_from_user(AVCodecContext * dst,AVCodecContext * src)328 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
329 {
330 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
331 dst->flags = src->flags;
332
333 dst->draw_horiz_band= src->draw_horiz_band;
334 dst->get_buffer2 = src->get_buffer2;
335
336 dst->opaque = src->opaque;
337 dst->debug = src->debug;
338 dst->debug_mv = src->debug_mv;
339
340 dst->slice_flags = src->slice_flags;
341 dst->flags2 = src->flags2;
342
343 copy_fields(skip_loop_filter, subtitle_header);
344
345 dst->frame_number = src->frame_number;
346 dst->reordered_opaque = src->reordered_opaque;
347 dst->thread_safe_callbacks = src->thread_safe_callbacks;
348
349 if (src->slice_count && src->slice_offset) {
350 if (dst->slice_count < src->slice_count) {
351 int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
352 sizeof(*dst->slice_offset));
353 if (err < 0)
354 return err;
355 }
356 memcpy(dst->slice_offset, src->slice_offset,
357 src->slice_count * sizeof(*dst->slice_offset));
358 }
359 dst->slice_count = src->slice_count;
360 return 0;
361 #undef copy_fields
362 }
363
364 /// Releases the buffers that this decoding thread was the last user of.
release_delayed_buffers(PerThreadContext * p)365 static void release_delayed_buffers(PerThreadContext *p)
366 {
367 FrameThreadContext *fctx = p->parent;
368
369 while (p->num_released_buffers > 0) {
370 AVFrame *f;
371
372 pthread_mutex_lock(&fctx->buffer_mutex);
373
374 // fix extended data in case the caller screwed it up
375 av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
376 p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
377 f = &p->released_buffers[--p->num_released_buffers];
378 f->extended_data = f->data;
379 av_frame_unref(f);
380
381 pthread_mutex_unlock(&fctx->buffer_mutex);
382 }
383 }
384
submit_packet(PerThreadContext * p,AVCodecContext * user_avctx,AVPacket * avpkt)385 static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx,
386 AVPacket *avpkt)
387 {
388 FrameThreadContext *fctx = p->parent;
389 PerThreadContext *prev_thread = fctx->prev_thread;
390 const AVCodec *codec = p->avctx->codec;
391 int ret;
392
393 if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
394 return 0;
395
396 pthread_mutex_lock(&p->mutex);
397
398 ret = update_context_from_user(p->avctx, user_avctx);
399 if (ret) {
400 pthread_mutex_unlock(&p->mutex);
401 return ret;
402 }
403 atomic_store_explicit(&p->debug_threads,
404 (p->avctx->debug & FF_DEBUG_THREADS) != 0,
405 memory_order_relaxed);
406
407 release_delayed_buffers(p);
408
409 if (prev_thread) {
410 int err;
411 if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
412 pthread_mutex_lock(&prev_thread->progress_mutex);
413 while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
414 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
415 pthread_mutex_unlock(&prev_thread->progress_mutex);
416 }
417
418 err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
419 if (err) {
420 pthread_mutex_unlock(&p->mutex);
421 return err;
422 }
423 }
424
425 av_packet_unref(&p->avpkt);
426 ret = av_packet_ref(&p->avpkt, avpkt);
427 if (ret < 0) {
428 pthread_mutex_unlock(&p->mutex);
429 av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
430 return ret;
431 }
432
433 atomic_store(&p->state, STATE_SETTING_UP);
434 pthread_cond_signal(&p->input_cond);
435 pthread_mutex_unlock(&p->mutex);
436
437 /*
438 * If the client doesn't have a thread-safe get_buffer(),
439 * then decoding threads call back to the main thread,
440 * and it calls back to the client here.
441 */
442
443 if (!p->avctx->thread_safe_callbacks && (
444 p->avctx->get_format != avcodec_default_get_format ||
445 p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
446 while (atomic_load(&p->state) != STATE_SETUP_FINISHED && atomic_load(&p->state) != STATE_INPUT_READY) {
447 int call_done = 1;
448 pthread_mutex_lock(&p->progress_mutex);
449 while (atomic_load(&p->state) == STATE_SETTING_UP)
450 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
451
452 switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
453 case STATE_GET_BUFFER:
454 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
455 break;
456 case STATE_GET_FORMAT:
457 p->result_format = ff_get_format(p->avctx, p->available_formats);
458 break;
459 default:
460 call_done = 0;
461 break;
462 }
463 if (call_done) {
464 atomic_store(&p->state, STATE_SETTING_UP);
465 pthread_cond_signal(&p->progress_cond);
466 }
467 pthread_mutex_unlock(&p->progress_mutex);
468 }
469 }
470
471 fctx->prev_thread = p;
472 fctx->next_decoding++;
473
474 return 0;
475 }
476
ff_thread_decode_frame(AVCodecContext * avctx,AVFrame * picture,int * got_picture_ptr,AVPacket * avpkt)477 int ff_thread_decode_frame(AVCodecContext *avctx,
478 AVFrame *picture, int *got_picture_ptr,
479 AVPacket *avpkt)
480 {
481 FrameThreadContext *fctx = avctx->internal->thread_ctx;
482 int finished = fctx->next_finished;
483 PerThreadContext *p;
484 int err;
485
486 /* release the async lock, permitting blocked hwaccel threads to
487 * go forward while we are in this function */
488 async_unlock(fctx);
489
490 /*
491 * Submit a packet to the next decoding thread.
492 */
493
494 p = &fctx->threads[fctx->next_decoding];
495 err = submit_packet(p, avctx, avpkt);
496 if (err)
497 goto finish;
498
499 /*
500 * If we're still receiving the initial packets, don't return a frame.
501 */
502
503 if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
504 fctx->delaying = 0;
505
506 if (fctx->delaying) {
507 *got_picture_ptr=0;
508 if (avpkt->size) {
509 err = avpkt->size;
510 goto finish;
511 }
512 }
513
514 /*
515 * Return the next available frame from the oldest thread.
516 * If we're at the end of the stream, then we have to skip threads that
517 * didn't output a frame/error, because we don't want to accidentally signal
518 * EOF (avpkt->size == 0 && *got_picture_ptr == 0 && err >= 0).
519 */
520
521 do {
522 p = &fctx->threads[finished++];
523
524 if (atomic_load(&p->state) != STATE_INPUT_READY) {
525 pthread_mutex_lock(&p->progress_mutex);
526 while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
527 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
528 pthread_mutex_unlock(&p->progress_mutex);
529 }
530
531 av_frame_move_ref(picture, p->frame);
532 *got_picture_ptr = p->got_frame;
533 picture->pkt_dts = p->avpkt.dts;
534 err = p->result;
535
536 /*
537 * A later call with avkpt->size == 0 may loop over all threads,
538 * including this one, searching for a frame/error to return before being
539 * stopped by the "finished != fctx->next_finished" condition.
540 * Make sure we don't mistakenly return the same frame/error again.
541 */
542 p->got_frame = 0;
543 p->result = 0;
544
545 if (finished >= avctx->thread_count) finished = 0;
546 } while (!avpkt->size && !*got_picture_ptr && err >= 0 && finished != fctx->next_finished);
547
548 update_context_from_thread(avctx, p->avctx, 1);
549
550 if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
551
552 fctx->next_finished = finished;
553
554 /* return the size of the consumed packet if no error occurred */
555 if (err >= 0)
556 err = avpkt->size;
557 finish:
558 async_lock(fctx);
559 return err;
560 }
561
ff_thread_report_progress(ThreadFrame * f,int n,int field)562 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
563 {
564 PerThreadContext *p;
565 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
566
567 if (!progress ||
568 atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
569 return;
570
571 p = f->owner[field]->internal->thread_ctx;
572
573 if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
574 av_log(f->owner[field], AV_LOG_DEBUG,
575 "%p finished %d field %d\n", progress, n, field);
576
577 pthread_mutex_lock(&p->progress_mutex);
578
579 atomic_store_explicit(&progress[field], n, memory_order_release);
580
581 pthread_cond_broadcast(&p->progress_cond);
582 pthread_mutex_unlock(&p->progress_mutex);
583 }
584
ff_thread_await_progress(ThreadFrame * f,int n,int field)585 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
586 {
587 PerThreadContext *p;
588 atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
589
590 if (!progress ||
591 atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
592 return;
593
594 p = f->owner[field]->internal->thread_ctx;
595
596 if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
597 av_log(f->owner[field], AV_LOG_DEBUG,
598 "thread awaiting %d field %d from %p\n", n, field, progress);
599
600 pthread_mutex_lock(&p->progress_mutex);
601 while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
602 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
603 pthread_mutex_unlock(&p->progress_mutex);
604 }
605
ff_thread_finish_setup(AVCodecContext * avctx)606 void ff_thread_finish_setup(AVCodecContext *avctx) {
607 PerThreadContext *p = avctx->internal->thread_ctx;
608
609 if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
610
611 if (avctx->hwaccel && !p->hwaccel_serializing) {
612 pthread_mutex_lock(&p->parent->hwaccel_mutex);
613 p->hwaccel_serializing = 1;
614 }
615
616 /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
617 if (avctx->hwaccel &&
618 !(avctx->hwaccel->caps_internal & HWACCEL_CAP_ASYNC_SAFE)) {
619 p->async_serializing = 1;
620
621 async_lock(p->parent);
622 }
623
624 pthread_mutex_lock(&p->progress_mutex);
625 if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
626 av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
627 }
628
629 atomic_store(&p->state, STATE_SETUP_FINISHED);
630
631 pthread_cond_broadcast(&p->progress_cond);
632 pthread_mutex_unlock(&p->progress_mutex);
633 }
634
635 /// Waits for all threads to finish.
park_frame_worker_threads(FrameThreadContext * fctx,int thread_count)636 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
637 {
638 int i;
639
640 async_unlock(fctx);
641
642 for (i = 0; i < thread_count; i++) {
643 PerThreadContext *p = &fctx->threads[i];
644
645 if (atomic_load(&p->state) != STATE_INPUT_READY) {
646 pthread_mutex_lock(&p->progress_mutex);
647 while (atomic_load(&p->state) != STATE_INPUT_READY)
648 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
649 pthread_mutex_unlock(&p->progress_mutex);
650 }
651 p->got_frame = 0;
652 }
653
654 async_lock(fctx);
655 }
656
ff_frame_thread_free(AVCodecContext * avctx,int thread_count)657 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
658 {
659 FrameThreadContext *fctx = avctx->internal->thread_ctx;
660 const AVCodec *codec = avctx->codec;
661 int i;
662
663 park_frame_worker_threads(fctx, thread_count);
664
665 if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
666 if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
667 av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
668 fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
669 fctx->threads->avctx->internal->is_copy = 1;
670 }
671
672 for (i = 0; i < thread_count; i++) {
673 PerThreadContext *p = &fctx->threads[i];
674
675 pthread_mutex_lock(&p->mutex);
676 p->die = 1;
677 pthread_cond_signal(&p->input_cond);
678 pthread_mutex_unlock(&p->mutex);
679
680 if (p->thread_init)
681 pthread_join(p->thread, NULL);
682 p->thread_init=0;
683
684 if (codec->close && p->avctx)
685 codec->close(p->avctx);
686
687 release_delayed_buffers(p);
688 av_frame_free(&p->frame);
689 }
690
691 for (i = 0; i < thread_count; i++) {
692 PerThreadContext *p = &fctx->threads[i];
693
694 pthread_mutex_destroy(&p->mutex);
695 pthread_mutex_destroy(&p->progress_mutex);
696 pthread_cond_destroy(&p->input_cond);
697 pthread_cond_destroy(&p->progress_cond);
698 pthread_cond_destroy(&p->output_cond);
699 av_packet_unref(&p->avpkt);
700 av_freep(&p->released_buffers);
701
702 if (i && p->avctx) {
703 av_freep(&p->avctx->priv_data);
704 av_freep(&p->avctx->slice_offset);
705 }
706
707 if (p->avctx) {
708 av_freep(&p->avctx->internal);
709 av_buffer_unref(&p->avctx->hw_frames_ctx);
710 }
711
712 av_freep(&p->avctx);
713 }
714
715 av_freep(&fctx->threads);
716 pthread_mutex_destroy(&fctx->buffer_mutex);
717 pthread_mutex_destroy(&fctx->hwaccel_mutex);
718 pthread_mutex_destroy(&fctx->async_mutex);
719 pthread_cond_destroy(&fctx->async_cond);
720
721 av_freep(&avctx->internal->thread_ctx);
722
723 if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
724 av_opt_free(avctx->priv_data);
725 avctx->codec = NULL;
726 }
727
ff_frame_thread_init(AVCodecContext * avctx)728 int ff_frame_thread_init(AVCodecContext *avctx)
729 {
730 int thread_count = avctx->thread_count;
731 const AVCodec *codec = avctx->codec;
732 AVCodecContext *src = avctx;
733 FrameThreadContext *fctx;
734 int i, err = 0;
735
736 #if HAVE_W32THREADS
737 w32thread_init();
738 #endif
739
740 if (!thread_count) {
741 int nb_cpus = av_cpu_count();
742 #if FF_API_DEBUG_MV
743 if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
744 nb_cpus = 1;
745 #endif
746 // use number of cores + 1 as thread count if there is more than one
747 if (nb_cpus > 1)
748 thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
749 else
750 thread_count = avctx->thread_count = 1;
751 }
752
753 if (thread_count <= 1) {
754 avctx->active_thread_type = 0;
755 return 0;
756 }
757
758 avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
759 if (!fctx)
760 return AVERROR(ENOMEM);
761
762 fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
763 if (!fctx->threads) {
764 av_freep(&avctx->internal->thread_ctx);
765 return AVERROR(ENOMEM);
766 }
767
768 pthread_mutex_init(&fctx->buffer_mutex, NULL);
769 pthread_mutex_init(&fctx->hwaccel_mutex, NULL);
770 pthread_mutex_init(&fctx->async_mutex, NULL);
771 pthread_cond_init(&fctx->async_cond, NULL);
772
773 fctx->async_lock = 1;
774 fctx->delaying = 1;
775
776 for (i = 0; i < thread_count; i++) {
777 AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
778 PerThreadContext *p = &fctx->threads[i];
779
780 pthread_mutex_init(&p->mutex, NULL);
781 pthread_mutex_init(&p->progress_mutex, NULL);
782 pthread_cond_init(&p->input_cond, NULL);
783 pthread_cond_init(&p->progress_cond, NULL);
784 pthread_cond_init(&p->output_cond, NULL);
785
786 p->frame = av_frame_alloc();
787 if (!p->frame) {
788 av_freep(©);
789 err = AVERROR(ENOMEM);
790 goto error;
791 }
792
793 p->parent = fctx;
794 p->avctx = copy;
795
796 if (!copy) {
797 err = AVERROR(ENOMEM);
798 goto error;
799 }
800
801 *copy = *src;
802
803 copy->internal = av_malloc(sizeof(AVCodecInternal));
804 if (!copy->internal) {
805 copy->priv_data = NULL;
806 err = AVERROR(ENOMEM);
807 goto error;
808 }
809 *copy->internal = *src->internal;
810 copy->internal->thread_ctx = p;
811 copy->internal->last_pkt_props = &p->avpkt;
812
813 if (!i) {
814 src = copy;
815
816 if (codec->init)
817 err = codec->init(copy);
818
819 update_context_from_thread(avctx, copy, 1);
820 } else {
821 copy->priv_data = av_malloc(codec->priv_data_size);
822 if (!copy->priv_data) {
823 err = AVERROR(ENOMEM);
824 goto error;
825 }
826 memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
827 copy->internal->is_copy = 1;
828
829 if (codec->init_thread_copy)
830 err = codec->init_thread_copy(copy);
831 }
832
833 if (err) goto error;
834
835 atomic_init(&p->debug_threads, (copy->debug & FF_DEBUG_THREADS) != 0);
836
837 err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
838 p->thread_init= !err;
839 if(!p->thread_init)
840 goto error;
841 }
842
843 return 0;
844
845 error:
846 ff_frame_thread_free(avctx, i+1);
847
848 return err;
849 }
850
ff_thread_flush(AVCodecContext * avctx)851 void ff_thread_flush(AVCodecContext *avctx)
852 {
853 int i;
854 FrameThreadContext *fctx = avctx->internal->thread_ctx;
855
856 if (!fctx) return;
857
858 park_frame_worker_threads(fctx, avctx->thread_count);
859 if (fctx->prev_thread) {
860 if (fctx->prev_thread != &fctx->threads[0])
861 update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
862 }
863
864 fctx->next_decoding = fctx->next_finished = 0;
865 fctx->delaying = 1;
866 fctx->prev_thread = NULL;
867 for (i = 0; i < avctx->thread_count; i++) {
868 PerThreadContext *p = &fctx->threads[i];
869 // Make sure decode flush calls with size=0 won't return old frames
870 p->got_frame = 0;
871 av_frame_unref(p->frame);
872 p->result = 0;
873
874 release_delayed_buffers(p);
875
876 if (avctx->codec->flush)
877 avctx->codec->flush(p->avctx);
878 }
879 }
880
ff_thread_can_start_frame(AVCodecContext * avctx)881 int ff_thread_can_start_frame(AVCodecContext *avctx)
882 {
883 PerThreadContext *p = avctx->internal->thread_ctx;
884 if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
885 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
886 return 0;
887 }
888 return 1;
889 }
890
thread_get_buffer_internal(AVCodecContext * avctx,ThreadFrame * f,int flags)891 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
892 {
893 PerThreadContext *p = avctx->internal->thread_ctx;
894 int err;
895
896 f->owner[0] = f->owner[1] = avctx;
897
898 ff_init_buffer_info(avctx, f->f);
899
900 if (!(avctx->active_thread_type & FF_THREAD_FRAME))
901 return ff_get_buffer(avctx, f->f, flags);
902
903 if (atomic_load(&p->state) != STATE_SETTING_UP &&
904 (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
905 av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
906 return -1;
907 }
908
909 if (avctx->internal->allocate_progress) {
910 atomic_int *progress;
911 f->progress = av_buffer_alloc(2 * sizeof(*progress));
912 if (!f->progress) {
913 return AVERROR(ENOMEM);
914 }
915 progress = (atomic_int*)f->progress->data;
916
917 atomic_init(&progress[0], -1);
918 atomic_init(&progress[1], -1);
919 }
920
921 pthread_mutex_lock(&p->parent->buffer_mutex);
922 if (avctx->thread_safe_callbacks ||
923 avctx->get_buffer2 == avcodec_default_get_buffer2) {
924 err = ff_get_buffer(avctx, f->f, flags);
925 } else {
926 pthread_mutex_lock(&p->progress_mutex);
927 p->requested_frame = f->f;
928 p->requested_flags = flags;
929 atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
930 pthread_cond_broadcast(&p->progress_cond);
931
932 while (atomic_load(&p->state) != STATE_SETTING_UP)
933 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
934
935 err = p->result;
936
937 pthread_mutex_unlock(&p->progress_mutex);
938
939 }
940 if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
941 ff_thread_finish_setup(avctx);
942 if (err)
943 av_buffer_unref(&f->progress);
944
945 pthread_mutex_unlock(&p->parent->buffer_mutex);
946
947 return err;
948 }
949
ff_thread_get_format(AVCodecContext * avctx,const enum AVPixelFormat * fmt)950 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
951 {
952 enum AVPixelFormat res;
953 PerThreadContext *p = avctx->internal->thread_ctx;
954 if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
955 avctx->get_format == avcodec_default_get_format)
956 return ff_get_format(avctx, fmt);
957 if (atomic_load(&p->state) != STATE_SETTING_UP) {
958 av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
959 return -1;
960 }
961 pthread_mutex_lock(&p->progress_mutex);
962 p->available_formats = fmt;
963 atomic_store(&p->state, STATE_GET_FORMAT);
964 pthread_cond_broadcast(&p->progress_cond);
965
966 while (atomic_load(&p->state) != STATE_SETTING_UP)
967 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
968
969 res = p->result_format;
970
971 pthread_mutex_unlock(&p->progress_mutex);
972
973 return res;
974 }
975
ff_thread_get_buffer(AVCodecContext * avctx,ThreadFrame * f,int flags)976 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
977 {
978 int ret = thread_get_buffer_internal(avctx, f, flags);
979 if (ret < 0)
980 av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
981 return ret;
982 }
983
ff_thread_release_buffer(AVCodecContext * avctx,ThreadFrame * f)984 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
985 {
986 PerThreadContext *p = avctx->internal->thread_ctx;
987 FrameThreadContext *fctx;
988 AVFrame *dst, *tmp;
989 int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
990 avctx->thread_safe_callbacks ||
991 avctx->get_buffer2 == avcodec_default_get_buffer2;
992
993 if (!f->f || !f->f->buf[0])
994 return;
995
996 if (avctx->debug & FF_DEBUG_BUFFERS)
997 av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
998
999 av_buffer_unref(&f->progress);
1000 f->owner[0] = f->owner[1] = NULL;
1001
1002 if (can_direct_free) {
1003 av_frame_unref(f->f);
1004 return;
1005 }
1006
1007 fctx = p->parent;
1008 pthread_mutex_lock(&fctx->buffer_mutex);
1009
1010 if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
1011 goto fail;
1012 tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
1013 (p->num_released_buffers + 1) *
1014 sizeof(*p->released_buffers));
1015 if (!tmp)
1016 goto fail;
1017 p->released_buffers = tmp;
1018
1019 dst = &p->released_buffers[p->num_released_buffers];
1020 av_frame_move_ref(dst, f->f);
1021
1022 p->num_released_buffers++;
1023
1024 fail:
1025 pthread_mutex_unlock(&fctx->buffer_mutex);
1026 }
1027