GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/pthread_frame.c Lines: 371 536 69.2 %
Date: 2021-01-20 23:14:43 Branches: 185 325 56.9 %

Line Branch Exec 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 "config.h"
26
27
#include <stdatomic.h>
28
#include <stdint.h>
29
30
#include "avcodec.h"
31
#include "hwconfig.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
#if FF_API_THREAD_SAFE_CALLBACKS
93
    /**
94
     * Array of frames passed to ff_thread_release_buffer().
95
     * Frames are released after all threads referencing them are finished.
96
     */
97
    AVFrame **released_buffers;
98
    int   num_released_buffers;
99
    int       released_buffers_allocated;
100
101
    AVFrame *requested_frame;       ///< AVFrame the codec passed to get_buffer()
102
    int      requested_flags;       ///< flags passed to get_buffer() for requested_frame
103
104
    const enum AVPixelFormat *available_formats; ///< Format array for get_format()
105
    enum AVPixelFormat result_format;            ///< get_format() result
106
#endif
107
108
    int die;                        ///< Set when the thread should exit.
109
110
    int hwaccel_serializing;
111
    int async_serializing;
112
113
    atomic_int debug_threads;       ///< Set if the FF_DEBUG_THREADS option is set.
114
} PerThreadContext;
115
116
/**
117
 * Context stored in the client AVCodecInternal thread_ctx.
118
 */
119
typedef struct FrameThreadContext {
120
    PerThreadContext *threads;     ///< The contexts for each thread.
121
    PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
122
123
    pthread_mutex_t buffer_mutex;  ///< Mutex used to protect get/release_buffer().
124
    /**
125
     * This lock is used for ensuring threads run in serial when hwaccel
126
     * is used.
127
     */
128
    pthread_mutex_t hwaccel_mutex;
129
    pthread_mutex_t async_mutex;
130
    pthread_cond_t async_cond;
131
    int async_lock;
132
133
    int next_decoding;             ///< The next context to submit a packet to.
134
    int next_finished;             ///< The next context to return output from.
135
136
    int delaying;                  /**<
137
                                    * Set for the first N packets, where N is the number of threads.
138
                                    * While it is set, ff_thread_en/decode_frame won't return any results.
139
                                    */
140
} FrameThreadContext;
141
142
#if FF_API_THREAD_SAFE_CALLBACKS
143
#define THREAD_SAFE_CALLBACKS(avctx) \
144
((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
145
#endif
146
147
594
static void async_lock(FrameThreadContext *fctx)
148
{
149
594
    pthread_mutex_lock(&fctx->async_mutex);
150
594
    while (fctx->async_lock)
151
        pthread_cond_wait(&fctx->async_cond, &fctx->async_mutex);
152
594
    fctx->async_lock = 1;
153
594
    pthread_mutex_unlock(&fctx->async_mutex);
154
594
}
155
156
594
static void async_unlock(FrameThreadContext *fctx)
157
{
158
594
    pthread_mutex_lock(&fctx->async_mutex);
159
594
    av_assert0(fctx->async_lock);
160
594
    fctx->async_lock = 0;
161
594
    pthread_cond_broadcast(&fctx->async_cond);
162
594
    pthread_mutex_unlock(&fctx->async_mutex);
163
594
}
164
165
/**
166
 * Codec worker thread.
167
 *
168
 * Automatically calls ff_thread_finish_setup() if the codec does
169
 * not provide an update_thread_context method, or if the codec returns
170
 * before calling it.
171
 */
172
94
static attribute_align_arg void *frame_worker_thread(void *arg)
173
{
174
94
    PerThreadContext *p = arg;
175
94
    AVCodecContext *avctx = p->avctx;
176
94
    const AVCodec *codec = avctx->codec;
177
178
94
    pthread_mutex_lock(&p->mutex);
179
    while (1) {
180

1239
        while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
181
612
            pthread_cond_wait(&p->input_cond, &p->mutex);
182
183
627
        if (p->die) break;
184
185
FF_DISABLE_DEPRECATION_WARNINGS
186
533
        if (!codec->update_thread_context
187
#if FF_API_THREAD_SAFE_CALLBACKS
188

453
            && THREAD_SAFE_CALLBACKS(avctx)
189
#endif
190
            )
191
453
            ff_thread_finish_setup(avctx);
192
FF_ENABLE_DEPRECATION_WARNINGS
193
194
        /* If a decoder supports hwaccel, then it must call ff_get_format().
195
         * Since that call must happen before ff_thread_finish_setup(), the
196
         * decoder is required to implement update_thread_context() and call
197
         * ff_thread_finish_setup() manually. Therefore the above
198
         * ff_thread_finish_setup() call did not happen and hwaccel_serializing
199
         * cannot be true here. */
200
533
        av_assert0(!p->hwaccel_serializing);
201
202
        /* if the previous thread uses hwaccel then we take the lock to ensure
203
         * the threads don't run concurrently */
204
533
        if (avctx->hwaccel) {
205
            pthread_mutex_lock(&p->parent->hwaccel_mutex);
206
            p->hwaccel_serializing = 1;
207
        }
208
209
533
        av_frame_unref(p->frame);
210
533
        p->got_frame = 0;
211
533
        p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
212
213

533
        if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
214
            if (avctx->codec->caps_internal & FF_CODEC_CAP_ALLOCATE_PROGRESS)
215
                av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
216
                       "free the frame on failure. This is a bug, please report it.\n");
217
            av_frame_unref(p->frame);
218
        }
219
220
533
        if (atomic_load(&p->state) == STATE_SETTING_UP)
221
12
            ff_thread_finish_setup(avctx);
222
223
533
        if (p->hwaccel_serializing) {
224
            p->hwaccel_serializing = 0;
225
            pthread_mutex_unlock(&p->parent->hwaccel_mutex);
226
        }
227
228
533
        if (p->async_serializing) {
229
            p->async_serializing = 0;
230
231
            async_unlock(p->parent);
232
        }
233
234
533
        pthread_mutex_lock(&p->progress_mutex);
235
236
533
        atomic_store(&p->state, STATE_INPUT_READY);
237
238
533
        pthread_cond_broadcast(&p->progress_cond);
239
533
        pthread_cond_signal(&p->output_cond);
240
533
        pthread_mutex_unlock(&p->progress_mutex);
241
    }
242
94
    pthread_mutex_unlock(&p->mutex);
243
244
94
    return NULL;
245
}
246
247
/**
248
 * Update the next thread's AVCodecContext with values from the reference thread's context.
249
 *
250
 * @param dst The destination context.
251
 * @param src The source context.
252
 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
253
 * @return 0 on success, negative error code on failure
254
 */
255
1074
static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
256
{
257
1074
    int err = 0;
258
259

1074
    if (dst != src && (for_user || src->codec->update_thread_context)) {
260
621
        dst->time_base = src->time_base;
261
621
        dst->framerate = src->framerate;
262
621
        dst->width     = src->width;
263
621
        dst->height    = src->height;
264
621
        dst->pix_fmt   = src->pix_fmt;
265
621
        dst->sw_pix_fmt = src->sw_pix_fmt;
266
267
621
        dst->coded_width  = src->coded_width;
268
621
        dst->coded_height = src->coded_height;
269
270
621
        dst->has_b_frames = src->has_b_frames;
271
621
        dst->idct_algo    = src->idct_algo;
272
273
621
        dst->bits_per_coded_sample = src->bits_per_coded_sample;
274
621
        dst->sample_aspect_ratio   = src->sample_aspect_ratio;
275
276
621
        dst->profile = src->profile;
277
621
        dst->level   = src->level;
278
279
621
        dst->bits_per_raw_sample = src->bits_per_raw_sample;
280
621
        dst->ticks_per_frame     = src->ticks_per_frame;
281
621
        dst->color_primaries     = src->color_primaries;
282
283
621
        dst->color_trc   = src->color_trc;
284
621
        dst->colorspace  = src->colorspace;
285
621
        dst->color_range = src->color_range;
286
621
        dst->chroma_sample_location = src->chroma_sample_location;
287
288
621
        dst->hwaccel = src->hwaccel;
289
621
        dst->hwaccel_context = src->hwaccel_context;
290
291
621
        dst->channels       = src->channels;
292
621
        dst->sample_rate    = src->sample_rate;
293
621
        dst->sample_fmt     = src->sample_fmt;
294
621
        dst->channel_layout = src->channel_layout;
295
621
        dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
296
297
621
        if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
298

621
            (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
299
            av_buffer_unref(&dst->hw_frames_ctx);
300
301
            if (src->hw_frames_ctx) {
302
                dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
303
                if (!dst->hw_frames_ctx)
304
                    return AVERROR(ENOMEM);
305
            }
306
        }
307
308
621
        dst->hwaccel_flags = src->hwaccel_flags;
309
310
621
        err = av_buffer_replace(&dst->internal->pool, src->internal->pool);
311
621
        if (err < 0)
312
            return err;
313
    }
314
315
1074
    if (for_user) {
316
#if FF_API_CODED_FRAME
317
FF_DISABLE_DEPRECATION_WARNINGS
318
546
        dst->coded_frame = src->coded_frame;
319
FF_ENABLE_DEPRECATION_WARNINGS
320
#endif
321
    } else {
322
528
        if (dst->codec->update_thread_context)
323
75
            err = dst->codec->update_thread_context(dst, src);
324
    }
325
326
1074
    return err;
327
}
328
329
/**
330
 * Update the next thread's AVCodecContext with values set by the user.
331
 *
332
 * @param dst The destination context.
333
 * @param src The source context.
334
 * @return 0 on success, negative error code on failure
335
 */
336
533
static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
337
{
338
533
    dst->flags          = src->flags;
339
340
533
    dst->draw_horiz_band= src->draw_horiz_band;
341
533
    dst->get_buffer2    = src->get_buffer2;
342
343
533
    dst->opaque   = src->opaque;
344
533
    dst->debug    = src->debug;
345
533
    dst->debug_mv = src->debug_mv;
346
347
533
    dst->slice_flags = src->slice_flags;
348
533
    dst->flags2      = src->flags2;
349
533
    dst->export_side_data = src->export_side_data;
350
351
533
    dst->skip_loop_filter = src->skip_loop_filter;
352
533
    dst->skip_idct        = src->skip_idct;
353
533
    dst->skip_frame       = src->skip_frame;
354
355
533
    dst->frame_number     = src->frame_number;
356
533
    dst->reordered_opaque = src->reordered_opaque;
357
#if FF_API_THREAD_SAFE_CALLBACKS
358
FF_DISABLE_DEPRECATION_WARNINGS
359
533
    dst->thread_safe_callbacks = src->thread_safe_callbacks;
360
FF_ENABLE_DEPRECATION_WARNINGS
361
#endif
362
363

533
    if (src->slice_count && src->slice_offset) {
364
        if (dst->slice_count < src->slice_count) {
365
            int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
366
                                        sizeof(*dst->slice_offset));
367
            if (err < 0)
368
                return err;
369
        }
370
        memcpy(dst->slice_offset, src->slice_offset,
371
               src->slice_count * sizeof(*dst->slice_offset));
372
    }
373
533
    dst->slice_count = src->slice_count;
374
533
    return 0;
375
}
376
377
#if FF_API_THREAD_SAFE_CALLBACKS
378
/// Releases the buffers that this decoding thread was the last user of.
379
627
static void release_delayed_buffers(PerThreadContext *p)
380
{
381
627
    FrameThreadContext *fctx = p->parent;
382
383
627
    while (p->num_released_buffers > 0) {
384
        AVFrame *f;
385
386
        pthread_mutex_lock(&fctx->buffer_mutex);
387
388
        // fix extended data in case the caller screwed it up
389
        av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
390
                   p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
391
        f = p->released_buffers[--p->num_released_buffers];
392
        f->extended_data = f->data;
393
        av_frame_unref(f);
394
395
        pthread_mutex_unlock(&fctx->buffer_mutex);
396
    }
397
627
}
398
#endif
399
400
582
static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx,
401
                         AVPacket *avpkt)
402
{
403
582
    FrameThreadContext *fctx = p->parent;
404
582
    PerThreadContext *prev_thread = fctx->prev_thread;
405
582
    const AVCodec *codec = p->avctx->codec;
406
    int ret;
407
408

582
    if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
409
49
        return 0;
410
411
533
    pthread_mutex_lock(&p->mutex);
412
413
533
    ret = update_context_from_user(p->avctx, user_avctx);
414
533
    if (ret) {
415
        pthread_mutex_unlock(&p->mutex);
416
        return ret;
417
    }
418
533
    atomic_store_explicit(&p->debug_threads,
419
                          (p->avctx->debug & FF_DEBUG_THREADS) != 0,
420
                          memory_order_relaxed);
421
422
#if FF_API_THREAD_SAFE_CALLBACKS
423
533
    release_delayed_buffers(p);
424
#endif
425
426
533
    if (prev_thread) {
427
        int err;
428
521
        if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
429
95
            pthread_mutex_lock(&prev_thread->progress_mutex);
430
190
            while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
431
95
                pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
432
95
            pthread_mutex_unlock(&prev_thread->progress_mutex);
433
        }
434
435
521
        err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
436
521
        if (err) {
437
            pthread_mutex_unlock(&p->mutex);
438
            return err;
439
        }
440
    }
441
442
533
    av_packet_unref(&p->avpkt);
443
533
    ret = av_packet_ref(&p->avpkt, avpkt);
444
533
    if (ret < 0) {
445
        pthread_mutex_unlock(&p->mutex);
446
        av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
447
        return ret;
448
    }
449
450
533
    atomic_store(&p->state, STATE_SETTING_UP);
451
533
    pthread_cond_signal(&p->input_cond);
452
533
    pthread_mutex_unlock(&p->mutex);
453
454
#if FF_API_THREAD_SAFE_CALLBACKS
455
FF_DISABLE_DEPRECATION_WARNINGS
456
    /*
457
     * If the client doesn't have a thread-safe get_buffer(),
458
     * then decoding threads call back to the main thread,
459
     * and it calls back to the client here.
460
     */
461
462
533
    if (!p->avctx->thread_safe_callbacks && (
463
368
         p->avctx->get_format != avcodec_default_get_format ||
464
368
         p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
465
        while (atomic_load(&p->state) != STATE_SETUP_FINISHED && atomic_load(&p->state) != STATE_INPUT_READY) {
466
            int call_done = 1;
467
            pthread_mutex_lock(&p->progress_mutex);
468
            while (atomic_load(&p->state) == STATE_SETTING_UP)
469
                pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
470
471
            switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
472
            case STATE_GET_BUFFER:
473
                p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
474
                break;
475
            case STATE_GET_FORMAT:
476
                p->result_format = ff_get_format(p->avctx, p->available_formats);
477
                break;
478
            default:
479
                call_done = 0;
480
                break;
481
            }
482
            if (call_done) {
483
                atomic_store(&p->state, STATE_SETTING_UP);
484
                pthread_cond_signal(&p->progress_cond);
485
            }
486
            pthread_mutex_unlock(&p->progress_mutex);
487
        }
488
    }
489
FF_ENABLE_DEPRECATION_WARNINGS
490
#endif
491
492
533
    fctx->prev_thread = p;
493
533
    fctx->next_decoding++;
494
495
533
    return 0;
496
}
497
498
582
int ff_thread_decode_frame(AVCodecContext *avctx,
499
                           AVFrame *picture, int *got_picture_ptr,
500
                           AVPacket *avpkt)
501
{
502
582
    FrameThreadContext *fctx = avctx->internal->thread_ctx;
503
582
    int finished = fctx->next_finished;
504
    PerThreadContext *p;
505
    int err;
506
507
    /* release the async lock, permitting blocked hwaccel threads to
508
     * go forward while we are in this function */
509
582
    async_unlock(fctx);
510
511
    /*
512
     * Submit a packet to the next decoding thread.
513
     */
514
515
582
    p = &fctx->threads[fctx->next_decoding];
516
582
    err = submit_packet(p, avctx, avpkt);
517
582
    if (err)
518
        goto finish;
519
520
    /*
521
     * If we're still receiving the initial packets, don't return a frame.
522
     */
523
524
582
    if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
525
118
        fctx->delaying = 0;
526
527
582
    if (fctx->delaying) {
528
68
        *got_picture_ptr=0;
529
68
        if (avpkt->size) {
530
48
            err = avpkt->size;
531
48
            goto finish;
532
        }
533
    }
534
535
    /*
536
     * Return the next available frame from the oldest thread.
537
     * If we're at the end of the stream, then we have to skip threads that
538
     * didn't output a frame/error, because we don't want to accidentally signal
539
     * EOF (avpkt->size == 0 && *got_picture_ptr == 0 && err >= 0).
540
     */
541
542
    do {
543
615
        p = &fctx->threads[finished++];
544
545
615
        if (atomic_load(&p->state) != STATE_INPUT_READY) {
546
135
            pthread_mutex_lock(&p->progress_mutex);
547
270
            while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
548
135
                pthread_cond_wait(&p->output_cond, &p->progress_mutex);
549
135
            pthread_mutex_unlock(&p->progress_mutex);
550
        }
551
552
615
        av_frame_move_ref(picture, p->frame);
553
615
        *got_picture_ptr = p->got_frame;
554
615
        picture->pkt_dts = p->avpkt.dts;
555
615
        err = p->result;
556
557
        /*
558
         * A later call with avkpt->size == 0 may loop over all threads,
559
         * including this one, searching for a frame/error to return before being
560
         * stopped by the "finished != fctx->next_finished" condition.
561
         * Make sure we don't mistakenly return the same frame/error again.
562
         */
563
615
        p->got_frame = 0;
564
615
        p->result = 0;
565
566
615
        if (finished >= avctx->thread_count) finished = 0;
567


615
    } while (!avpkt->size && !*got_picture_ptr && err >= 0 && finished != fctx->next_finished);
568
569
534
    update_context_from_thread(avctx, p->avctx, 1);
570
571
534
    if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
572
573
534
    fctx->next_finished = finished;
574
575
    /* return the size of the consumed packet if no error occurred */
576
534
    if (err >= 0)
577
534
        err = avpkt->size;
578
finish:
579
582
    async_lock(fctx);
580
582
    return err;
581
}
582
583
408447
void ff_thread_report_progress(ThreadFrame *f, int n, int field)
584
{
585
    PerThreadContext *p;
586
408447
    atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
587
588
408447
    if (!progress ||
589
1172
        atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
590
407294
        return;
591
592
1153
    p = f->owner[field]->internal->thread_ctx;
593
594
1153
    if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
595
        av_log(f->owner[field], AV_LOG_DEBUG,
596
               "%p finished %d field %d\n", progress, n, field);
597
598
1153
    pthread_mutex_lock(&p->progress_mutex);
599
600
1153
    atomic_store_explicit(&progress[field], n, memory_order_release);
601
602
1153
    pthread_cond_broadcast(&p->progress_cond);
603
1153
    pthread_mutex_unlock(&p->progress_mutex);
604
}
605
606
2681377
void ff_thread_await_progress(ThreadFrame *f, int n, int field)
607
{
608
    PerThreadContext *p;
609
2681377
    atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
610
611
2681377
    if (!progress ||
612
182570
        atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
613
2680925
        return;
614
615
452
    p = f->owner[field]->internal->thread_ctx;
616
617
452
    if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
618
        av_log(f->owner[field], AV_LOG_DEBUG,
619
               "thread awaiting %d field %d from %p\n", n, field, progress);
620
621
452
    pthread_mutex_lock(&p->progress_mutex);
622
915
    while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
623
463
        pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
624
452
    pthread_mutex_unlock(&p->progress_mutex);
625
}
626
627
29043
void ff_thread_finish_setup(AVCodecContext *avctx) {
628
29043
    PerThreadContext *p = avctx->internal->thread_ctx;
629
630
29043
    if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
631
632

533
    if (avctx->hwaccel && !p->hwaccel_serializing) {
633
        pthread_mutex_lock(&p->parent->hwaccel_mutex);
634
        p->hwaccel_serializing = 1;
635
    }
636
637
    /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
638
533
    if (avctx->hwaccel &&
639
        !(avctx->hwaccel->caps_internal & HWACCEL_CAP_ASYNC_SAFE)) {
640
        p->async_serializing = 1;
641
642
        async_lock(p->parent);
643
    }
644
645
533
    pthread_mutex_lock(&p->progress_mutex);
646
533
    if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
647
        av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
648
    }
649
650
533
    atomic_store(&p->state, STATE_SETUP_FINISHED);
651
652
533
    pthread_cond_broadcast(&p->progress_cond);
653
533
    pthread_mutex_unlock(&p->progress_mutex);
654
}
655
656
/// Waits for all threads to finish.
657
12
static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
658
{
659
    int i;
660
661
12
    async_unlock(fctx);
662
663
106
    for (i = 0; i < thread_count; i++) {
664
94
        PerThreadContext *p = &fctx->threads[i];
665
666
94
        if (atomic_load(&p->state) != STATE_INPUT_READY) {
667
            pthread_mutex_lock(&p->progress_mutex);
668
            while (atomic_load(&p->state) != STATE_INPUT_READY)
669
                pthread_cond_wait(&p->output_cond, &p->progress_mutex);
670
            pthread_mutex_unlock(&p->progress_mutex);
671
        }
672
94
        p->got_frame = 0;
673
    }
674
675
12
    async_lock(fctx);
676
12
}
677
678
12
void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
679
{
680
12
    FrameThreadContext *fctx = avctx->internal->thread_ctx;
681
12
    const AVCodec *codec = avctx->codec;
682
    int i;
683
684
12
    park_frame_worker_threads(fctx, thread_count);
685
686
12
    if (fctx->prev_thread && avctx->internal->hwaccel_priv_data !=
687
12
                             fctx->prev_thread->avctx->internal->hwaccel_priv_data) {
688
        if (update_context_from_thread(avctx, fctx->prev_thread->avctx, 1) < 0) {
689
            av_log(avctx, AV_LOG_ERROR, "Failed to update user thread.\n");
690
        }
691
    }
692
693

12
    if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
694
7
        if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
695
            av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
696
            fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
697
            fctx->threads->avctx->internal->is_copy = 1;
698
        }
699
700
106
    for (i = 0; i < thread_count; i++) {
701
94
        PerThreadContext *p = &fctx->threads[i];
702
703
94
        pthread_mutex_lock(&p->mutex);
704
94
        p->die = 1;
705
94
        pthread_cond_signal(&p->input_cond);
706
94
        pthread_mutex_unlock(&p->mutex);
707
708
94
        if (p->thread_init)
709
94
            pthread_join(p->thread, NULL);
710
94
        p->thread_init=0;
711
712

94
        if (codec->close && p->avctx)
713
94
            codec->close(p->avctx);
714
715
#if FF_API_THREAD_SAFE_CALLBACKS
716
94
        release_delayed_buffers(p);
717
#endif
718
94
        av_frame_free(&p->frame);
719
    }
720
721
106
    for (i = 0; i < thread_count; i++) {
722
94
        PerThreadContext *p = &fctx->threads[i];
723
724
94
        pthread_mutex_destroy(&p->mutex);
725
94
        pthread_mutex_destroy(&p->progress_mutex);
726
94
        pthread_cond_destroy(&p->input_cond);
727
94
        pthread_cond_destroy(&p->progress_cond);
728
94
        pthread_cond_destroy(&p->output_cond);
729
94
        av_packet_unref(&p->avpkt);
730
731
#if FF_API_THREAD_SAFE_CALLBACKS
732
94
        for (int j = 0; j < p->released_buffers_allocated; j++)
733
            av_frame_free(&p->released_buffers[j]);
734
94
        av_freep(&p->released_buffers);
735
#endif
736
737
94
        if (p->avctx) {
738
94
            if (codec->priv_class)
739
40
                av_opt_free(p->avctx->priv_data);
740
94
            av_freep(&p->avctx->priv_data);
741
742
94
            av_freep(&p->avctx->slice_offset);
743
        }
744
745
94
        if (p->avctx) {
746
94
            av_buffer_unref(&p->avctx->internal->pool);
747
94
            av_freep(&p->avctx->internal);
748
94
            av_buffer_unref(&p->avctx->hw_frames_ctx);
749
        }
750
751
94
        av_freep(&p->avctx);
752
    }
753
754
12
    av_freep(&fctx->threads);
755
12
    pthread_mutex_destroy(&fctx->buffer_mutex);
756
12
    pthread_mutex_destroy(&fctx->hwaccel_mutex);
757
12
    pthread_mutex_destroy(&fctx->async_mutex);
758
12
    pthread_cond_destroy(&fctx->async_cond);
759
760
12
    av_freep(&avctx->internal->thread_ctx);
761
762

12
    if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
763
6
        av_opt_free(avctx->priv_data);
764
12
    avctx->codec = NULL;
765
12
}
766
767
12
int ff_frame_thread_init(AVCodecContext *avctx)
768
{
769
12
    int thread_count = avctx->thread_count;
770
12
    const AVCodec *codec = avctx->codec;
771
12
    AVCodecContext *src = avctx;
772
    FrameThreadContext *fctx;
773
12
    int i, err = 0;
774
775
12
    if (!thread_count) {
776
4
        int nb_cpus = av_cpu_count();
777
#if FF_API_DEBUG_MV
778
        if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
779
            nb_cpus = 1;
780
#endif
781
        // use number of cores + 1 as thread count if there is more than one
782
4
        if (nb_cpus > 1)
783
4
            thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
784
        else
785
            thread_count = avctx->thread_count = 1;
786
    }
787
788
12
    if (thread_count <= 1) {
789
        avctx->active_thread_type = 0;
790
        return 0;
791
    }
792
793
12
    avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
794
12
    if (!fctx)
795
        return AVERROR(ENOMEM);
796
797
12
    fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
798
12
    if (!fctx->threads) {
799
        av_freep(&avctx->internal->thread_ctx);
800
        return AVERROR(ENOMEM);
801
    }
802
803
12
    pthread_mutex_init(&fctx->buffer_mutex, NULL);
804
12
    pthread_mutex_init(&fctx->hwaccel_mutex, NULL);
805
12
    pthread_mutex_init(&fctx->async_mutex, NULL);
806
12
    pthread_cond_init(&fctx->async_cond, NULL);
807
808
12
    fctx->async_lock = 1;
809
12
    fctx->delaying = 1;
810
811
12
    if (codec->type == AVMEDIA_TYPE_VIDEO)
812
8
        avctx->delay = src->thread_count - 1;
813
814
106
    for (i = 0; i < thread_count; i++) {
815
94
        AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
816
94
        PerThreadContext *p  = &fctx->threads[i];
817
818
94
        pthread_mutex_init(&p->mutex, NULL);
819
94
        pthread_mutex_init(&p->progress_mutex, NULL);
820
94
        pthread_cond_init(&p->input_cond, NULL);
821
94
        pthread_cond_init(&p->progress_cond, NULL);
822
94
        pthread_cond_init(&p->output_cond, NULL);
823
824
94
        p->frame = av_frame_alloc();
825
94
        if (!p->frame) {
826
            av_freep(&copy);
827
            err = AVERROR(ENOMEM);
828
            goto error;
829
        }
830
831
94
        p->parent = fctx;
832
94
        p->avctx  = copy;
833
834
94
        if (!copy) {
835
            err = AVERROR(ENOMEM);
836
            goto error;
837
        }
838
839
94
        *copy = *src;
840
841
94
        copy->internal = av_malloc(sizeof(AVCodecInternal));
842
94
        if (!copy->internal) {
843
            copy->priv_data = NULL;
844
            err = AVERROR(ENOMEM);
845
            goto error;
846
        }
847
94
        *copy->internal = *src->internal;
848
94
        copy->internal->thread_ctx = p;
849
94
        copy->internal->last_pkt_props = &p->avpkt;
850
851
94
        copy->delay = avctx->delay;
852
853
94
        if (codec->priv_data_size) {
854
94
            copy->priv_data = av_mallocz(codec->priv_data_size);
855
94
            if (!copy->priv_data) {
856
                err = AVERROR(ENOMEM);
857
                goto error;
858
            }
859
860
94
            if (codec->priv_class) {
861
40
                *(const AVClass **)copy->priv_data = codec->priv_class;
862
40
                err = av_opt_copy(copy->priv_data, src->priv_data);
863
40
                if (err < 0)
864
                    goto error;
865
            }
866
        }
867
868
94
        if (i)
869
82
            copy->internal->is_copy = 1;
870
871
94
        if (codec->init)
872
94
            err = codec->init(copy);
873
874
94
        if (err) goto error;
875
876
94
        if (!i)
877
12
            update_context_from_thread(avctx, copy, 1);
878
879
94
        atomic_init(&p->debug_threads, (copy->debug & FF_DEBUG_THREADS) != 0);
880
881
94
        err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
882
94
        p->thread_init= !err;
883
94
        if(!p->thread_init)
884
            goto error;
885
    }
886
887
12
    return 0;
888
889
error:
890
    ff_frame_thread_free(avctx, i+1);
891
892
    return err;
893
}
894
895
void ff_thread_flush(AVCodecContext *avctx)
896
{
897
    int i;
898
    FrameThreadContext *fctx = avctx->internal->thread_ctx;
899
900
    if (!fctx) return;
901
902
    park_frame_worker_threads(fctx, avctx->thread_count);
903
    if (fctx->prev_thread) {
904
        if (fctx->prev_thread != &fctx->threads[0])
905
            update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
906
    }
907
908
    fctx->next_decoding = fctx->next_finished = 0;
909
    fctx->delaying = 1;
910
    fctx->prev_thread = NULL;
911
    for (i = 0; i < avctx->thread_count; i++) {
912
        PerThreadContext *p = &fctx->threads[i];
913
        // Make sure decode flush calls with size=0 won't return old frames
914
        p->got_frame = 0;
915
        av_frame_unref(p->frame);
916
        p->result = 0;
917
918
#if FF_API_THREAD_SAFE_CALLBACKS
919
        release_delayed_buffers(p);
920
#endif
921
922
        if (avctx->codec->flush)
923
            avctx->codec->flush(p->avctx);
924
    }
925
}
926
927
34090
int ff_thread_can_start_frame(AVCodecContext *avctx)
928
{
929
34090
    PerThreadContext *p = avctx->internal->thread_ctx;
930
FF_DISABLE_DEPRECATION_WARNINGS
931

34090
    if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
932
        (avctx->codec->update_thread_context
933
#if FF_API_THREAD_SAFE_CALLBACKS
934
         || !THREAD_SAFE_CALLBACKS(avctx)
935
#endif
936
         )) {
937
        return 0;
938
    }
939
FF_ENABLE_DEPRECATION_WARNINGS
940
34090
    return 1;
941
}
942
943
79611
static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
944
{
945
79611
    PerThreadContext *p = avctx->internal->thread_ctx;
946
    int err;
947
948
79611
    f->owner[0] = f->owner[1] = avctx;
949
950
79611
    if (!(avctx->active_thread_type & FF_THREAD_FRAME))
951
79090
        return ff_get_buffer(avctx, f->f, flags);
952
953
FF_DISABLE_DEPRECATION_WARNINGS
954
521
    if (atomic_load(&p->state) != STATE_SETTING_UP &&
955
453
        (avctx->codec->update_thread_context
956
#if FF_API_THREAD_SAFE_CALLBACKS
957

453
         || !THREAD_SAFE_CALLBACKS(avctx)
958
#endif
959
         )) {
960
FF_ENABLE_DEPRECATION_WARNINGS
961
        av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
962
        return -1;
963
    }
964
965
521
    if (avctx->codec->caps_internal & FF_CODEC_CAP_ALLOCATE_PROGRESS) {
966
        atomic_int *progress;
967
68
        f->progress = av_buffer_alloc(2 * sizeof(*progress));
968
68
        if (!f->progress) {
969
            return AVERROR(ENOMEM);
970
        }
971
68
        progress = (atomic_int*)f->progress->data;
972
973
68
        atomic_init(&progress[0], -1);
974
68
        atomic_init(&progress[1], -1);
975
    }
976
977
521
    pthread_mutex_lock(&p->parent->buffer_mutex);
978
#if !FF_API_THREAD_SAFE_CALLBACKS
979
    err = ff_get_buffer(avctx, f->f, flags);
980
#else
981
FF_DISABLE_DEPRECATION_WARNINGS
982

521
    if (THREAD_SAFE_CALLBACKS(avctx)) {
983
521
        err = ff_get_buffer(avctx, f->f, flags);
984
    } else {
985
        pthread_mutex_lock(&p->progress_mutex);
986
        p->requested_frame = f->f;
987
        p->requested_flags = flags;
988
        atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
989
        pthread_cond_broadcast(&p->progress_cond);
990
991
        while (atomic_load(&p->state) != STATE_SETTING_UP)
992
            pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
993
994
        err = p->result;
995
996
        pthread_mutex_unlock(&p->progress_mutex);
997
998
    }
999

521
    if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
1000
        ff_thread_finish_setup(avctx);
1001
FF_ENABLE_DEPRECATION_WARNINGS
1002
#endif
1003
521
    if (err)
1004
        av_buffer_unref(&f->progress);
1005
1006
521
    pthread_mutex_unlock(&p->parent->buffer_mutex);
1007
1008
521
    return err;
1009
}
1010
1011
#if FF_API_THREAD_SAFE_CALLBACKS
1012
FF_DISABLE_DEPRECATION_WARNINGS
1013
1630
enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1014
{
1015
    enum AVPixelFormat res;
1016
1630
    PerThreadContext *p = avctx->internal->thread_ctx;
1017

1630
    if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
1018
1
        avctx->get_format == avcodec_default_get_format)
1019
1630
        return ff_get_format(avctx, fmt);
1020
    if (atomic_load(&p->state) != STATE_SETTING_UP) {
1021
        av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
1022
        return -1;
1023
    }
1024
    pthread_mutex_lock(&p->progress_mutex);
1025
    p->available_formats = fmt;
1026
    atomic_store(&p->state, STATE_GET_FORMAT);
1027
    pthread_cond_broadcast(&p->progress_cond);
1028
1029
    while (atomic_load(&p->state) != STATE_SETTING_UP)
1030
        pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
1031
1032
    res = p->result_format;
1033
1034
    pthread_mutex_unlock(&p->progress_mutex);
1035
1036
    return res;
1037
}
1038
FF_ENABLE_DEPRECATION_WARNINGS
1039
#endif
1040
1041
79611
int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1042
{
1043
79611
    int ret = thread_get_buffer_internal(avctx, f, flags);
1044
79611
    if (ret < 0)
1045
93
        av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1046
79611
    return ret;
1047
}
1048
1049
902017
void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1050
{
1051
#if FF_API_THREAD_SAFE_CALLBACKS
1052
FF_DISABLE_DEPRECATION_WARNINGS
1053
902017
    PerThreadContext *p = avctx->internal->thread_ctx;
1054
    FrameThreadContext *fctx;
1055
    AVFrame *dst;
1056
902017
    int ret = 0;
1057
902526
    int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1058

509
                          THREAD_SAFE_CALLBACKS(avctx);
1059
FF_ENABLE_DEPRECATION_WARNINGS
1060
#endif
1061
1062
902017
    if (!f->f)
1063
322
        return;
1064
1065
901695
    if (avctx->debug & FF_DEBUG_BUFFERS)
1066
        av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1067
1068
901695
    av_buffer_unref(&f->progress);
1069
901695
    f->owner[0] = f->owner[1] = NULL;
1070
1071
#if !FF_API_THREAD_SAFE_CALLBACKS
1072
    av_frame_unref(f->f);
1073
#else
1074
    // when the frame buffers are not allocated, just reset it to clean state
1075

901695
    if (can_direct_free || !f->f->buf[0]) {
1076
901695
        av_frame_unref(f->f);
1077
901695
        return;
1078
    }
1079
1080
    fctx = p->parent;
1081
    pthread_mutex_lock(&fctx->buffer_mutex);
1082
1083
    if (p->num_released_buffers == p->released_buffers_allocated) {
1084
        AVFrame **tmp = av_realloc_array(p->released_buffers, p->released_buffers_allocated + 1,
1085
                                         sizeof(*p->released_buffers));
1086
        if (tmp) {
1087
            tmp[p->released_buffers_allocated] = av_frame_alloc();
1088
            p->released_buffers = tmp;
1089
        }
1090
1091
        if (!tmp || !tmp[p->released_buffers_allocated]) {
1092
            ret = AVERROR(ENOMEM);
1093
            goto fail;
1094
        }
1095
        p->released_buffers_allocated++;
1096
    }
1097
1098
    dst = p->released_buffers[p->num_released_buffers];
1099
    av_frame_move_ref(dst, f->f);
1100
1101
    p->num_released_buffers++;
1102
1103
fail:
1104
    pthread_mutex_unlock(&fctx->buffer_mutex);
1105
1106
    // make sure the frame is clean even if we fail to free it
1107
    // this leaks, but it is better than crashing
1108
    if (ret < 0) {
1109
        av_log(avctx, AV_LOG_ERROR, "Could not queue a frame for freeing, this will leak\n");
1110
        memset(f->f->buf, 0, sizeof(f->f->buf));
1111
        if (f->f->extended_buf)
1112
            memset(f->f->extended_buf, 0, f->f->nb_extended_buf * sizeof(*f->f->extended_buf));
1113
        av_frame_unref(f->f);
1114
    }
1115
#endif
1116
}