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

1236
        while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
177
609
            pthread_cond_wait(&p->input_cond, &p->mutex);
178
179
627
        if (p->die) break;
180
181

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

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

1074
    if (dst != src && (for_user || src->codec->update_thread_context)) {
250
621
        dst->time_base = src->time_base;
251
621
        dst->framerate = src->framerate;
252
621
        dst->width     = src->width;
253
621
        dst->height    = src->height;
254
621
        dst->pix_fmt   = src->pix_fmt;
255
621
        dst->sw_pix_fmt = src->sw_pix_fmt;
256
257
621
        dst->coded_width  = src->coded_width;
258
621
        dst->coded_height = src->coded_height;
259
260
621
        dst->has_b_frames = src->has_b_frames;
261
621
        dst->idct_algo    = src->idct_algo;
262
263
621
        dst->bits_per_coded_sample = src->bits_per_coded_sample;
264
621
        dst->sample_aspect_ratio   = src->sample_aspect_ratio;
265
266
621
        dst->profile = src->profile;
267
621
        dst->level   = src->level;
268
269
621
        dst->bits_per_raw_sample = src->bits_per_raw_sample;
270
621
        dst->ticks_per_frame     = src->ticks_per_frame;
271
621
        dst->color_primaries     = src->color_primaries;
272
273
621
        dst->color_trc   = src->color_trc;
274
621
        dst->colorspace  = src->colorspace;
275
621
        dst->color_range = src->color_range;
276
621
        dst->chroma_sample_location = src->chroma_sample_location;
277
278
621
        dst->hwaccel = src->hwaccel;
279
621
        dst->hwaccel_context = src->hwaccel_context;
280
281
621
        dst->channels       = src->channels;
282
621
        dst->sample_rate    = src->sample_rate;
283
621
        dst->sample_fmt     = src->sample_fmt;
284
621
        dst->channel_layout = src->channel_layout;
285
621
        dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
286
287
621
        if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
288

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

533
    if (src->slice_count && src->slice_offset) {
350
        if (dst->slice_count < src->slice_count) {
351
            int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
352
                                        sizeof(*dst->slice_offset));
353
            if (err < 0)
354
                return err;
355
        }
356
        memcpy(dst->slice_offset, src->slice_offset,
357
               src->slice_count * sizeof(*dst->slice_offset));
358
    }
359
533
    dst->slice_count = src->slice_count;
360
533
    return 0;
361
}
362
363
/// Releases the buffers that this decoding thread was the last user of.
364
627
static void release_delayed_buffers(PerThreadContext *p)
365
{
366
627
    FrameThreadContext *fctx = p->parent;
367
368
627
    while (p->num_released_buffers > 0) {
369
        AVFrame *f;
370
371
        pthread_mutex_lock(&fctx->buffer_mutex);
372
373
        // fix extended data in case the caller screwed it up
374
        av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
375
                   p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
376
        f = p->released_buffers[--p->num_released_buffers];
377
        f->extended_data = f->data;
378
        av_frame_unref(f);
379
380
        pthread_mutex_unlock(&fctx->buffer_mutex);
381
    }
382
627
}
383
384
582
static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx,
385
                         AVPacket *avpkt)
386
{
387
582
    FrameThreadContext *fctx = p->parent;
388
582
    PerThreadContext *prev_thread = fctx->prev_thread;
389
582
    const AVCodec *codec = p->avctx->codec;
390
    int ret;
391
392

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


615
    } while (!avpkt->size && !*got_picture_ptr && err >= 0 && finished != fctx->next_finished);
546
547
534
    update_context_from_thread(avctx, p->avctx, 1);
548
549
534
    if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
550
551
534
    fctx->next_finished = finished;
552
553
    /* return the size of the consumed packet if no error occurred */
554
534
    if (err >= 0)
555
534
        err = avpkt->size;
556
finish:
557
582
    async_lock(fctx);
558
582
    return err;
559
}
560
561
410349
void ff_thread_report_progress(ThreadFrame *f, int n, int field)
562
{
563
    PerThreadContext *p;
564
410349
    atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
565
566
410349
    if (!progress ||
567
1172
        atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
568
409196
        return;
569
570
1153
    p = f->owner[field]->internal->thread_ctx;
571
572
1153
    if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
573
        av_log(f->owner[field], AV_LOG_DEBUG,
574
               "%p finished %d field %d\n", progress, n, field);
575
576
1153
    pthread_mutex_lock(&p->progress_mutex);
577
578
1153
    atomic_store_explicit(&progress[field], n, memory_order_release);
579
580
1153
    pthread_cond_broadcast(&p->progress_cond);
581
1153
    pthread_mutex_unlock(&p->progress_mutex);
582
}
583
584
2681377
void ff_thread_await_progress(ThreadFrame *f, int n, int field)
585
{
586
    PerThreadContext *p;
587
2681377
    atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
588
589
2681377
    if (!progress ||
590
182570
        atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
591
2680858
        return;
592
593
519
    p = f->owner[field]->internal->thread_ctx;
594
595
519
    if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
596
        av_log(f->owner[field], AV_LOG_DEBUG,
597
               "thread awaiting %d field %d from %p\n", n, field, progress);
598
599
519
    pthread_mutex_lock(&p->progress_mutex);
600
1051
    while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
601
532
        pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
602
519
    pthread_mutex_unlock(&p->progress_mutex);
603
}
604
605
29140
void ff_thread_finish_setup(AVCodecContext *avctx) {
606
29140
    PerThreadContext *p = avctx->internal->thread_ctx;
607
608
29140
    if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
609
610

533
    if (avctx->hwaccel && !p->hwaccel_serializing) {
611
        pthread_mutex_lock(&p->parent->hwaccel_mutex);
612
        p->hwaccel_serializing = 1;
613
    }
614
615
    /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
616
533
    if (avctx->hwaccel &&
617
        !(avctx->hwaccel->caps_internal & HWACCEL_CAP_ASYNC_SAFE)) {
618
        p->async_serializing = 1;
619
620
        async_lock(p->parent);
621
    }
622
623
533
    pthread_mutex_lock(&p->progress_mutex);
624
533
    if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
625
        av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
626
    }
627
628
533
    atomic_store(&p->state, STATE_SETUP_FINISHED);
629
630
533
    pthread_cond_broadcast(&p->progress_cond);
631
533
    pthread_mutex_unlock(&p->progress_mutex);
632
}
633
634
/// Waits for all threads to finish.
635
12
static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
636
{
637
    int i;
638
639
12
    async_unlock(fctx);
640
641
106
    for (i = 0; i < thread_count; i++) {
642
94
        PerThreadContext *p = &fctx->threads[i];
643
644
94
        if (atomic_load(&p->state) != STATE_INPUT_READY) {
645
            pthread_mutex_lock(&p->progress_mutex);
646
            while (atomic_load(&p->state) != STATE_INPUT_READY)
647
                pthread_cond_wait(&p->output_cond, &p->progress_mutex);
648
            pthread_mutex_unlock(&p->progress_mutex);
649
        }
650
94
        p->got_frame = 0;
651
    }
652
653
12
    async_lock(fctx);
654
12
}
655
656
12
void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
657
{
658
12
    FrameThreadContext *fctx = avctx->internal->thread_ctx;
659
12
    const AVCodec *codec = avctx->codec;
660
    int i, j;
661
662
12
    park_frame_worker_threads(fctx, thread_count);
663
664
12
    if (fctx->prev_thread && avctx->internal->hwaccel_priv_data !=
665
12
                             fctx->prev_thread->avctx->internal->hwaccel_priv_data) {
666
        if (update_context_from_thread(avctx, fctx->prev_thread->avctx, 1) < 0) {
667
            av_log(avctx, AV_LOG_ERROR, "Failed to update user thread.\n");
668
        }
669
    }
670
671

12
    if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
672
7
        if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
673
            av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
674
            fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
675
            fctx->threads->avctx->internal->is_copy = 1;
676
        }
677
678
106
    for (i = 0; i < thread_count; i++) {
679
94
        PerThreadContext *p = &fctx->threads[i];
680
681
94
        pthread_mutex_lock(&p->mutex);
682
94
        p->die = 1;
683
94
        pthread_cond_signal(&p->input_cond);
684
94
        pthread_mutex_unlock(&p->mutex);
685
686
94
        if (p->thread_init)
687
94
            pthread_join(p->thread, NULL);
688
94
        p->thread_init=0;
689
690

94
        if (codec->close && p->avctx)
691
94
            codec->close(p->avctx);
692
693
94
        release_delayed_buffers(p);
694
94
        av_frame_free(&p->frame);
695
    }
696
697
106
    for (i = 0; i < thread_count; i++) {
698
94
        PerThreadContext *p = &fctx->threads[i];
699
700
94
        pthread_mutex_destroy(&p->mutex);
701
94
        pthread_mutex_destroy(&p->progress_mutex);
702
94
        pthread_cond_destroy(&p->input_cond);
703
94
        pthread_cond_destroy(&p->progress_cond);
704
94
        pthread_cond_destroy(&p->output_cond);
705
94
        av_packet_unref(&p->avpkt);
706
707
94
        for (j = 0; j < p->released_buffers_allocated; j++)
708
            av_frame_free(&p->released_buffers[j]);
709
94
        av_freep(&p->released_buffers);
710
711
94
        if (p->avctx) {
712
94
            if (codec->priv_class)
713
40
                av_opt_free(p->avctx->priv_data);
714
94
            av_freep(&p->avctx->priv_data);
715
716
94
            av_freep(&p->avctx->slice_offset);
717
        }
718
719
94
        if (p->avctx) {
720
94
            av_buffer_unref(&p->avctx->internal->pool);
721
94
            av_freep(&p->avctx->internal);
722
94
            av_buffer_unref(&p->avctx->hw_frames_ctx);
723
        }
724
725
94
        av_freep(&p->avctx);
726
    }
727
728
12
    av_freep(&fctx->threads);
729
12
    pthread_mutex_destroy(&fctx->buffer_mutex);
730
12
    pthread_mutex_destroy(&fctx->hwaccel_mutex);
731
12
    pthread_mutex_destroy(&fctx->async_mutex);
732
12
    pthread_cond_destroy(&fctx->async_cond);
733
734
12
    av_freep(&avctx->internal->thread_ctx);
735
736

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

34190
    if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
903
        (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
904
        return 0;
905
    }
906
34190
    return 1;
907
}
908
909
79648
static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
910
{
911
79648
    PerThreadContext *p = avctx->internal->thread_ctx;
912
    int err;
913
914
79648
    f->owner[0] = f->owner[1] = avctx;
915
916
79648
    if (!(avctx->active_thread_type & FF_THREAD_FRAME))
917
79127
        return ff_get_buffer(avctx, f->f, flags);
918
919
521
    if (atomic_load(&p->state) != STATE_SETTING_UP &&
920

453
        (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
921
        av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
922
        return -1;
923
    }
924
925
521
    if (avctx->codec->caps_internal & FF_CODEC_CAP_ALLOCATE_PROGRESS) {
926
        atomic_int *progress;
927
68
        f->progress = av_buffer_alloc(2 * sizeof(*progress));
928
68
        if (!f->progress) {
929
            return AVERROR(ENOMEM);
930
        }
931
68
        progress = (atomic_int*)f->progress->data;
932
933
68
        atomic_init(&progress[0], -1);
934
68
        atomic_init(&progress[1], -1);
935
    }
936
937
521
    pthread_mutex_lock(&p->parent->buffer_mutex);
938

521
    if (THREAD_SAFE_CALLBACKS(avctx)) {
939
521
        err = ff_get_buffer(avctx, f->f, flags);
940
    } else {
941
        pthread_mutex_lock(&p->progress_mutex);
942
        p->requested_frame = f->f;
943
        p->requested_flags = flags;
944
        atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
945
        pthread_cond_broadcast(&p->progress_cond);
946
947
        while (atomic_load(&p->state) != STATE_SETTING_UP)
948
            pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
949
950
        err = p->result;
951
952
        pthread_mutex_unlock(&p->progress_mutex);
953
954
    }
955

521
    if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
956
        ff_thread_finish_setup(avctx);
957
521
    if (err)
958
        av_buffer_unref(&f->progress);
959
960
521
    pthread_mutex_unlock(&p->parent->buffer_mutex);
961
962
521
    return err;
963
}
964
965
1626
enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
966
{
967
    enum AVPixelFormat res;
968
1626
    PerThreadContext *p = avctx->internal->thread_ctx;
969

1626
    if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
970
1
        avctx->get_format == avcodec_default_get_format)
971
1626
        return ff_get_format(avctx, fmt);
972
    if (atomic_load(&p->state) != STATE_SETTING_UP) {
973
        av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
974
        return -1;
975
    }
976
    pthread_mutex_lock(&p->progress_mutex);
977
    p->available_formats = fmt;
978
    atomic_store(&p->state, STATE_GET_FORMAT);
979
    pthread_cond_broadcast(&p->progress_cond);
980
981
    while (atomic_load(&p->state) != STATE_SETTING_UP)
982
        pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
983
984
    res = p->result_format;
985
986
    pthread_mutex_unlock(&p->progress_mutex);
987
988
    return res;
989
}
990
991
79648
int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
992
{
993
79648
    int ret = thread_get_buffer_internal(avctx, f, flags);
994
79648
    if (ret < 0)
995
93
        av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
996
79648
    return ret;
997
}
998
999
905820
void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1000
{
1001
905820
    PerThreadContext *p = avctx->internal->thread_ctx;
1002
    FrameThreadContext *fctx;
1003
    AVFrame *dst;
1004
905820
    int ret = 0;
1005
906329
    int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1006

509
                          THREAD_SAFE_CALLBACKS(avctx);
1007
1008
905820
    if (!f->f)
1009
322
        return;
1010
1011
905498
    if (avctx->debug & FF_DEBUG_BUFFERS)
1012
        av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1013
1014
905498
    av_buffer_unref(&f->progress);
1015
905498
    f->owner[0] = f->owner[1] = NULL;
1016
1017
    // when the frame buffers are not allocated, just reset it to clean state
1018

905498
    if (can_direct_free || !f->f->buf[0]) {
1019
905498
        av_frame_unref(f->f);
1020
905498
        return;
1021
    }
1022
1023
    fctx = p->parent;
1024
    pthread_mutex_lock(&fctx->buffer_mutex);
1025
1026
    if (p->num_released_buffers == p->released_buffers_allocated) {
1027
        AVFrame **tmp = av_realloc_array(p->released_buffers, p->released_buffers_allocated + 1,
1028
                                         sizeof(*p->released_buffers));
1029
        if (tmp) {
1030
            tmp[p->released_buffers_allocated] = av_frame_alloc();
1031
            p->released_buffers = tmp;
1032
        }
1033
1034
        if (!tmp || !tmp[p->released_buffers_allocated]) {
1035
            ret = AVERROR(ENOMEM);
1036
            goto fail;
1037
        }
1038
        p->released_buffers_allocated++;
1039
    }
1040
1041
    dst = p->released_buffers[p->num_released_buffers];
1042
    av_frame_move_ref(dst, f->f);
1043
1044
    p->num_released_buffers++;
1045
1046
fail:
1047
    pthread_mutex_unlock(&fctx->buffer_mutex);
1048
1049
    // make sure the frame is clean even if we fail to free it
1050
    // this leaks, but it is better than crashing
1051
    if (ret < 0) {
1052
        av_log(avctx, AV_LOG_ERROR, "Could not queue a frame for freeing, this will leak\n");
1053
        memset(f->f->buf, 0, sizeof(f->f->buf));
1054
        if (f->f->extended_buf)
1055
            memset(f->f->extended_buf, 0, f->f->nb_extended_buf * sizeof(*f->f->extended_buf));
1056
        av_frame_unref(f->f);
1057
    }
1058
}