~ubuntu-branches/ubuntu/oneiric/mplayer2/oneiric-proposed

« back to all changes in this revision

Viewing changes to ffmpeg-mt/libavcodec/pthread.c

  • Committer: Bazaar Package Importer
  • Author(s): Reinhard Tartler
  • Date: 2011-03-20 22:48:03 UTC
  • Revision ID: james.westby@ubuntu.com-20110320224803-kc2nlrxz6pcphmf1
Tags: upstream-2.0~rc2
ImportĀ upstreamĀ versionĀ 2.0~rc2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * Copyright (c) 2004 Roman Shaposhnik
 
3
 * Copyright (c) 2008 Alexander Strange (astrange@ithinksw.com)
 
4
 *
 
5
 * Many thanks to Steven M. Schultz for providing clever ideas and
 
6
 * to Michael Niedermayer <michaelni@gmx.at> for writing initial
 
7
 * implementation.
 
8
 *
 
9
 * This file is part of FFmpeg.
 
10
 *
 
11
 * FFmpeg is free software; you can redistribute it and/or
 
12
 * modify it under the terms of the GNU Lesser General Public
 
13
 * License as published by the Free Software Foundation; either
 
14
 * version 2.1 of the License, or (at your option) any later version.
 
15
 *
 
16
 * FFmpeg is distributed in the hope that it will be useful,
 
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 
19
 * Lesser General Public License for more details.
 
20
 *
 
21
 * You should have received a copy of the GNU Lesser General Public
 
22
 * License along with FFmpeg; if not, write to the Free Software
 
23
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
24
 */
 
25
 
 
26
/**
 
27
 * @file
 
28
 * Multithreading support functions
 
29
 * @see doc/multithreading.txt
 
30
 */
 
31
 
 
32
#include <pthread.h>
 
33
 
 
34
#include "avcodec.h"
 
35
#include "thread.h"
 
36
 
 
37
typedef int (action_func)(AVCodecContext *c, void *arg);
 
38
typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
 
39
 
 
40
typedef struct ThreadContext {
 
41
    pthread_t *workers;
 
42
    action_func *func;
 
43
    action_func2 *func2;
 
44
    void *args;
 
45
    int *rets;
 
46
    int rets_count;
 
47
    int job_count;
 
48
    int job_size;
 
49
 
 
50
    pthread_cond_t last_job_cond;
 
51
    pthread_cond_t current_job_cond;
 
52
    pthread_mutex_t current_job_lock;
 
53
    int current_job;
 
54
    int done;
 
55
} ThreadContext;
 
56
 
 
57
/// Max number of frame buffers that can be allocated when using frame threads.
 
58
#define MAX_BUFFERS 32
 
59
 
 
60
/**
 
61
 * Context used by codec threads and stored in their AVCodecContext thread_opaque.
 
62
 */
 
63
typedef struct PerThreadContext {
 
64
    struct FrameThreadContext *parent;
 
65
 
 
66
    pthread_t      thread;
 
67
    pthread_cond_t input_cond;      ///< Used to wait for a new frame from the main thread.
 
68
    pthread_cond_t progress_cond;   ///< Used by child threads to wait for progress to change.
 
69
    pthread_cond_t output_cond;     ///< Used by the main thread to wait for frames to finish.
 
70
 
 
71
    pthread_mutex_t mutex;          ///< Mutex used to protect the contents of the PerThreadContext.
 
72
    pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
 
73
 
 
74
    AVCodecContext *avctx;          ///< Context used to decode frames passed to this thread.
 
75
 
 
76
    AVPacket       avpkt;           ///< Input frame (for decoding) or output (for encoding).
 
77
    int            allocated_buf_size; ///< Size allocated for avpkt.data
 
78
 
 
79
    AVFrame picture;                ///< Output picture (for decoding) or input (for encoding).
 
80
    int     got_picture;            ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
 
81
    int     result;                 ///< The result of the last codec decode/encode() call.
 
82
 
 
83
    enum {
 
84
        STATE_INPUT_READY,          ///< Set when the thread is awaiting a frame.
 
85
        STATE_SETTING_UP,           ///< Set before the codec has called ff_thread_finish_setup().
 
86
        STATE_GET_BUFFER,           /**
 
87
                                     * Set when the codec calls get_buffer().
 
88
                                     * State is returned to STATE_SETTING_UP afterwards.
 
89
                                     */
 
90
        STATE_SETUP_FINISHED        ///< Set after the codec has called ff_thread_finish_setup().
 
91
    } state;
 
92
 
 
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[MAX_BUFFERS];
 
98
    int     num_released_buffers;
 
99
 
 
100
    /**
 
101
     * Array of progress values used by ff_thread_get_buffer().
 
102
     */
 
103
    int     progress[MAX_BUFFERS][2];
 
104
    uint8_t progress_used[MAX_BUFFERS];
 
105
 
 
106
    AVFrame *requested_frame;       ///< AVFrame the codec passed to get_buffer()
 
107
} PerThreadContext;
 
108
 
 
109
/**
 
110
 * Context stored in the client AVCodecContext thread_opaque.
 
111
 */
 
112
typedef struct FrameThreadContext {
 
113
    PerThreadContext *threads;     ///< The contexts for each thread.
 
114
    PerThreadContext *prev_thread; ///< The last thread submit_frame() was called on.
 
115
 
 
116
    pthread_mutex_t buffer_mutex;  ///< Mutex used to protect get/release_buffer().
 
117
 
 
118
    int next_decoding;             ///< The next context to submit a frame to.
 
119
    int next_finished;             ///< The next context to return output from.
 
120
 
 
121
    int delaying;                  /**
 
122
                                    * Set for the first N frames, where N is the number of threads.
 
123
                                    * While it is set, ff_en/decode_frame_threaded won't return any results.
 
124
                                    */
 
125
 
 
126
    int die;                       ///< Set when threads should exit.
 
127
} FrameThreadContext;
 
128
 
 
129
static void* attribute_align_arg worker(void *v)
 
130
{
 
131
    AVCodecContext *avctx = v;
 
132
    ThreadContext *c = avctx->thread_opaque;
 
133
    int our_job = c->job_count;
 
134
    int thread_count = avctx->thread_count;
 
135
    int self_id;
 
136
 
 
137
    pthread_mutex_lock(&c->current_job_lock);
 
138
    self_id = c->current_job++;
 
139
    for (;;){
 
140
        while (our_job >= c->job_count) {
 
141
            if (c->current_job == thread_count + c->job_count)
 
142
                pthread_cond_signal(&c->last_job_cond);
 
143
 
 
144
            pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
 
145
            our_job = self_id;
 
146
 
 
147
            if (c->done) {
 
148
                pthread_mutex_unlock(&c->current_job_lock);
 
149
                return NULL;
 
150
            }
 
151
        }
 
152
        pthread_mutex_unlock(&c->current_job_lock);
 
153
 
 
154
        c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
 
155
                                                   c->func2(avctx, c->args, our_job, self_id);
 
156
 
 
157
        pthread_mutex_lock(&c->current_job_lock);
 
158
        our_job = c->current_job++;
 
159
    }
 
160
}
 
161
 
 
162
static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
 
163
{
 
164
    pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
 
165
    pthread_mutex_unlock(&c->current_job_lock);
 
166
}
 
167
 
 
168
static void thread_free(AVCodecContext *avctx)
 
169
{
 
170
    ThreadContext *c = avctx->thread_opaque;
 
171
    int i;
 
172
 
 
173
    pthread_mutex_lock(&c->current_job_lock);
 
174
    c->done = 1;
 
175
    pthread_cond_broadcast(&c->current_job_cond);
 
176
    pthread_mutex_unlock(&c->current_job_lock);
 
177
 
 
178
    for (i=0; i<avctx->thread_count; i++)
 
179
         pthread_join(c->workers[i], NULL);
 
180
 
 
181
    pthread_mutex_destroy(&c->current_job_lock);
 
182
    pthread_cond_destroy(&c->current_job_cond);
 
183
    pthread_cond_destroy(&c->last_job_cond);
 
184
    av_free(c->workers);
 
185
    av_freep(&avctx->thread_opaque);
 
186
}
 
187
 
 
188
static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
 
189
{
 
190
    ThreadContext *c= avctx->thread_opaque;
 
191
    int dummy_ret;
 
192
 
 
193
    if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
 
194
        return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
 
195
 
 
196
    if (job_count <= 0)
 
197
        return 0;
 
198
 
 
199
    pthread_mutex_lock(&c->current_job_lock);
 
200
 
 
201
    c->current_job = avctx->thread_count;
 
202
    c->job_count = job_count;
 
203
    c->job_size = job_size;
 
204
    c->args = arg;
 
205
    c->func = func;
 
206
    if (ret) {
 
207
        c->rets = ret;
 
208
        c->rets_count = job_count;
 
209
    } else {
 
210
        c->rets = &dummy_ret;
 
211
        c->rets_count = 1;
 
212
    }
 
213
    pthread_cond_broadcast(&c->current_job_cond);
 
214
 
 
215
    avcodec_thread_park_workers(c, avctx->thread_count);
 
216
 
 
217
    return 0;
 
218
}
 
219
 
 
220
static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
 
221
{
 
222
    ThreadContext *c= avctx->thread_opaque;
 
223
    c->func2 = func2;
 
224
    return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
 
225
}
 
226
 
 
227
static int thread_init(AVCodecContext *avctx)
 
228
{
 
229
    int i;
 
230
    ThreadContext *c;
 
231
    int thread_count = avctx->thread_count;
 
232
 
 
233
    avctx->thread_count = thread_count;
 
234
 
 
235
    if (thread_count <= 1)
 
236
        return 0;
 
237
 
 
238
    c = av_mallocz(sizeof(ThreadContext));
 
239
    if (!c)
 
240
        return -1;
 
241
 
 
242
    c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
 
243
    if (!c->workers) {
 
244
        av_free(c);
 
245
        return -1;
 
246
    }
 
247
 
 
248
    avctx->thread_opaque = c;
 
249
    c->current_job = 0;
 
250
    c->job_count = 0;
 
251
    c->job_size = 0;
 
252
    c->done = 0;
 
253
    pthread_cond_init(&c->current_job_cond, NULL);
 
254
    pthread_cond_init(&c->last_job_cond, NULL);
 
255
    pthread_mutex_init(&c->current_job_lock, NULL);
 
256
    pthread_mutex_lock(&c->current_job_lock);
 
257
    for (i=0; i<thread_count; i++) {
 
258
        if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
 
259
           avctx->thread_count = i;
 
260
           pthread_mutex_unlock(&c->current_job_lock);
 
261
           avcodec_thread_free(avctx);
 
262
           return -1;
 
263
        }
 
264
    }
 
265
 
 
266
    avcodec_thread_park_workers(c, thread_count);
 
267
 
 
268
    avctx->execute = avcodec_thread_execute;
 
269
    avctx->execute2 = avcodec_thread_execute2;
 
270
    return 0;
 
271
}
 
272
 
 
273
/**
 
274
 * Codec worker thread.
 
275
 *
 
276
 * Automatically calls ff_thread_finish_setup() if the codec does
 
277
 * not provide an update_thread_context method, or if the codec returns
 
278
 * before calling it.
 
279
 */
 
280
static attribute_align_arg void *frame_worker_thread(void *arg)
 
281
{
 
282
    PerThreadContext *p = arg;
 
283
    FrameThreadContext *fctx = p->parent;
 
284
    AVCodecContext *avctx = p->avctx;
 
285
    AVCodec *codec = avctx->codec;
 
286
 
 
287
    while (1) {
 
288
        if (p->state == STATE_INPUT_READY && !fctx->die) {
 
289
            pthread_mutex_lock(&p->mutex);
 
290
            while (p->state == STATE_INPUT_READY && !fctx->die)
 
291
                pthread_cond_wait(&p->input_cond, &p->mutex);
 
292
            pthread_mutex_unlock(&p->mutex);
 
293
        }
 
294
 
 
295
        if (fctx->die) break;
 
296
 
 
297
        if (!codec->update_thread_context) ff_thread_finish_setup(avctx);
 
298
 
 
299
        pthread_mutex_lock(&p->mutex);
 
300
        avcodec_get_frame_defaults(&p->picture);
 
301
        p->got_picture = 0;
 
302
        p->result = codec->decode(avctx, &p->picture, &p->got_picture, &p->avpkt);
 
303
 
 
304
        if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
 
305
 
 
306
        p->state = STATE_INPUT_READY;
 
307
 
 
308
        pthread_mutex_lock(&p->progress_mutex);
 
309
        pthread_cond_signal(&p->output_cond);
 
310
        pthread_mutex_unlock(&p->progress_mutex);
 
311
 
 
312
        pthread_mutex_unlock(&p->mutex);
 
313
    }
 
314
 
 
315
    return NULL;
 
316
}
 
317
 
 
318
/**
 
319
 * Updates the next thread's AVCodecContext with values from the reference thread's context.
 
320
 *
 
321
 * @param dst The destination context.
 
322
 * @param src The source context.
 
323
 * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
 
324
 */
 
325
static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
 
326
{
 
327
    int err = 0;
 
328
 
 
329
    if (dst != src) {
 
330
        dst->sub_id    = src->sub_id;
 
331
        dst->time_base = src->time_base;
 
332
        dst->width     = src->width;
 
333
        dst->height    = src->height;
 
334
        dst->pix_fmt   = src->pix_fmt;
 
335
 
 
336
        dst->has_b_frames = src->has_b_frames;
 
337
        dst->idct_algo    = src->idct_algo;
 
338
        dst->slice_count  = src->slice_count;
 
339
 
 
340
        dst->bits_per_coded_sample = src->bits_per_coded_sample;
 
341
        dst->sample_aspect_ratio   = src->sample_aspect_ratio;
 
342
        dst->dtg_active_format     = src->dtg_active_format;
 
343
 
 
344
        dst->profile = src->profile;
 
345
        dst->level   = src->level;
 
346
 
 
347
        dst->bits_per_raw_sample = src->bits_per_raw_sample;
 
348
        dst->ticks_per_frame     = src->ticks_per_frame;
 
349
        dst->color_primaries     = src->color_primaries;
 
350
 
 
351
        dst->color_trc   = src->color_trc;
 
352
        dst->colorspace  = src->colorspace;
 
353
        dst->color_range = src->color_range;
 
354
        dst->chroma_sample_location = src->chroma_sample_location;
 
355
    }
 
356
 
 
357
    if (for_user) {
 
358
        dst->coded_frame   = src->coded_frame;
 
359
        dst->has_b_frames += src->thread_count - 1;
 
360
    } else {
 
361
        if (dst->codec->update_thread_context)
 
362
            err = dst->codec->update_thread_context(dst, src);
 
363
    }
 
364
 
 
365
    return err;
 
366
}
 
367
 
 
368
/**
 
369
 * Update the next thread's AVCodecContext with values set by the user.
 
370
 *
 
371
 * @param dst The destination context.
 
372
 * @param src The source context.
 
373
 */
 
374
static void update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
 
375
{
 
376
#define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
 
377
    dst->flags          = src->flags;
 
378
 
 
379
    dst->draw_horiz_band= src->draw_horiz_band;
 
380
    dst->get_buffer     = src->get_buffer;
 
381
    dst->release_buffer = src->release_buffer;
 
382
 
 
383
    dst->opaque   = src->opaque;
 
384
    dst->hurry_up = src->hurry_up;
 
385
    dst->dsp_mask = src->dsp_mask;
 
386
    dst->debug    = src->debug;
 
387
    dst->debug_mv = src->debug_mv;
 
388
 
 
389
    dst->slice_flags = src->slice_flags;
 
390
    dst->flags2      = src->flags2;
 
391
 
 
392
    copy_fields(skip_loop_filter, bidir_refine);
 
393
 
 
394
    dst->frame_number     = src->frame_number;
 
395
    dst->reordered_opaque = src->reordered_opaque;
 
396
#undef copy_fields
 
397
}
 
398
 
 
399
static void free_progress(AVFrame *f)
 
400
{
 
401
    PerThreadContext *p = f->owner->thread_opaque;
 
402
    int *progress = f->thread_opaque;
 
403
 
 
404
    p->progress_used[(progress - p->progress[0]) / 2] = 0;
 
405
}
 
406
 
 
407
/// Releases the buffers that this decoding thread was the last user of.
 
408
static void release_delayed_buffers(PerThreadContext *p)
 
409
{
 
410
    FrameThreadContext *fctx = p->parent;
 
411
 
 
412
    while (p->num_released_buffers > 0) {
 
413
        AVFrame *f = &p->released_buffers[--p->num_released_buffers];
 
414
 
 
415
        pthread_mutex_lock(&fctx->buffer_mutex);
 
416
        free_progress(f);
 
417
        f->thread_opaque = NULL;
 
418
 
 
419
        f->owner->release_buffer(f->owner, f);
 
420
        pthread_mutex_unlock(&fctx->buffer_mutex);
 
421
    }
 
422
}
 
423
 
 
424
static int submit_frame(PerThreadContext *p, AVPacket *avpkt)
 
425
{
 
426
    FrameThreadContext *fctx = p->parent;
 
427
    PerThreadContext *prev_thread = fctx->prev_thread;
 
428
    AVCodec *codec = p->avctx->codec;
 
429
    uint8_t *buf = p->avpkt.data;
 
430
 
 
431
    if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
 
432
 
 
433
    pthread_mutex_lock(&p->mutex);
 
434
 
 
435
    release_delayed_buffers(p);
 
436
 
 
437
    if (prev_thread) {
 
438
        int err;
 
439
        if (prev_thread->state == STATE_SETTING_UP) {
 
440
            pthread_mutex_lock(&prev_thread->progress_mutex);
 
441
            while (prev_thread->state == STATE_SETTING_UP)
 
442
                pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
 
443
            pthread_mutex_unlock(&prev_thread->progress_mutex);
 
444
        }
 
445
 
 
446
        err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
 
447
        if (err) {
 
448
            pthread_mutex_unlock(&p->mutex);
 
449
            return err;
 
450
        }
 
451
    }
 
452
 
 
453
    av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
 
454
    p->avpkt = *avpkt;
 
455
    p->avpkt.data = buf;
 
456
    memcpy(buf, avpkt->data, avpkt->size);
 
457
    memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
 
458
 
 
459
    p->state = STATE_SETTING_UP;
 
460
    pthread_cond_signal(&p->input_cond);
 
461
    pthread_mutex_unlock(&p->mutex);
 
462
 
 
463
    /*
 
464
     * If the client doesn't have a thread-safe get_buffer(),
 
465
     * then decoding threads call back to the main thread,
 
466
     * and it calls back to the client here.
 
467
     */
 
468
 
 
469
    if (!p->avctx->thread_safe_callbacks &&
 
470
         p->avctx->get_buffer != avcodec_default_get_buffer) {
 
471
        while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
 
472
            pthread_mutex_lock(&p->progress_mutex);
 
473
            while (p->state == STATE_SETTING_UP)
 
474
                pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
 
475
 
 
476
            if (p->state == STATE_GET_BUFFER) {
 
477
                p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
 
478
                p->state  = STATE_SETTING_UP;
 
479
                pthread_cond_signal(&p->progress_cond);
 
480
            }
 
481
            pthread_mutex_unlock(&p->progress_mutex);
 
482
        }
 
483
    }
 
484
 
 
485
    fctx->prev_thread = p;
 
486
 
 
487
    return 0;
 
488
}
 
489
 
 
490
int ff_thread_decode_frame(AVCodecContext *avctx,
 
491
                           AVFrame *picture, int *got_picture_ptr,
 
492
                           AVPacket *avpkt)
 
493
{
 
494
    FrameThreadContext *fctx = avctx->thread_opaque;
 
495
    int finished = fctx->next_finished;
 
496
    PerThreadContext *p;
 
497
    int err;
 
498
 
 
499
    /*
 
500
     * Submit a frame to the next decoding thread.
 
501
     */
 
502
 
 
503
    p = &fctx->threads[fctx->next_decoding];
 
504
    update_context_from_user(p->avctx, avctx);
 
505
    err = submit_frame(p, avpkt);
 
506
    if (err) return err;
 
507
 
 
508
    fctx->next_decoding++;
 
509
 
 
510
    /*
 
511
     * If we're still receiving the initial frames, don't return a picture.
 
512
     */
 
513
 
 
514
    if (fctx->delaying && avpkt->size) {
 
515
        if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
 
516
 
 
517
        *got_picture_ptr=0;
 
518
        return 0;
 
519
    }
 
520
 
 
521
    /*
 
522
     * Return the next available picture from the oldest thread.
 
523
     * If we're at the end of the stream, then we have to skip threads that
 
524
     * didn't output a picture, because we don't want to accidentally signal
 
525
     * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
 
526
     */
 
527
 
 
528
    do {
 
529
        p = &fctx->threads[finished++];
 
530
 
 
531
        if (p->state != STATE_INPUT_READY) {
 
532
            pthread_mutex_lock(&p->progress_mutex);
 
533
            while (p->state != STATE_INPUT_READY)
 
534
                pthread_cond_wait(&p->output_cond, &p->progress_mutex);
 
535
            pthread_mutex_unlock(&p->progress_mutex);
 
536
        }
 
537
 
 
538
        *picture = p->picture;
 
539
        *got_picture_ptr = p->got_picture;
 
540
        picture->pkt_dts = p->avpkt.dts;
 
541
 
 
542
        /*
 
543
         * A later call with avkpt->size == 0 may loop over all threads,
 
544
         * including this one, searching for a frame to return before being
 
545
         * stopped by the "finished != fctx->next_finished" condition.
 
546
         * Make sure we don't mistakenly return the same frame again.
 
547
         */
 
548
        p->got_picture = 0;
 
549
 
 
550
        if (finished >= avctx->thread_count) finished = 0;
 
551
    } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
 
552
 
 
553
    update_context_from_thread(avctx, p->avctx, 1);
 
554
 
 
555
    if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
 
556
 
 
557
    fctx->next_finished = finished;
 
558
 
 
559
    return p->result;
 
560
}
 
561
 
 
562
void ff_thread_report_progress(AVFrame *f, int n, int field)
 
563
{
 
564
    PerThreadContext *p;
 
565
    int *progress = f->thread_opaque;
 
566
 
 
567
    if (!progress || progress[field] >= n) return;
 
568
 
 
569
    p = f->owner->thread_opaque;
 
570
 
 
571
    if (f->owner->debug&FF_DEBUG_THREADS)
 
572
        av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
 
573
 
 
574
    pthread_mutex_lock(&p->progress_mutex);
 
575
    progress[field] = n;
 
576
    pthread_cond_broadcast(&p->progress_cond);
 
577
    pthread_mutex_unlock(&p->progress_mutex);
 
578
}
 
579
 
 
580
void ff_thread_await_progress(AVFrame *f, int n, int field)
 
581
{
 
582
    PerThreadContext *p;
 
583
    int *progress = f->thread_opaque;
 
584
 
 
585
    if (!progress || progress[field] >= n) return;
 
586
 
 
587
    p = f->owner->thread_opaque;
 
588
 
 
589
    if (f->owner->debug&FF_DEBUG_THREADS)
 
590
        av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
 
591
 
 
592
    pthread_mutex_lock(&p->progress_mutex);
 
593
    while (progress[field] < n)
 
594
        pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
 
595
    pthread_mutex_unlock(&p->progress_mutex);
 
596
}
 
597
 
 
598
void ff_thread_finish_setup(AVCodecContext *avctx) {
 
599
    PerThreadContext *p = avctx->thread_opaque;
 
600
 
 
601
    if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
 
602
 
 
603
    pthread_mutex_lock(&p->progress_mutex);
 
604
    p->state = STATE_SETUP_FINISHED;
 
605
    pthread_cond_broadcast(&p->progress_cond);
 
606
    pthread_mutex_unlock(&p->progress_mutex);
 
607
}
 
608
 
 
609
/// Waits for all threads to finish.
 
610
static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
 
611
{
 
612
    int i;
 
613
 
 
614
    for (i = 0; i < thread_count; i++) {
 
615
        PerThreadContext *p = &fctx->threads[i];
 
616
 
 
617
        if (p->state != STATE_INPUT_READY) {
 
618
            pthread_mutex_lock(&p->progress_mutex);
 
619
            while (p->state != STATE_INPUT_READY)
 
620
                pthread_cond_wait(&p->output_cond, &p->progress_mutex);
 
621
            pthread_mutex_unlock(&p->progress_mutex);
 
622
        }
 
623
    }
 
624
}
 
625
 
 
626
static void frame_thread_free(AVCodecContext *avctx, int thread_count)
 
627
{
 
628
    FrameThreadContext *fctx = avctx->thread_opaque;
 
629
    AVCodec *codec = avctx->codec;
 
630
    int i;
 
631
 
 
632
    park_frame_worker_threads(fctx, thread_count);
 
633
 
 
634
    if (fctx->prev_thread)
 
635
        update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
 
636
 
 
637
    fctx->die = 1;
 
638
 
 
639
    for (i = 0; i < thread_count; i++) {
 
640
        PerThreadContext *p = &fctx->threads[i];
 
641
 
 
642
        pthread_mutex_lock(&p->mutex);
 
643
        pthread_cond_signal(&p->input_cond);
 
644
        pthread_mutex_unlock(&p->mutex);
 
645
 
 
646
        pthread_join(p->thread, NULL);
 
647
 
 
648
        if (codec->close)
 
649
            codec->close(p->avctx);
 
650
 
 
651
        avctx->codec = NULL;
 
652
 
 
653
        release_delayed_buffers(p);
 
654
    }
 
655
 
 
656
    for (i = 0; i < thread_count; i++) {
 
657
        PerThreadContext *p = &fctx->threads[i];
 
658
 
 
659
        avcodec_default_free_buffers(p->avctx);
 
660
 
 
661
        pthread_mutex_destroy(&p->mutex);
 
662
        pthread_mutex_destroy(&p->progress_mutex);
 
663
        pthread_cond_destroy(&p->input_cond);
 
664
        pthread_cond_destroy(&p->progress_cond);
 
665
        pthread_cond_destroy(&p->output_cond);
 
666
        av_freep(&p->avpkt.data);
 
667
 
 
668
        if (i)
 
669
            av_freep(&p->avctx->priv_data);
 
670
 
 
671
        av_freep(&p->avctx);
 
672
    }
 
673
 
 
674
    av_freep(&fctx->threads);
 
675
    pthread_mutex_destroy(&fctx->buffer_mutex);
 
676
    av_freep(&avctx->thread_opaque);
 
677
}
 
678
 
 
679
static int frame_thread_init(AVCodecContext *avctx)
 
680
{
 
681
    int thread_count = avctx->thread_count;
 
682
    AVCodec *codec = avctx->codec;
 
683
    AVCodecContext *src = avctx;
 
684
    FrameThreadContext *fctx;
 
685
    int i, err = 0;
 
686
 
 
687
    avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
 
688
 
 
689
    fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
 
690
    pthread_mutex_init(&fctx->buffer_mutex, NULL);
 
691
    fctx->delaying = 1;
 
692
 
 
693
    for (i = 0; i < thread_count; i++) {
 
694
        AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
 
695
        PerThreadContext *p  = &fctx->threads[i];
 
696
 
 
697
        pthread_mutex_init(&p->mutex, NULL);
 
698
        pthread_mutex_init(&p->progress_mutex, NULL);
 
699
        pthread_cond_init(&p->input_cond, NULL);
 
700
        pthread_cond_init(&p->progress_cond, NULL);
 
701
        pthread_cond_init(&p->output_cond, NULL);
 
702
 
 
703
        p->parent = fctx;
 
704
        p->avctx  = copy;
 
705
 
 
706
        *copy = *src;
 
707
        copy->thread_opaque = p;
 
708
        copy->pkt = &p->avpkt;
 
709
 
 
710
        if (!i) {
 
711
            src = copy;
 
712
 
 
713
            if (codec->init)
 
714
                err = codec->init(copy);
 
715
 
 
716
            update_context_from_thread(avctx, copy, 1);
 
717
        } else {
 
718
            copy->is_copy   = 1;
 
719
            copy->priv_data = av_malloc(codec->priv_data_size);
 
720
            memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
 
721
 
 
722
            if (codec->init_thread_copy)
 
723
                err = codec->init_thread_copy(copy);
 
724
        }
 
725
 
 
726
        if (err) goto error;
 
727
 
 
728
        pthread_create(&p->thread, NULL, frame_worker_thread, p);
 
729
    }
 
730
 
 
731
    return 0;
 
732
 
 
733
error:
 
734
    frame_thread_free(avctx, i+1);
 
735
 
 
736
    return err;
 
737
}
 
738
 
 
739
void ff_thread_flush(AVCodecContext *avctx)
 
740
{
 
741
    FrameThreadContext *fctx = avctx->thread_opaque;
 
742
 
 
743
    if (!avctx->thread_opaque) return;
 
744
 
 
745
    park_frame_worker_threads(fctx, avctx->thread_count);
 
746
 
 
747
    if (fctx->prev_thread)
 
748
        update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
 
749
 
 
750
    fctx->next_decoding = fctx->next_finished = 0;
 
751
    fctx->delaying = 1;
 
752
    fctx->prev_thread = NULL;
 
753
}
 
754
 
 
755
static int *allocate_progress(PerThreadContext *p)
 
756
{
 
757
    int i;
 
758
 
 
759
    for (i = 0; i < MAX_BUFFERS; i++)
 
760
        if (!p->progress_used[i]) break;
 
761
 
 
762
    if (i == MAX_BUFFERS) {
 
763
        av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
 
764
        return NULL;
 
765
    }
 
766
 
 
767
    p->progress_used[i] = 1;
 
768
 
 
769
    return p->progress[i];
 
770
}
 
771
 
 
772
int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
 
773
{
 
774
    PerThreadContext *p = avctx->thread_opaque;
 
775
    int *progress, err;
 
776
 
 
777
    f->owner = avctx;
 
778
 
 
779
    if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
 
780
        f->thread_opaque = NULL;
 
781
        return avctx->get_buffer(avctx, f);
 
782
    }
 
783
 
 
784
    if (p->state != STATE_SETTING_UP) {
 
785
        av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
 
786
        return -1;
 
787
    }
 
788
 
 
789
    pthread_mutex_lock(&p->parent->buffer_mutex);
 
790
    f->thread_opaque = progress = allocate_progress(p);
 
791
 
 
792
    if (!progress) {
 
793
        pthread_mutex_unlock(&p->parent->buffer_mutex);
 
794
        return -1;
 
795
    }
 
796
 
 
797
    progress[0] =
 
798
    progress[1] = -1;
 
799
 
 
800
    if (avctx->thread_safe_callbacks ||
 
801
        avctx->get_buffer == avcodec_default_get_buffer) {
 
802
        err = avctx->get_buffer(avctx, f);
 
803
    } else {
 
804
        p->requested_frame = f;
 
805
        p->state = STATE_GET_BUFFER;
 
806
        pthread_mutex_lock(&p->progress_mutex);
 
807
        pthread_cond_signal(&p->progress_cond);
 
808
 
 
809
        while (p->state != STATE_SETTING_UP)
 
810
            pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
 
811
 
 
812
        err = p->result;
 
813
 
 
814
        pthread_mutex_unlock(&p->progress_mutex);
 
815
    }
 
816
 
 
817
    pthread_mutex_unlock(&p->parent->buffer_mutex);
 
818
 
 
819
    /*
 
820
     * Buffer age is difficult to keep track of between
 
821
     * multiple threads, and the optimizations it allows
 
822
     * are not worth the effort. It is disabled for now.
 
823
     */
 
824
    f->age = INT_MAX;
 
825
 
 
826
    return err;
 
827
}
 
828
 
 
829
void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
 
830
{
 
831
    PerThreadContext *p = avctx->thread_opaque;
 
832
 
 
833
    if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
 
834
        avctx->release_buffer(avctx, f);
 
835
        return;
 
836
    }
 
837
 
 
838
    if (p->num_released_buffers >= MAX_BUFFERS) {
 
839
        av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
 
840
        return;
 
841
    }
 
842
 
 
843
    if(avctx->debug & FF_DEBUG_BUFFERS)
 
844
        av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p, %d buffers used\n",
 
845
                                    f, f->owner->internal_buffer_count);
 
846
 
 
847
    p->released_buffers[p->num_released_buffers++] = *f;
 
848
    memset(f->data, 0, sizeof(f->data));
 
849
}
 
850
 
 
851
/**
 
852
 * Set the threading algorithms used.
 
853
 *
 
854
 * Threading requires more than one thread.
 
855
 * Frame threading requires entire frames to be passed to the codec,
 
856
 * and introduces extra decoding delay, so is incompatible with low_delay.
 
857
 *
 
858
 * @param avctx The context.
 
859
 */
 
860
static void validate_thread_parameters(AVCodecContext *avctx)
 
861
{
 
862
    int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
 
863
                                && !(avctx->flags & CODEC_FLAG_TRUNCATED)
 
864
                                && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
 
865
                                && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
 
866
    if (avctx->thread_count == 1) {
 
867
        avctx->active_thread_type = 0;
 
868
    } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
 
869
        avctx->active_thread_type = FF_THREAD_FRAME;
 
870
    } else {
 
871
        avctx->active_thread_type = FF_THREAD_SLICE;
 
872
    }
 
873
}
 
874
 
 
875
int avcodec_thread_init(AVCodecContext *avctx, int thread_count)
 
876
{
 
877
    if (avctx->thread_opaque) {
 
878
        av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
 
879
        return -1;
 
880
    }
 
881
 
 
882
    avctx->thread_count = FFMAX(1, thread_count);
 
883
 
 
884
    if (avctx->codec) {
 
885
        validate_thread_parameters(avctx);
 
886
 
 
887
        if (avctx->active_thread_type&FF_THREAD_SLICE)
 
888
            return thread_init(avctx);
 
889
        else if (avctx->active_thread_type&FF_THREAD_FRAME)
 
890
            return frame_thread_init(avctx);
 
891
    }
 
892
 
 
893
    return 0;
 
894
}
 
895
 
 
896
void avcodec_thread_free(AVCodecContext *avctx)
 
897
{
 
898
    if (avctx->active_thread_type&FF_THREAD_FRAME)
 
899
        frame_thread_free(avctx, avctx->thread_count);
 
900
    else
 
901
        thread_free(avctx);
 
902
}