Coverage Report

Created: 2026-07-25 07:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/pthread_frame.c
Line
Count
Source
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 <stdatomic.h>
26
27
#include "avcodec.h"
28
#include "avcodec_internal.h"
29
#include "codec_internal.h"
30
#include "decode.h"
31
#include "hwaccel_internal.h"
32
#include "hwconfig.h"
33
#include "internal.h"
34
#include "packet_internal.h"
35
#include "pthread_internal.h"
36
#include "libavutil/refstruct.h"
37
#include "thread.h"
38
#include "threadframe.h"
39
40
#include "libavutil/avassert.h"
41
#include "libavutil/buffer.h"
42
#include "libavutil/cpu.h"
43
#include "libavutil/frame.h"
44
#include "libavutil/internal.h"
45
#include "libavutil/log.h"
46
#include "libavutil/mem.h"
47
#include "libavutil/opt.h"
48
#include "libavutil/thread.h"
49
50
enum {
51
    /// Set when the thread is awaiting a packet.
52
    STATE_INPUT_READY,
53
    /// Set before the codec has called ff_thread_finish_setup().
54
    STATE_SETTING_UP,
55
    /// Set after the codec has called ff_thread_finish_setup().
56
    STATE_SETUP_FINISHED,
57
};
58
59
enum {
60
    UNINITIALIZED,  ///< Thread has not been created, AVCodec->close mustn't be called
61
    NEEDS_CLOSE,    ///< FFCodec->close needs to be called
62
    INITIALIZED,    ///< Thread has been properly set up
63
};
64
65
typedef struct DecodedFrames {
66
    AVFrame  **f;
67
    size_t  nb_f;
68
    size_t  nb_f_allocated;
69
} DecodedFrames;
70
71
typedef struct ThreadFrameProgress {
72
    atomic_int progress[2];
73
} ThreadFrameProgress;
74
75
/**
76
 * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
77
 */
78
typedef struct PerThreadContext {
79
    struct FrameThreadContext *parent;
80
81
    pthread_t      thread;
82
    int            thread_init;
83
    unsigned       pthread_init_cnt;///< Number of successfully initialized mutexes/conditions
84
    pthread_cond_t input_cond;      ///< Used to wait for a new packet from the main thread.
85
    pthread_cond_t progress_cond;   ///< Used by child threads to wait for progress to change.
86
    pthread_cond_t output_cond;     ///< Used by the main thread to wait for frames to finish.
87
88
    pthread_mutex_t mutex;          ///< Mutex used to protect the contents of the PerThreadContext.
89
    pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
90
91
    AVCodecContext *avctx;          ///< Context used to decode packets passed to this thread.
92
93
    AVPacket       *avpkt;          ///< Input packet (for decoding) or output (for encoding).
94
95
    /**
96
     * Decoded frames from a single decode iteration.
97
     */
98
    DecodedFrames df;
99
    int     result;                 ///< The result of the last codec decode/encode() call.
100
101
    atomic_int state;
102
103
    int die;                        ///< Set when the thread should exit.
104
105
    int hwaccel_serializing;
106
    int async_serializing;
107
108
    // set to 1 in ff_thread_finish_setup() when a threadsafe hwaccel is used;
109
    // cannot check hwaccel caps directly, because
110
    // worked threads clear hwaccel state for thread-unsafe hwaccels
111
    // after each decode call
112
    int hwaccel_threadsafe;
113
114
    atomic_int debug_threads;       ///< Set if the FF_DEBUG_THREADS option is set.
115
} PerThreadContext;
116
117
/**
118
 * Context stored in the client AVCodecInternal thread_ctx.
119
 */
120
typedef struct FrameThreadContext {
121
    PerThreadContext *threads;     ///< The contexts for each thread.
122
    PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
123
124
    unsigned    pthread_init_cnt;  ///< Number of successfully initialized mutexes/conditions
125
    pthread_mutex_t buffer_mutex;  ///< Mutex used to protect get/release_buffer().
126
    /**
127
     * This lock is used for ensuring threads run in serial when thread-unsafe
128
     * hwaccel is used.
129
     */
130
    pthread_mutex_t hwaccel_mutex;
131
    pthread_mutex_t async_mutex;
132
    pthread_cond_t async_cond;
133
    int async_lock;
134
135
    DecodedFrames df;
136
    int result;
137
138
    /**
139
     * Packet to be submitted to the next thread for decoding.
140
     */
141
    AVPacket *next_pkt;
142
143
    int next_decoding;             ///< The next context to submit a packet to.
144
    int next_finished;             ///< The next context to return output from.
145
146
    /* hwaccel state for thread-unsafe hwaccels is temporarily stored here in
147
     * order to transfer its ownership to the next decoding thread without the
148
     * need for extra synchronization */
149
    const AVHWAccel *stash_hwaccel;
150
    void            *stash_hwaccel_context;
151
    void            *stash_hwaccel_priv;
152
} FrameThreadContext;
153
154
static int hwaccel_serial(const AVCodecContext *avctx)
155
0
{
156
0
    return avctx->hwaccel && !(ffhwaccel(avctx->hwaccel)->caps_internal & HWACCEL_CAP_THREAD_SAFE);
157
0
}
158
159
static void async_lock(FrameThreadContext *fctx)
160
0
{
161
0
    pthread_mutex_lock(&fctx->async_mutex);
162
0
    while (fctx->async_lock)
163
0
        pthread_cond_wait(&fctx->async_cond, &fctx->async_mutex);
164
0
    fctx->async_lock = 1;
165
0
    pthread_mutex_unlock(&fctx->async_mutex);
166
0
}
167
168
static void async_unlock(FrameThreadContext *fctx)
169
0
{
170
0
    pthread_mutex_lock(&fctx->async_mutex);
171
0
    av_assert0(fctx->async_lock);
172
0
    fctx->async_lock = 0;
173
0
    pthread_cond_broadcast(&fctx->async_cond);
174
0
    pthread_mutex_unlock(&fctx->async_mutex);
175
0
}
176
177
static void thread_set_name(PerThreadContext *p)
178
0
{
179
0
    AVCodecContext *avctx = p->avctx;
180
0
    int idx = p - p->parent->threads;
181
0
    char name[16];
182
183
0
    snprintf(name, sizeof(name), "av:%.7s:df%d", avctx->codec->name, idx);
184
185
0
    ff_thread_setname(name);
186
0
}
187
188
// get a free frame to decode into
189
static AVFrame *decoded_frames_get_free(DecodedFrames *df)
190
0
{
191
0
    if (df->nb_f == df->nb_f_allocated) {
192
0
        AVFrame **tmp = av_realloc_array(df->f, df->nb_f + 1,
193
0
                                         sizeof(*df->f));
194
0
        if (!tmp)
195
0
            return NULL;
196
0
        df->f = tmp;
197
198
0
        df->f[df->nb_f] = av_frame_alloc();
199
0
        if (!df->f[df->nb_f])
200
0
            return NULL;
201
202
0
        df->nb_f_allocated++;
203
0
    }
204
205
0
    av_assert0(!df->f[df->nb_f]->buf[0]);
206
207
0
    return df->f[df->nb_f];
208
0
}
209
210
static void decoded_frames_pop(DecodedFrames *df, AVFrame *dst)
211
0
{
212
0
    AVFrame *tmp_frame = df->f[0];
213
0
    av_frame_move_ref(dst, tmp_frame);
214
0
    memmove(df->f, df->f + 1, (df->nb_f - 1) * sizeof(*df->f));
215
0
    df->f[--df->nb_f] = tmp_frame;
216
0
}
217
218
static void decoded_frames_flush(DecodedFrames *df)
219
0
{
220
0
    for (size_t i = 0; i < df->nb_f; i++)
221
0
        av_frame_unref(df->f[i]);
222
0
    df->nb_f = 0;
223
0
}
224
225
static void decoded_frames_free(DecodedFrames *df)
226
0
{
227
0
    for (size_t i = 0; i < df->nb_f_allocated; i++)
228
0
        av_frame_free(&df->f[i]);
229
0
    av_freep(&df->f);
230
0
    df->nb_f           = 0;
231
0
    df->nb_f_allocated = 0;
232
0
}
233
234
/**
235
 * Codec worker thread.
236
 *
237
 * Automatically calls ff_thread_finish_setup() if the codec does
238
 * not provide an update_thread_context method, or if the codec returns
239
 * before calling it.
240
 */
241
static attribute_align_arg void *frame_worker_thread(void *arg)
242
0
{
243
0
    PerThreadContext *p = arg;
244
0
    AVCodecContext *avctx = p->avctx;
245
0
    const FFCodec *codec = ffcodec(avctx->codec);
246
247
0
    thread_set_name(p);
248
249
0
    pthread_mutex_lock(&p->mutex);
250
0
    while (1) {
251
0
        int ret;
252
253
0
        while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
254
0
            pthread_cond_wait(&p->input_cond, &p->mutex);
255
256
0
        if (p->die) break;
257
258
0
        if (!codec->update_thread_context)
259
0
            ff_thread_finish_setup(avctx);
260
261
        /* If a decoder supports hwaccel, then it must call ff_get_format().
262
         * Since that call must happen before ff_thread_finish_setup(), the
263
         * decoder is required to implement update_thread_context() and call
264
         * ff_thread_finish_setup() manually. Therefore the above
265
         * ff_thread_finish_setup() call did not happen and hwaccel_serializing
266
         * cannot be true here. */
267
0
        av_assert0(!p->hwaccel_serializing);
268
269
        /* if the previous thread uses thread-unsafe hwaccel then we take the
270
         * lock to ensure the threads don't run concurrently */
271
0
        if (hwaccel_serial(avctx)) {
272
0
            pthread_mutex_lock(&p->parent->hwaccel_mutex);
273
0
            p->hwaccel_serializing = 1;
274
0
        }
275
276
0
        ret = 0;
277
0
        while (ret >= 0) {
278
0
            AVFrame *frame;
279
280
            /* get the frame which will store the output */
281
0
            frame = decoded_frames_get_free(&p->df);
282
0
            if (!frame) {
283
0
                p->result = AVERROR(ENOMEM);
284
0
                goto alloc_fail;
285
0
            }
286
287
            /* do the actual decoding */
288
0
            ret = ff_decode_receive_frame_internal(avctx, frame);
289
0
            if (ret == 0)
290
0
                p->df.nb_f++;
291
0
            else if (ret < 0 && frame->buf[0])
292
0
                av_frame_unref(frame);
293
294
0
            p->result = (ret == AVERROR(EAGAIN)) ? 0 : ret;
295
0
        }
296
297
0
        if (atomic_load(&p->state) == STATE_SETTING_UP)
298
0
            ff_thread_finish_setup(avctx);
299
300
0
alloc_fail:
301
0
        if (p->hwaccel_serializing) {
302
            /* wipe hwaccel state for thread-unsafe hwaccels to avoid stale
303
             * pointers lying around;
304
             * the state was transferred to FrameThreadContext in
305
             * ff_thread_finish_setup(), so nothing is leaked */
306
0
            avctx->hwaccel                     = NULL;
307
0
            avctx->hwaccel_context             = NULL;
308
0
            avctx->internal->hwaccel_priv_data = NULL;
309
310
0
            p->hwaccel_serializing = 0;
311
0
            pthread_mutex_unlock(&p->parent->hwaccel_mutex);
312
0
        }
313
0
        av_assert0(!avctx->hwaccel ||
314
0
                   (ffhwaccel(avctx->hwaccel)->caps_internal & HWACCEL_CAP_THREAD_SAFE));
315
316
0
        if (p->async_serializing) {
317
0
            p->async_serializing = 0;
318
319
0
            async_unlock(p->parent);
320
0
        }
321
322
0
        pthread_mutex_lock(&p->progress_mutex);
323
324
0
        atomic_store(&p->state, STATE_INPUT_READY);
325
326
0
        pthread_cond_broadcast(&p->progress_cond);
327
0
        pthread_cond_signal(&p->output_cond);
328
0
        pthread_mutex_unlock(&p->progress_mutex);
329
0
    }
330
0
    pthread_mutex_unlock(&p->mutex);
331
332
0
    return NULL;
333
0
}
334
335
/**
336
 * Update the next thread's AVCodecContext with values from the reference thread's context.
337
 *
338
 * @param dst The destination context.
339
 * @param src The source context.
340
 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
341
 * @return 0 on success, negative error code on failure
342
 */
343
static int update_context_from_thread(AVCodecContext *dst, const AVCodecContext *src, int for_user)
344
0
{
345
0
    const FFCodec *const codec = ffcodec(dst->codec);
346
0
    int err = 0;
347
348
0
    if (dst != src && (for_user || codec->update_thread_context)) {
349
0
        dst->time_base = src->time_base;
350
0
        dst->framerate = src->framerate;
351
0
        dst->width     = src->width;
352
0
        dst->height    = src->height;
353
0
        dst->pix_fmt   = src->pix_fmt;
354
0
        dst->sw_pix_fmt = src->sw_pix_fmt;
355
356
0
        dst->coded_width  = src->coded_width;
357
0
        dst->coded_height = src->coded_height;
358
359
0
        dst->has_b_frames = src->has_b_frames;
360
0
        dst->idct_algo    = src->idct_algo;
361
362
0
        dst->bits_per_coded_sample = src->bits_per_coded_sample;
363
0
        dst->sample_aspect_ratio   = src->sample_aspect_ratio;
364
365
0
        dst->profile = src->profile;
366
0
        dst->level   = src->level;
367
368
0
        dst->bits_per_raw_sample = src->bits_per_raw_sample;
369
0
        dst->color_primaries     = src->color_primaries;
370
371
0
        dst->alpha_mode  = src->alpha_mode;
372
373
0
        dst->color_trc   = src->color_trc;
374
0
        dst->colorspace  = src->colorspace;
375
0
        dst->color_range = src->color_range;
376
0
        dst->chroma_sample_location = src->chroma_sample_location;
377
378
0
        dst->sample_rate    = src->sample_rate;
379
0
        dst->sample_fmt     = src->sample_fmt;
380
0
        err = av_channel_layout_copy(&dst->ch_layout, &src->ch_layout);
381
0
        if (err < 0)
382
0
            return err;
383
384
0
        if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
385
0
            (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
386
0
            av_buffer_unref(&dst->hw_frames_ctx);
387
388
0
            if (src->hw_frames_ctx) {
389
0
                dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
390
0
                if (!dst->hw_frames_ctx)
391
0
                    return AVERROR(ENOMEM);
392
0
            }
393
0
        }
394
395
0
        dst->hwaccel_flags = src->hwaccel_flags;
396
397
0
        av_refstruct_replace(&dst->internal->pool, src->internal->pool);
398
0
        ff_decode_internal_sync(dst, src);
399
0
    }
400
401
0
    if (for_user) {
402
0
        if (codec->update_thread_context_for_user)
403
0
            err = codec->update_thread_context_for_user(dst, src);
404
0
    } else {
405
0
        const PerThreadContext *p_src = src->internal->thread_ctx;
406
0
        PerThreadContext       *p_dst = dst->internal->thread_ctx;
407
408
0
        if (codec->update_thread_context) {
409
0
            err = codec->update_thread_context(dst, src);
410
0
            if (err < 0)
411
0
                return err;
412
0
        }
413
414
        // reset dst hwaccel state if needed
415
0
        av_assert0(p_dst->hwaccel_threadsafe ||
416
0
                   (!dst->hwaccel && !dst->internal->hwaccel_priv_data));
417
0
        if (p_dst->hwaccel_threadsafe &&
418
0
            (!p_src->hwaccel_threadsafe || dst->hwaccel != src->hwaccel)) {
419
0
            ff_hwaccel_uninit(dst);
420
0
            p_dst->hwaccel_threadsafe = 0;
421
0
        }
422
423
        // propagate hwaccel state for threadsafe hwaccels
424
0
        if (p_src->hwaccel_threadsafe) {
425
0
            const FFHWAccel *hwaccel = ffhwaccel(src->hwaccel);
426
0
            if (!dst->hwaccel) {
427
0
                if (hwaccel->priv_data_size) {
428
0
                    av_assert0(hwaccel->update_thread_context);
429
430
0
                    dst->internal->hwaccel_priv_data =
431
0
                            av_mallocz(hwaccel->priv_data_size);
432
0
                    if (!dst->internal->hwaccel_priv_data)
433
0
                        return AVERROR(ENOMEM);
434
0
                }
435
0
                dst->hwaccel = src->hwaccel;
436
0
            }
437
0
            av_assert0(dst->hwaccel == src->hwaccel);
438
439
0
            if (hwaccel->update_thread_context) {
440
0
                err = hwaccel->update_thread_context(dst, src);
441
0
                if (err < 0) {
442
0
                    av_log(dst, AV_LOG_ERROR, "Error propagating hwaccel state\n");
443
0
                    ff_hwaccel_uninit(dst);
444
0
                    return err;
445
0
                }
446
0
            }
447
0
            p_dst->hwaccel_threadsafe = 1;
448
0
        }
449
0
    }
450
451
0
    return err;
452
0
}
453
454
/**
455
 * Update the next thread's AVCodecContext with values set by the user.
456
 *
457
 * @param dst The destination context.
458
 * @param src The source context.
459
 * @return 0 on success, negative error code on failure
460
 */
461
static int update_context_from_user(AVCodecContext *dst, const AVCodecContext *src)
462
0
{
463
0
    int err;
464
465
0
    dst->flags          = src->flags;
466
467
0
    dst->draw_horiz_band= src->draw_horiz_band;
468
0
    dst->get_buffer2    = src->get_buffer2;
469
470
0
    dst->opaque   = src->opaque;
471
0
    dst->debug    = src->debug;
472
473
0
    dst->slice_flags = src->slice_flags;
474
0
    dst->flags2      = src->flags2;
475
0
    dst->export_side_data = src->export_side_data;
476
477
0
    dst->skip_loop_filter = src->skip_loop_filter;
478
0
    dst->skip_idct        = src->skip_idct;
479
0
    dst->skip_frame       = src->skip_frame;
480
481
0
    dst->frame_num        = src->frame_num;
482
483
0
    av_packet_unref(dst->internal->last_pkt_props);
484
0
    err = av_packet_copy_props(dst->internal->last_pkt_props, src->internal->last_pkt_props);
485
0
    if (err < 0)
486
0
        return err;
487
488
0
    return 0;
489
0
}
490
491
static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx,
492
                         AVPacket *in_pkt)
493
0
{
494
0
    FrameThreadContext *fctx = p->parent;
495
0
    PerThreadContext *prev_thread = fctx->prev_thread;
496
0
    const AVCodec *codec = p->avctx->codec;
497
0
    int ret;
498
499
0
    pthread_mutex_lock(&p->mutex);
500
501
0
    av_packet_unref(p->avpkt);
502
0
    av_packet_move_ref(p->avpkt, in_pkt);
503
504
0
    if (AVPACKET_IS_EMPTY(p->avpkt))
505
0
        p->avctx->internal->draining = 1;
506
507
0
    ret = update_context_from_user(p->avctx, user_avctx);
508
0
    if (ret) {
509
0
        pthread_mutex_unlock(&p->mutex);
510
0
        return ret;
511
0
    }
512
0
    atomic_store_explicit(&p->debug_threads,
513
0
                          (p->avctx->debug & FF_DEBUG_THREADS) != 0,
514
0
                          memory_order_relaxed);
515
516
0
    if (prev_thread) {
517
0
        if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
518
0
            pthread_mutex_lock(&prev_thread->progress_mutex);
519
0
            while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
520
0
                pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
521
0
            pthread_mutex_unlock(&prev_thread->progress_mutex);
522
0
        }
523
524
        /* codecs without delay might not be prepared to be called repeatedly here during
525
         * flushing (vp3/theora), and also don't need to be, since from this point on, they
526
         * will always return EOF anyway */
527
0
        if (!p->avctx->internal->draining ||
528
0
            (codec->capabilities & AV_CODEC_CAP_DELAY)) {
529
0
            ret = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
530
0
            if (ret) {
531
0
                pthread_mutex_unlock(&p->mutex);
532
0
                return ret;
533
0
            }
534
0
        }
535
0
    }
536
537
    /* transfer the stashed hwaccel state, if any */
538
0
    av_assert0(!p->avctx->hwaccel || p->hwaccel_threadsafe);
539
0
    if (!p->hwaccel_threadsafe) {
540
0
        FFSWAP(const AVHWAccel*, p->avctx->hwaccel,                     fctx->stash_hwaccel);
541
0
        FFSWAP(void*,            p->avctx->hwaccel_context,             fctx->stash_hwaccel_context);
542
0
        FFSWAP(void*,            p->avctx->internal->hwaccel_priv_data, fctx->stash_hwaccel_priv);
543
0
    }
544
545
0
    atomic_store(&p->state, STATE_SETTING_UP);
546
0
    pthread_cond_signal(&p->input_cond);
547
0
    pthread_mutex_unlock(&p->mutex);
548
549
0
    fctx->prev_thread = p;
550
0
    fctx->next_decoding = (fctx->next_decoding + 1) % p->avctx->thread_count;
551
552
0
    return 0;
553
0
}
554
555
int ff_thread_receive_frame(AVCodecContext *avctx, AVFrame *frame, unsigned flags)
556
0
{
557
0
    FrameThreadContext *fctx = avctx->internal->thread_ctx;
558
0
    int ret = 0;
559
560
    /* release the async lock, permitting blocked hwaccel threads to
561
     * go forward while we are in this function */
562
0
    async_unlock(fctx);
563
564
    /* submit packets to threads while there are no buffered results to return */
565
0
    while (!fctx->df.nb_f && !fctx->result) {
566
0
        PerThreadContext *p;
567
568
0
        if (fctx->next_decoding != fctx->next_finished &&
569
0
            (flags & AV_CODEC_RECEIVE_FRAME_FLAG_SYNCHRONOUS))
570
0
            goto wait_for_result;
571
572
        /* get a packet to be submitted to the next thread */
573
0
        av_packet_unref(fctx->next_pkt);
574
0
        ret = ff_decode_get_packet(avctx, fctx->next_pkt);
575
0
        if (ret < 0 && ret != AVERROR_EOF)
576
0
            goto finish;
577
578
0
        ret = submit_packet(&fctx->threads[fctx->next_decoding], avctx,
579
0
                            fctx->next_pkt);
580
0
        if (ret < 0)
581
0
             goto finish;
582
583
        /* do not return any frames until all threads have something to do */
584
0
        if (fctx->next_decoding != fctx->next_finished &&
585
0
            !avctx->internal->draining)
586
0
            continue;
587
588
0
    wait_for_result:
589
0
        p                   = &fctx->threads[fctx->next_finished];
590
0
        fctx->next_finished = (fctx->next_finished + 1) % avctx->thread_count;
591
592
0
        if (atomic_load(&p->state) != STATE_INPUT_READY) {
593
0
            pthread_mutex_lock(&p->progress_mutex);
594
0
            while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
595
0
                pthread_cond_wait(&p->output_cond, &p->progress_mutex);
596
0
            pthread_mutex_unlock(&p->progress_mutex);
597
0
        }
598
599
0
        update_context_from_thread(avctx, p->avctx, 1);
600
0
        fctx->result = p->result;
601
0
        p->result    = 0;
602
0
        if (p->df.nb_f)
603
0
            FFSWAP(DecodedFrames, fctx->df, p->df);
604
0
    }
605
606
    /* a thread may return multiple frames AND an error
607
     * we first return all the frames, then the error */
608
0
    if (fctx->df.nb_f) {
609
0
        decoded_frames_pop(&fctx->df, frame);
610
0
        ret = 0;
611
0
    } else {
612
0
        ret = fctx->result;
613
0
        fctx->result = 0;
614
0
    }
615
616
0
finish:
617
0
    async_lock(fctx);
618
0
    return ret;
619
0
}
620
621
void ff_thread_report_progress(ThreadFrame *f, int n, int field)
622
8.79M
{
623
8.79M
    PerThreadContext *p;
624
8.79M
    atomic_int *progress = f->progress ? f->progress->progress : NULL;
625
626
8.79M
    if (!progress ||
627
8.79M
        atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
628
8.79M
        return;
629
630
0
    p = f->owner[field]->internal->thread_ctx;
631
632
0
    if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
633
0
        av_log(f->owner[field], AV_LOG_DEBUG,
634
0
               "%p finished %d field %d\n", progress, n, field);
635
636
0
    pthread_mutex_lock(&p->progress_mutex);
637
638
0
    atomic_store_explicit(&progress[field], n, memory_order_release);
639
640
0
    pthread_cond_broadcast(&p->progress_cond);
641
0
    pthread_mutex_unlock(&p->progress_mutex);
642
0
}
643
644
void ff_thread_await_progress(const ThreadFrame *f, int n, int field)
645
1.39M
{
646
1.39M
    PerThreadContext *p;
647
1.39M
    atomic_int *progress = f->progress ? f->progress->progress : NULL;
648
649
1.39M
    if (!progress ||
650
1.39M
        atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
651
1.39M
        return;
652
653
0
    p = f->owner[field]->internal->thread_ctx;
654
655
0
    if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
656
0
        av_log(f->owner[field], AV_LOG_DEBUG,
657
0
               "thread awaiting %d field %d from %p\n", n, field, progress);
658
659
0
    pthread_mutex_lock(&p->progress_mutex);
660
0
    while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
661
0
        pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
662
0
    pthread_mutex_unlock(&p->progress_mutex);
663
0
}
664
665
2.79M
void ff_thread_finish_setup(AVCodecContext *avctx) {
666
2.79M
    PerThreadContext *p;
667
668
2.79M
    if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
669
670
0
    p = avctx->internal->thread_ctx;
671
672
0
    p->hwaccel_threadsafe = avctx->hwaccel &&
673
0
                            (ffhwaccel(avctx->hwaccel)->caps_internal & HWACCEL_CAP_THREAD_SAFE);
674
675
0
    if (hwaccel_serial(avctx) && !p->hwaccel_serializing) {
676
0
        pthread_mutex_lock(&p->parent->hwaccel_mutex);
677
0
        p->hwaccel_serializing = 1;
678
0
    }
679
680
    /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
681
0
    if (avctx->hwaccel &&
682
0
        !(ffhwaccel(avctx->hwaccel)->caps_internal & HWACCEL_CAP_ASYNC_SAFE)) {
683
0
        p->async_serializing = 1;
684
685
0
        async_lock(p->parent);
686
0
    }
687
688
    /* thread-unsafe hwaccels share a single private data instance, so we
689
     * save hwaccel state for passing to the next thread;
690
     * this is done here so that this worker thread can wipe its own hwaccel
691
     * state after decoding, without requiring synchronization */
692
0
    av_assert0(!p->parent->stash_hwaccel);
693
0
    if (hwaccel_serial(avctx)) {
694
0
        p->parent->stash_hwaccel         = avctx->hwaccel;
695
0
        p->parent->stash_hwaccel_context = avctx->hwaccel_context;
696
0
        p->parent->stash_hwaccel_priv    = avctx->internal->hwaccel_priv_data;
697
0
    }
698
699
0
    pthread_mutex_lock(&p->progress_mutex);
700
0
    if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
701
0
        av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
702
0
    }
703
704
0
    atomic_store(&p->state, STATE_SETUP_FINISHED);
705
706
0
    pthread_cond_broadcast(&p->progress_cond);
707
0
    pthread_mutex_unlock(&p->progress_mutex);
708
0
}
709
710
/// Waits for all threads to finish.
711
static av_cold void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
712
0
{
713
0
    int i;
714
715
0
    async_unlock(fctx);
716
717
0
    for (i = 0; i < thread_count; i++) {
718
0
        PerThreadContext *p = &fctx->threads[i];
719
720
0
        if (atomic_load(&p->state) != STATE_INPUT_READY) {
721
0
            pthread_mutex_lock(&p->progress_mutex);
722
0
            while (atomic_load(&p->state) != STATE_INPUT_READY)
723
0
                pthread_cond_wait(&p->output_cond, &p->progress_mutex);
724
0
            pthread_mutex_unlock(&p->progress_mutex);
725
0
        }
726
0
    }
727
728
0
    async_lock(fctx);
729
0
}
730
731
#define OFF(member) offsetof(FrameThreadContext, member)
732
DEFINE_OFFSET_ARRAY(FrameThreadContext, thread_ctx, pthread_init_cnt,
733
                    (OFF(buffer_mutex), OFF(hwaccel_mutex), OFF(async_mutex)),
734
                    (OFF(async_cond)));
735
#undef OFF
736
737
#define OFF(member) offsetof(PerThreadContext, member)
738
DEFINE_OFFSET_ARRAY(PerThreadContext, per_thread, pthread_init_cnt,
739
                    (OFF(progress_mutex), OFF(mutex)),
740
                    (OFF(input_cond), OFF(progress_cond), OFF(output_cond)));
741
#undef OFF
742
743
av_cold void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
744
0
{
745
0
    FrameThreadContext *fctx = avctx->internal->thread_ctx;
746
0
    const FFCodec *codec = ffcodec(avctx->codec);
747
0
    int i;
748
749
0
    park_frame_worker_threads(fctx, thread_count);
750
751
0
    for (i = 0; i < thread_count; i++) {
752
0
        PerThreadContext *p = &fctx->threads[i];
753
0
        AVCodecContext *ctx = p->avctx;
754
755
0
        if (ctx->internal) {
756
0
            if (p->thread_init == INITIALIZED) {
757
0
                pthread_mutex_lock(&p->mutex);
758
0
                p->die = 1;
759
0
                pthread_cond_signal(&p->input_cond);
760
0
                pthread_mutex_unlock(&p->mutex);
761
762
0
                pthread_join(p->thread, NULL);
763
0
            }
764
0
            if (codec->close && p->thread_init != UNINITIALIZED)
765
0
                codec->close(ctx);
766
767
            /* When using a threadsafe hwaccel, this is where
768
             * each thread's context is uninit'd and freed. */
769
0
            ff_hwaccel_uninit(ctx);
770
771
0
            if (ctx->priv_data) {
772
0
                if (codec->p.priv_class)
773
0
                    av_opt_free(ctx->priv_data);
774
0
                av_freep(&ctx->priv_data);
775
0
            }
776
777
0
            av_refstruct_unref(&ctx->internal->pool);
778
0
            av_packet_free(&ctx->internal->in_pkt);
779
0
            av_packet_free(&ctx->internal->last_pkt_props);
780
0
            ff_decode_internal_uninit(ctx);
781
0
            av_freep(&ctx->internal);
782
0
            av_buffer_unref(&ctx->hw_frames_ctx);
783
0
            av_frame_side_data_free(&ctx->decoded_side_data,
784
0
                                    &ctx->nb_decoded_side_data);
785
0
        }
786
787
0
        decoded_frames_free(&p->df);
788
789
0
        ff_pthread_free(p, per_thread_offsets);
790
0
        av_packet_free(&p->avpkt);
791
792
0
        av_freep(&p->avctx);
793
0
    }
794
795
0
    decoded_frames_free(&fctx->df);
796
0
    av_packet_free(&fctx->next_pkt);
797
798
0
    av_freep(&fctx->threads);
799
0
    ff_pthread_free(fctx, thread_ctx_offsets);
800
801
    /* if we have stashed hwaccel state, move it to the user-facing context,
802
     * so it will be freed in ff_codec_close() */
803
0
    av_assert0(!avctx->hwaccel);
804
0
    FFSWAP(const AVHWAccel*, avctx->hwaccel,                     fctx->stash_hwaccel);
805
0
    FFSWAP(void*,            avctx->hwaccel_context,             fctx->stash_hwaccel_context);
806
0
    FFSWAP(void*,            avctx->internal->hwaccel_priv_data, fctx->stash_hwaccel_priv);
807
808
0
    av_freep(&avctx->internal->thread_ctx);
809
0
}
810
811
static av_cold int init_thread(PerThreadContext *p, int *threads_to_free,
812
                               FrameThreadContext *fctx, AVCodecContext *avctx,
813
                               const FFCodec *codec, int first)
814
0
{
815
0
    AVCodecContext *copy;
816
0
    int err;
817
818
0
    atomic_init(&p->state, STATE_INPUT_READY);
819
820
0
    copy = av_memdup(avctx, sizeof(*avctx));
821
0
    if (!copy)
822
0
        return AVERROR(ENOMEM);
823
0
    copy->priv_data = NULL;
824
0
    copy->decoded_side_data = NULL;
825
0
    copy->nb_decoded_side_data = 0;
826
827
    /* From now on, this PerThreadContext will be cleaned up by
828
     * ff_frame_thread_free in case of errors. */
829
0
    (*threads_to_free)++;
830
831
0
    p->parent = fctx;
832
0
    p->avctx  = copy;
833
834
0
    copy->internal = ff_decode_internal_alloc();
835
0
    if (!copy->internal)
836
0
        return AVERROR(ENOMEM);
837
0
    ff_decode_internal_sync(copy, avctx);
838
0
    copy->internal->thread_ctx = p;
839
0
    copy->internal->progress_frame_pool = avctx->internal->progress_frame_pool;
840
841
0
    copy->delay = avctx->delay;
842
843
0
    if (codec->priv_data_size) {
844
0
        copy->priv_data = av_mallocz(codec->priv_data_size);
845
0
        if (!copy->priv_data)
846
0
            return AVERROR(ENOMEM);
847
848
0
        if (codec->p.priv_class) {
849
0
            *(const AVClass **)copy->priv_data = codec->p.priv_class;
850
0
            err = av_opt_copy(copy->priv_data, avctx->priv_data);
851
0
            if (err < 0)
852
0
                return err;
853
0
        }
854
0
    }
855
856
0
    err = ff_pthread_init(p, per_thread_offsets);
857
0
    if (err < 0)
858
0
        return err;
859
860
0
    if (!(p->avpkt = av_packet_alloc()))
861
0
        return AVERROR(ENOMEM);
862
863
0
    copy->internal->is_frame_mt = 1;
864
0
    if (!first)
865
0
        copy->internal->is_copy = 1;
866
867
0
    copy->internal->in_pkt = av_packet_alloc();
868
0
    if (!copy->internal->in_pkt)
869
0
        return AVERROR(ENOMEM);
870
871
0
    copy->internal->last_pkt_props = av_packet_alloc();
872
0
    if (!copy->internal->last_pkt_props)
873
0
        return AVERROR(ENOMEM);
874
875
0
    if (codec->init) {
876
0
        err = codec->init(copy);
877
0
        if (err < 0) {
878
0
            if (codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP)
879
0
                p->thread_init = NEEDS_CLOSE;
880
0
            return err;
881
0
        }
882
0
    }
883
0
    p->thread_init = NEEDS_CLOSE;
884
885
0
    if (first) {
886
0
        update_context_from_thread(avctx, copy, 1);
887
888
0
        av_frame_side_data_free(&avctx->decoded_side_data, &avctx->nb_decoded_side_data);
889
0
        for (int i = 0; i < copy->nb_decoded_side_data; i++) {
890
0
            err = av_frame_side_data_clone(&avctx->decoded_side_data,
891
0
                                           &avctx->nb_decoded_side_data,
892
0
                                           copy->decoded_side_data[i], 0);
893
0
            if (err < 0)
894
0
                return err;
895
0
        }
896
0
    }
897
898
0
    atomic_init(&p->debug_threads, (copy->debug & FF_DEBUG_THREADS) != 0);
899
900
0
    err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
901
0
    if (err < 0)
902
0
        return err;
903
0
    p->thread_init = INITIALIZED;
904
905
0
    return 0;
906
0
}
907
908
av_cold int ff_frame_thread_init(AVCodecContext *avctx)
909
0
{
910
0
    int thread_count = avctx->thread_count;
911
0
    const FFCodec *codec = ffcodec(avctx->codec);
912
0
    FrameThreadContext *fctx;
913
0
    int err, i = 0;
914
915
0
    if (!thread_count) {
916
0
        int nb_cpus = av_cpu_count();
917
        // use number of cores + 1 as thread count if there is more than one
918
0
        if (nb_cpus > 1)
919
0
            thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
920
0
        else
921
0
            thread_count = avctx->thread_count = 1;
922
0
    }
923
924
0
    if (thread_count <= 1) {
925
0
        avctx->active_thread_type = 0;
926
0
        return 0;
927
0
    }
928
929
0
    avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
930
0
    if (!fctx)
931
0
        return AVERROR(ENOMEM);
932
933
0
    err = ff_pthread_init(fctx, thread_ctx_offsets);
934
0
    if (err < 0) {
935
0
        ff_pthread_free(fctx, thread_ctx_offsets);
936
0
        av_freep(&avctx->internal->thread_ctx);
937
0
        return err;
938
0
    }
939
940
0
    fctx->next_pkt = av_packet_alloc();
941
0
    if (!fctx->next_pkt)
942
0
        return AVERROR(ENOMEM);
943
944
0
    fctx->async_lock = 1;
945
946
0
    if (codec->p.type == AVMEDIA_TYPE_VIDEO)
947
0
        avctx->delay = avctx->thread_count - 1;
948
949
0
    fctx->threads = av_calloc(thread_count, sizeof(*fctx->threads));
950
0
    if (!fctx->threads) {
951
0
        err = AVERROR(ENOMEM);
952
0
        goto error;
953
0
    }
954
955
0
    for (; i < thread_count; ) {
956
0
        PerThreadContext *p  = &fctx->threads[i];
957
0
        int first = !i;
958
959
0
        err = init_thread(p, &i, fctx, avctx, codec, first);
960
0
        if (err < 0)
961
0
            goto error;
962
0
    }
963
964
0
    return 0;
965
966
0
error:
967
0
    ff_frame_thread_free(avctx, i);
968
0
    return err;
969
0
}
970
971
av_cold void ff_thread_flush(AVCodecContext *avctx)
972
0
{
973
0
    int i;
974
0
    FrameThreadContext *fctx = avctx->internal->thread_ctx;
975
976
0
    if (!fctx) return;
977
978
0
    park_frame_worker_threads(fctx, avctx->thread_count);
979
0
    if (fctx->prev_thread) {
980
0
        if (fctx->prev_thread != &fctx->threads[0])
981
0
            update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
982
0
    }
983
984
0
    fctx->next_decoding = fctx->next_finished = 0;
985
0
    fctx->prev_thread = NULL;
986
987
0
    decoded_frames_flush(&fctx->df);
988
0
    fctx->result = 0;
989
990
0
    for (i = 0; i < avctx->thread_count; i++) {
991
0
        PerThreadContext *p = &fctx->threads[i];
992
993
0
        decoded_frames_flush(&p->df);
994
0
        p->result = 0;
995
996
0
        avcodec_flush_buffers(p->avctx);
997
0
    }
998
0
}
999
1000
int ff_thread_can_start_frame(AVCodecContext *avctx)
1001
6.57M
{
1002
6.57M
    if ((avctx->active_thread_type & FF_THREAD_FRAME) &&
1003
0
        ffcodec(avctx->codec)->update_thread_context) {
1004
0
        PerThreadContext *p = avctx->internal->thread_ctx;
1005
1006
0
        if (atomic_load(&p->state) != STATE_SETTING_UP)
1007
0
            return 0;
1008
0
    }
1009
1010
6.57M
    return 1;
1011
6.57M
}
1012
1013
static int thread_get_buffer_internal(AVCodecContext *avctx, AVFrame *f, int flags)
1014
11.1M
{
1015
11.1M
    PerThreadContext *p;
1016
11.1M
    int err;
1017
1018
11.1M
    if (!(avctx->active_thread_type & FF_THREAD_FRAME))
1019
11.1M
        return ff_get_buffer(avctx, f, flags);
1020
1021
0
    p = avctx->internal->thread_ctx;
1022
0
    if (atomic_load(&p->state) != STATE_SETTING_UP &&
1023
0
        ffcodec(avctx->codec)->update_thread_context) {
1024
0
        av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
1025
0
        return -1;
1026
0
    }
1027
1028
0
    pthread_mutex_lock(&p->parent->buffer_mutex);
1029
0
    err = ff_get_buffer(avctx, f, flags);
1030
1031
0
    pthread_mutex_unlock(&p->parent->buffer_mutex);
1032
1033
0
    return err;
1034
0
}
1035
1036
int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f, int flags)
1037
11.1M
{
1038
11.1M
    int ret = thread_get_buffer_internal(avctx, f, flags);
1039
11.1M
    if (ret < 0)
1040
161k
        av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1041
11.1M
    return ret;
1042
11.1M
}
1043
1044
int ff_thread_get_ext_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1045
4.04M
{
1046
4.04M
    int ret;
1047
1048
4.04M
    f->owner[0] = f->owner[1] = avctx;
1049
4.04M
    if (!(avctx->active_thread_type & FF_THREAD_FRAME))
1050
4.04M
        return ff_get_buffer(avctx, f->f, flags);
1051
1052
0
    f->progress = av_refstruct_allocz(sizeof(*f->progress));
1053
0
    if (!f->progress)
1054
0
        return AVERROR(ENOMEM);
1055
1056
0
    atomic_init(&f->progress->progress[0], -1);
1057
0
    atomic_init(&f->progress->progress[1], -1);
1058
1059
0
    ret = ff_thread_get_buffer(avctx, f->f, flags);
1060
0
    if (ret)
1061
0
        av_refstruct_unref(&f->progress);
1062
0
    return ret;
1063
0
}
1064
1065
void ff_thread_release_ext_buffer(ThreadFrame *f)
1066
9.89M
{
1067
9.89M
    av_refstruct_unref(&f->progress);
1068
9.89M
    f->owner[0] = f->owner[1] = NULL;
1069
9.89M
    if (f->f)
1070
9.89M
        av_frame_unref(f->f);
1071
9.89M
}
1072
1073
av_cold enum ThreadingStatus ff_thread_sync_ref(AVCodecContext *avctx, size_t offset)
1074
143k
{
1075
143k
    PerThreadContext *p;
1076
143k
    const void *ref;
1077
1078
143k
    if (!avctx->internal->is_copy)
1079
143k
        return avctx->active_thread_type & FF_THREAD_FRAME ?
1080
143k
                  FF_THREAD_IS_FIRST_THREAD : FF_THREAD_NO_FRAME_THREADING;
1081
1082
0
    p = avctx->internal->thread_ctx;
1083
1084
0
    av_assert1(memcpy(&ref, (char*)avctx->priv_data + offset, sizeof(ref)) && ref == NULL);
1085
1086
0
    memcpy(&ref, (const char*)p->parent->threads[0].avctx->priv_data + offset, sizeof(ref));
1087
0
    av_assert1(ref);
1088
0
    av_refstruct_replace((char*)avctx->priv_data + offset, ref);
1089
1090
0
    return FF_THREAD_IS_COPY;
1091
143k
}
1092
1093
int ff_thread_get_packet(AVCodecContext *avctx, AVPacket *pkt)
1094
0
{
1095
0
    PerThreadContext *p = avctx->internal->thread_ctx;
1096
1097
0
    if (!AVPACKET_IS_EMPTY(p->avpkt)) {
1098
0
        av_packet_move_ref(pkt, p->avpkt);
1099
0
        return 0;
1100
0
    }
1101
1102
0
    return avctx->internal->draining ? AVERROR_EOF : AVERROR(EAGAIN);
1103
0
}