Coverage Report

Created: 2026-10-28 07:09

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_pred        = src->skip_pred;
480
0
    dst->skip_frame       = src->skip_frame;
481
482
0
    dst->frame_num        = src->frame_num;
483
484
0
    av_packet_unref(dst->internal->last_pkt_props);
485
0
    err = av_packet_copy_props(dst->internal->last_pkt_props, src->internal->last_pkt_props);
486
0
    if (err < 0)
487
0
        return err;
488
489
0
    return 0;
490
0
}
491
492
static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx,
493
                         AVPacket *in_pkt)
494
0
{
495
0
    FrameThreadContext *fctx = p->parent;
496
0
    PerThreadContext *prev_thread = fctx->prev_thread;
497
0
    const AVCodec *codec = p->avctx->codec;
498
0
    int ret;
499
500
0
    pthread_mutex_lock(&p->mutex);
501
502
0
    av_packet_unref(p->avpkt);
503
0
    av_packet_move_ref(p->avpkt, in_pkt);
504
505
0
    if (AVPACKET_IS_EMPTY(p->avpkt))
506
0
        p->avctx->internal->draining = 1;
507
508
0
    ret = update_context_from_user(p->avctx, user_avctx);
509
0
    if (ret) {
510
0
        pthread_mutex_unlock(&p->mutex);
511
0
        return ret;
512
0
    }
513
0
    atomic_store_explicit(&p->debug_threads,
514
0
                          (p->avctx->debug & FF_DEBUG_THREADS) != 0,
515
0
                          memory_order_relaxed);
516
517
0
    if (prev_thread) {
518
0
        if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
519
0
            pthread_mutex_lock(&prev_thread->progress_mutex);
520
0
            while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
521
0
                pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
522
0
            pthread_mutex_unlock(&prev_thread->progress_mutex);
523
0
        }
524
525
        /* codecs without delay might not be prepared to be called repeatedly here during
526
         * flushing (vp3/theora), and also don't need to be, since from this point on, they
527
         * will always return EOF anyway */
528
0
        if (!p->avctx->internal->draining ||
529
0
            (codec->capabilities & AV_CODEC_CAP_DELAY)) {
530
0
            ret = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
531
0
            if (ret) {
532
0
                pthread_mutex_unlock(&p->mutex);
533
0
                return ret;
534
0
            }
535
0
        }
536
0
    }
537
538
    /* transfer the stashed hwaccel state, if any */
539
0
    av_assert0(!p->avctx->hwaccel || p->hwaccel_threadsafe);
540
0
    if (!p->hwaccel_threadsafe) {
541
0
        FFSWAP(const AVHWAccel*, p->avctx->hwaccel,                     fctx->stash_hwaccel);
542
0
        FFSWAP(void*,            p->avctx->hwaccel_context,             fctx->stash_hwaccel_context);
543
0
        FFSWAP(void*,            p->avctx->internal->hwaccel_priv_data, fctx->stash_hwaccel_priv);
544
0
    }
545
546
0
    atomic_store(&p->state, STATE_SETTING_UP);
547
0
    pthread_cond_signal(&p->input_cond);
548
0
    pthread_mutex_unlock(&p->mutex);
549
550
0
    fctx->prev_thread = p;
551
0
    fctx->next_decoding = (fctx->next_decoding + 1) % p->avctx->thread_count;
552
553
0
    return 0;
554
0
}
555
556
int ff_thread_receive_frame(AVCodecContext *avctx, AVFrame *frame, unsigned flags)
557
0
{
558
0
    FrameThreadContext *fctx = avctx->internal->thread_ctx;
559
0
    int ret = 0;
560
561
    /* release the async lock, permitting blocked hwaccel threads to
562
     * go forward while we are in this function */
563
0
    async_unlock(fctx);
564
565
    /* submit packets to threads while there are no buffered results to return */
566
0
    while (!fctx->df.nb_f && !fctx->result) {
567
0
        PerThreadContext *p;
568
569
0
        if (fctx->next_decoding != fctx->next_finished &&
570
0
            (flags & AV_CODEC_RECEIVE_FRAME_FLAG_SYNCHRONOUS))
571
0
            goto wait_for_result;
572
573
        /* get a packet to be submitted to the next thread */
574
0
        av_packet_unref(fctx->next_pkt);
575
0
        ret = ff_decode_get_packet(avctx, fctx->next_pkt);
576
0
        if (ret < 0 && ret != AVERROR_EOF)
577
0
            goto finish;
578
579
0
        ret = submit_packet(&fctx->threads[fctx->next_decoding], avctx,
580
0
                            fctx->next_pkt);
581
0
        if (ret < 0)
582
0
             goto finish;
583
584
        /* do not return any frames until all threads have something to do */
585
0
        if (fctx->next_decoding != fctx->next_finished &&
586
0
            !avctx->internal->draining)
587
0
            continue;
588
589
0
    wait_for_result:
590
0
        p                   = &fctx->threads[fctx->next_finished];
591
0
        fctx->next_finished = (fctx->next_finished + 1) % avctx->thread_count;
592
593
0
        if (atomic_load(&p->state) != STATE_INPUT_READY) {
594
0
            pthread_mutex_lock(&p->progress_mutex);
595
0
            while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
596
0
                pthread_cond_wait(&p->output_cond, &p->progress_mutex);
597
0
            pthread_mutex_unlock(&p->progress_mutex);
598
0
        }
599
600
0
        update_context_from_thread(avctx, p->avctx, 1);
601
0
        fctx->result = p->result;
602
0
        p->result    = 0;
603
0
        if (p->df.nb_f)
604
0
            FFSWAP(DecodedFrames, fctx->df, p->df);
605
0
    }
606
607
    /* a thread may return multiple frames AND an error
608
     * we first return all the frames, then the error */
609
0
    if (fctx->df.nb_f) {
610
0
        decoded_frames_pop(&fctx->df, frame);
611
0
        ret = 0;
612
0
    } else {
613
0
        ret = fctx->result;
614
0
        fctx->result = 0;
615
0
    }
616
617
0
finish:
618
0
    async_lock(fctx);
619
0
    return ret;
620
0
}
621
622
void ff_thread_report_progress(ThreadFrame *f, int n, int field)
623
0
{
624
0
    PerThreadContext *p;
625
0
    atomic_int *progress = f->progress ? f->progress->progress : NULL;
626
627
0
    if (!progress ||
628
0
        atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
629
0
        return;
630
631
0
    p = f->owner[field]->internal->thread_ctx;
632
633
0
    if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
634
0
        av_log(f->owner[field], AV_LOG_DEBUG,
635
0
               "%p finished %d field %d\n", progress, n, field);
636
637
0
    pthread_mutex_lock(&p->progress_mutex);
638
639
0
    atomic_store_explicit(&progress[field], n, memory_order_release);
640
641
0
    pthread_cond_broadcast(&p->progress_cond);
642
0
    pthread_mutex_unlock(&p->progress_mutex);
643
0
}
644
645
void ff_thread_await_progress(const ThreadFrame *f, int n, int field)
646
0
{
647
0
    PerThreadContext *p;
648
0
    atomic_int *progress = f->progress ? f->progress->progress : NULL;
649
650
0
    if (!progress ||
651
0
        atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
652
0
        return;
653
654
0
    p = f->owner[field]->internal->thread_ctx;
655
656
0
    if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
657
0
        av_log(f->owner[field], AV_LOG_DEBUG,
658
0
               "thread awaiting %d field %d from %p\n", n, field, progress);
659
660
0
    pthread_mutex_lock(&p->progress_mutex);
661
0
    while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
662
0
        pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
663
0
    pthread_mutex_unlock(&p->progress_mutex);
664
0
}
665
666
0
void ff_thread_finish_setup(AVCodecContext *avctx) {
667
0
    PerThreadContext *p;
668
669
0
    if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
670
671
0
    p = avctx->internal->thread_ctx;
672
673
0
    p->hwaccel_threadsafe = avctx->hwaccel &&
674
0
                            (ffhwaccel(avctx->hwaccel)->caps_internal & HWACCEL_CAP_THREAD_SAFE);
675
676
0
    if (hwaccel_serial(avctx) && !p->hwaccel_serializing) {
677
0
        pthread_mutex_lock(&p->parent->hwaccel_mutex);
678
0
        p->hwaccel_serializing = 1;
679
0
    }
680
681
    /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
682
0
    if (avctx->hwaccel &&
683
0
        !(ffhwaccel(avctx->hwaccel)->caps_internal & HWACCEL_CAP_ASYNC_SAFE)) {
684
0
        p->async_serializing = 1;
685
686
0
        async_lock(p->parent);
687
0
    }
688
689
    /* thread-unsafe hwaccels share a single private data instance, so we
690
     * save hwaccel state for passing to the next thread;
691
     * this is done here so that this worker thread can wipe its own hwaccel
692
     * state after decoding, without requiring synchronization */
693
0
    av_assert0(!p->parent->stash_hwaccel);
694
0
    if (hwaccel_serial(avctx)) {
695
0
        p->parent->stash_hwaccel         = avctx->hwaccel;
696
0
        p->parent->stash_hwaccel_context = avctx->hwaccel_context;
697
0
        p->parent->stash_hwaccel_priv    = avctx->internal->hwaccel_priv_data;
698
0
    }
699
700
0
    pthread_mutex_lock(&p->progress_mutex);
701
0
    if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
702
0
        av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
703
0
    }
704
705
0
    atomic_store(&p->state, STATE_SETUP_FINISHED);
706
707
0
    pthread_cond_broadcast(&p->progress_cond);
708
0
    pthread_mutex_unlock(&p->progress_mutex);
709
0
}
710
711
/// Waits for all threads to finish.
712
static av_cold void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
713
0
{
714
0
    int i;
715
716
0
    async_unlock(fctx);
717
718
0
    for (i = 0; i < thread_count; i++) {
719
0
        PerThreadContext *p = &fctx->threads[i];
720
721
0
        if (atomic_load(&p->state) != STATE_INPUT_READY) {
722
0
            pthread_mutex_lock(&p->progress_mutex);
723
0
            while (atomic_load(&p->state) != STATE_INPUT_READY)
724
0
                pthread_cond_wait(&p->output_cond, &p->progress_mutex);
725
0
            pthread_mutex_unlock(&p->progress_mutex);
726
0
        }
727
0
    }
728
729
0
    async_lock(fctx);
730
0
}
731
732
#define OFF(member) offsetof(FrameThreadContext, member)
733
DEFINE_OFFSET_ARRAY(FrameThreadContext, thread_ctx, pthread_init_cnt,
734
                    (OFF(buffer_mutex), OFF(hwaccel_mutex), OFF(async_mutex)),
735
                    (OFF(async_cond)));
736
#undef OFF
737
738
#define OFF(member) offsetof(PerThreadContext, member)
739
DEFINE_OFFSET_ARRAY(PerThreadContext, per_thread, pthread_init_cnt,
740
                    (OFF(progress_mutex), OFF(mutex)),
741
                    (OFF(input_cond), OFF(progress_cond), OFF(output_cond)));
742
#undef OFF
743
744
av_cold void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
745
0
{
746
0
    FrameThreadContext *fctx = avctx->internal->thread_ctx;
747
0
    const FFCodec *codec = ffcodec(avctx->codec);
748
0
    int i;
749
750
0
    park_frame_worker_threads(fctx, thread_count);
751
752
0
    for (i = 0; i < thread_count; i++) {
753
0
        PerThreadContext *p = &fctx->threads[i];
754
0
        AVCodecContext *ctx = p->avctx;
755
756
0
        if (ctx->internal) {
757
0
            if (p->thread_init == INITIALIZED) {
758
0
                pthread_mutex_lock(&p->mutex);
759
0
                p->die = 1;
760
0
                pthread_cond_signal(&p->input_cond);
761
0
                pthread_mutex_unlock(&p->mutex);
762
763
0
                pthread_join(p->thread, NULL);
764
0
            }
765
0
            if (codec->close && p->thread_init != UNINITIALIZED)
766
0
                codec->close(ctx);
767
768
            /* When using a threadsafe hwaccel, this is where
769
             * each thread's context is uninit'd and freed. */
770
0
            ff_hwaccel_uninit(ctx);
771
772
0
            if (ctx->priv_data) {
773
0
                if (codec->p.priv_class)
774
0
                    av_opt_free(ctx->priv_data);
775
0
                av_freep(&ctx->priv_data);
776
0
            }
777
778
0
            av_refstruct_unref(&ctx->internal->pool);
779
0
            av_packet_free(&ctx->internal->in_pkt);
780
0
            av_packet_free(&ctx->internal->last_pkt_props);
781
0
            ff_decode_internal_uninit(ctx);
782
0
            av_freep(&ctx->internal);
783
0
            av_buffer_unref(&ctx->hw_frames_ctx);
784
0
            av_frame_side_data_free(&ctx->decoded_side_data,
785
0
                                    &ctx->nb_decoded_side_data);
786
0
        }
787
788
0
        decoded_frames_free(&p->df);
789
790
0
        ff_pthread_free(p, per_thread_offsets);
791
0
        av_packet_free(&p->avpkt);
792
793
0
        av_channel_layout_uninit(&ctx->ch_layout);
794
0
        av_freep(&p->avctx);
795
0
    }
796
797
0
    decoded_frames_free(&fctx->df);
798
0
    av_packet_free(&fctx->next_pkt);
799
800
0
    av_freep(&fctx->threads);
801
0
    ff_pthread_free(fctx, thread_ctx_offsets);
802
803
    /* if we have stashed hwaccel state, move it to the user-facing context,
804
     * so it will be freed in ff_codec_close() */
805
0
    av_assert0(!avctx->hwaccel);
806
0
    FFSWAP(const AVHWAccel*, avctx->hwaccel,                     fctx->stash_hwaccel);
807
0
    FFSWAP(void*,            avctx->hwaccel_context,             fctx->stash_hwaccel_context);
808
0
    FFSWAP(void*,            avctx->internal->hwaccel_priv_data, fctx->stash_hwaccel_priv);
809
810
0
    av_freep(&avctx->internal->thread_ctx);
811
0
}
812
813
static av_cold int init_thread(PerThreadContext *p, int *threads_to_free,
814
                               FrameThreadContext *fctx, AVCodecContext *avctx,
815
                               const FFCodec *codec, int first)
816
0
{
817
0
    AVCodecContext *copy;
818
0
    int err;
819
820
0
    atomic_init(&p->state, STATE_INPUT_READY);
821
822
0
    copy = av_memdup(avctx, sizeof(*avctx));
823
0
    if (!copy)
824
0
        return AVERROR(ENOMEM);
825
0
    copy->internal = NULL;
826
0
    copy->priv_data = NULL;
827
0
    copy->decoded_side_data = NULL;
828
0
    copy->nb_decoded_side_data = 0;
829
0
    copy->ch_layout = (AVChannelLayout){ 0 };
830
831
    /* From now on, this PerThreadContext will be cleaned up by
832
     * ff_frame_thread_free in case of errors. */
833
0
    (*threads_to_free)++;
834
835
0
    p->parent = fctx;
836
0
    p->avctx  = copy;
837
838
0
    err = av_channel_layout_copy(&copy->ch_layout, &avctx->ch_layout);
839
0
    if (err < 0)
840
0
        return err;
841
842
0
    copy->internal = ff_decode_internal_alloc();
843
0
    if (!copy->internal)
844
0
        return AVERROR(ENOMEM);
845
0
    ff_decode_internal_sync(copy, avctx);
846
0
    copy->internal->thread_ctx = p;
847
0
    copy->internal->progress_frame_pool = avctx->internal->progress_frame_pool;
848
849
0
    copy->delay = avctx->delay;
850
851
0
    if (codec->priv_data_size) {
852
0
        copy->priv_data = av_mallocz(codec->priv_data_size);
853
0
        if (!copy->priv_data)
854
0
            return AVERROR(ENOMEM);
855
856
0
        if (codec->p.priv_class) {
857
0
            *(const AVClass **)copy->priv_data = codec->p.priv_class;
858
0
            err = av_opt_copy(copy->priv_data, avctx->priv_data);
859
0
            if (err < 0)
860
0
                return err;
861
0
        }
862
0
    }
863
864
0
    err = ff_pthread_init(p, per_thread_offsets);
865
0
    if (err < 0)
866
0
        return err;
867
868
0
    if (!(p->avpkt = av_packet_alloc()))
869
0
        return AVERROR(ENOMEM);
870
871
0
    copy->internal->is_frame_mt = 1;
872
0
    if (!first)
873
0
        copy->internal->is_copy = 1;
874
875
0
    copy->internal->in_pkt = av_packet_alloc();
876
0
    if (!copy->internal->in_pkt)
877
0
        return AVERROR(ENOMEM);
878
879
0
    copy->internal->last_pkt_props = av_packet_alloc();
880
0
    if (!copy->internal->last_pkt_props)
881
0
        return AVERROR(ENOMEM);
882
883
0
    if (codec->init) {
884
0
        err = codec->init(copy);
885
0
        if (err < 0) {
886
0
            if (codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP)
887
0
                p->thread_init = NEEDS_CLOSE;
888
0
            return err;
889
0
        }
890
0
    }
891
0
    p->thread_init = NEEDS_CLOSE;
892
893
0
    if (first) {
894
0
        err = update_context_from_thread(avctx, copy, 1);
895
0
        if (err < 0)
896
0
            return err;
897
0
    }
898
899
0
    const AVCodecContext *src = first ? copy : avctx;
900
0
    AVCodecContext       *dst = first ? avctx : copy;
901
0
    av_frame_side_data_free(&dst->decoded_side_data, &dst->nb_decoded_side_data);
902
0
    for (int i = 0; i < src->nb_decoded_side_data; i++) {
903
0
        err = av_frame_side_data_clone(&dst->decoded_side_data,
904
0
                                       &dst->nb_decoded_side_data,
905
0
                                       src->decoded_side_data[i], 0);
906
0
        if (err < 0)
907
0
            return err;
908
0
    }
909
910
0
    atomic_init(&p->debug_threads, (copy->debug & FF_DEBUG_THREADS) != 0);
911
912
0
    err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
913
0
    if (err < 0)
914
0
        return err;
915
0
    p->thread_init = INITIALIZED;
916
917
0
    return 0;
918
0
}
919
920
av_cold int ff_frame_thread_init(AVCodecContext *avctx)
921
0
{
922
0
    int thread_count = avctx->thread_count;
923
0
    const FFCodec *codec = ffcodec(avctx->codec);
924
0
    FrameThreadContext *fctx;
925
0
    int err, i = 0;
926
927
0
    if (!thread_count) {
928
0
        int nb_cpus = av_cpu_count();
929
        // use number of cores + 1 as thread count if there is more than one
930
0
        if (nb_cpus > 1)
931
0
            thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
932
0
        else
933
0
            thread_count = avctx->thread_count = 1;
934
0
    }
935
936
0
    if (thread_count <= 1) {
937
0
        avctx->active_thread_type = 0;
938
0
        return 0;
939
0
    }
940
941
0
    avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
942
0
    if (!fctx)
943
0
        return AVERROR(ENOMEM);
944
945
0
    err = ff_pthread_init(fctx, thread_ctx_offsets);
946
0
    if (err < 0) {
947
0
        ff_pthread_free(fctx, thread_ctx_offsets);
948
0
        av_freep(&avctx->internal->thread_ctx);
949
0
        return err;
950
0
    }
951
952
0
    fctx->next_pkt = av_packet_alloc();
953
0
    if (!fctx->next_pkt)
954
0
        return AVERROR(ENOMEM);
955
956
0
    fctx->async_lock = 1;
957
958
0
    if (codec->p.type == AVMEDIA_TYPE_VIDEO)
959
0
        avctx->delay = avctx->thread_count - 1;
960
961
0
    fctx->threads = av_calloc(thread_count, sizeof(*fctx->threads));
962
0
    if (!fctx->threads) {
963
0
        err = AVERROR(ENOMEM);
964
0
        goto error;
965
0
    }
966
967
0
    for (; i < thread_count; ) {
968
0
        PerThreadContext *p  = &fctx->threads[i];
969
0
        int first = !i;
970
971
0
        err = init_thread(p, &i, fctx, avctx, codec, first);
972
0
        if (err < 0)
973
0
            goto error;
974
0
    }
975
976
0
    return 0;
977
978
0
error:
979
0
    ff_frame_thread_free(avctx, i);
980
0
    return err;
981
0
}
982
983
av_cold void ff_thread_flush(AVCodecContext *avctx)
984
0
{
985
0
    int i;
986
0
    FrameThreadContext *fctx = avctx->internal->thread_ctx;
987
988
0
    if (!fctx) return;
989
990
0
    park_frame_worker_threads(fctx, avctx->thread_count);
991
0
    if (fctx->prev_thread) {
992
0
        if (fctx->prev_thread != &fctx->threads[0])
993
0
            update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
994
0
    }
995
996
0
    fctx->next_decoding = fctx->next_finished = 0;
997
0
    fctx->prev_thread = NULL;
998
999
0
    decoded_frames_flush(&fctx->df);
1000
0
    fctx->result = 0;
1001
1002
0
    for (i = 0; i < avctx->thread_count; i++) {
1003
0
        PerThreadContext *p = &fctx->threads[i];
1004
1005
0
        decoded_frames_flush(&p->df);
1006
0
        p->result = 0;
1007
1008
0
        avcodec_flush_buffers(p->avctx);
1009
0
    }
1010
0
}
1011
1012
int ff_thread_can_start_frame(AVCodecContext *avctx)
1013
0
{
1014
0
    if ((avctx->active_thread_type & FF_THREAD_FRAME) &&
1015
0
        ffcodec(avctx->codec)->update_thread_context) {
1016
0
        PerThreadContext *p = avctx->internal->thread_ctx;
1017
1018
0
        if (atomic_load(&p->state) != STATE_SETTING_UP)
1019
0
            return 0;
1020
0
    }
1021
1022
0
    return 1;
1023
0
}
1024
1025
static int thread_get_buffer_internal(AVCodecContext *avctx, AVFrame *f, int flags)
1026
0
{
1027
0
    PerThreadContext *p;
1028
0
    int err;
1029
1030
0
    if (!(avctx->active_thread_type & FF_THREAD_FRAME))
1031
0
        return ff_get_buffer(avctx, f, flags);
1032
1033
0
    p = avctx->internal->thread_ctx;
1034
0
    if (atomic_load(&p->state) != STATE_SETTING_UP &&
1035
0
        ffcodec(avctx->codec)->update_thread_context) {
1036
0
        av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
1037
0
        return -1;
1038
0
    }
1039
1040
0
    pthread_mutex_lock(&p->parent->buffer_mutex);
1041
0
    err = ff_get_buffer(avctx, f, flags);
1042
1043
0
    pthread_mutex_unlock(&p->parent->buffer_mutex);
1044
1045
0
    return err;
1046
0
}
1047
1048
int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f, int flags)
1049
0
{
1050
0
    int ret = thread_get_buffer_internal(avctx, f, flags);
1051
0
    if (ret < 0)
1052
0
        av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1053
0
    return ret;
1054
0
}
1055
1056
int ff_thread_get_ext_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1057
0
{
1058
0
    int ret;
1059
1060
0
    f->owner[0] = f->owner[1] = avctx;
1061
0
    if (!(avctx->active_thread_type & FF_THREAD_FRAME))
1062
0
        return ff_get_buffer(avctx, f->f, flags);
1063
1064
0
    f->progress = av_refstruct_allocz(sizeof(*f->progress));
1065
0
    if (!f->progress)
1066
0
        return AVERROR(ENOMEM);
1067
1068
0
    atomic_init(&f->progress->progress[0], -1);
1069
0
    atomic_init(&f->progress->progress[1], -1);
1070
1071
0
    ret = ff_thread_get_buffer(avctx, f->f, flags);
1072
0
    if (ret)
1073
0
        av_refstruct_unref(&f->progress);
1074
0
    return ret;
1075
0
}
1076
1077
void ff_thread_release_ext_buffer(ThreadFrame *f)
1078
0
{
1079
0
    av_refstruct_unref(&f->progress);
1080
0
    f->owner[0] = f->owner[1] = NULL;
1081
0
    if (f->f)
1082
0
        av_frame_unref(f->f);
1083
0
}
1084
1085
av_cold enum ThreadingStatus ff_thread_sync_ref(AVCodecContext *avctx, size_t offset)
1086
0
{
1087
0
    PerThreadContext *p;
1088
0
    const void *ref;
1089
1090
0
    if (!avctx->internal->is_copy)
1091
0
        return avctx->active_thread_type & FF_THREAD_FRAME ?
1092
0
                  FF_THREAD_IS_FIRST_THREAD : FF_THREAD_NO_FRAME_THREADING;
1093
1094
0
    p = avctx->internal->thread_ctx;
1095
1096
0
    av_assert1(memcpy(&ref, (char*)avctx->priv_data + offset, sizeof(ref)) && ref == NULL);
1097
1098
0
    memcpy(&ref, (const char*)p->parent->threads[0].avctx->priv_data + offset, sizeof(ref));
1099
0
    av_assert1(ref);
1100
0
    av_refstruct_replace((char*)avctx->priv_data + offset, ref);
1101
1102
0
    return FF_THREAD_IS_COPY;
1103
0
}
1104
1105
int ff_thread_get_packet(AVCodecContext *avctx, AVPacket *pkt)
1106
0
{
1107
0
    PerThreadContext *p = avctx->internal->thread_ctx;
1108
1109
0
    if (!AVPACKET_IS_EMPTY(p->avpkt)) {
1110
0
        av_packet_move_ref(pkt, p->avpkt);
1111
0
        return 0;
1112
0
    }
1113
1114
0
    return avctx->internal->draining ? AVERROR_EOF : AVERROR(EAGAIN);
1115
0
}