GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/diracdec.c Lines: 906 1176 77.0 %
Date: 2019-11-22 03:34:36 Branches: 568 855 66.4 %

Line Branch Exec Source
1
/*
2
 * Copyright (C) 2007 Marco Gerards <marco@gnu.org>
3
 * Copyright (C) 2009 David Conrad
4
 * Copyright (C) 2011 Jordi Ortiz
5
 *
6
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with FFmpeg; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
 */
22
23
/**
24
 * @file
25
 * Dirac Decoder
26
 * @author Marco Gerards <marco@gnu.org>, David Conrad, Jordi Ortiz <nenjordi@gmail.com>
27
 */
28
29
#include "libavutil/pixdesc.h"
30
#include "libavutil/thread.h"
31
#include "avcodec.h"
32
#include "get_bits.h"
33
#include "bytestream.h"
34
#include "internal.h"
35
#include "golomb.h"
36
#include "dirac_arith.h"
37
#include "dirac_vlc.h"
38
#include "mpeg12data.h"
39
#include "libavcodec/mpegvideo.h"
40
#include "mpegvideoencdsp.h"
41
#include "dirac_dwt.h"
42
#include "dirac.h"
43
#include "diractab.h"
44
#include "diracdsp.h"
45
#include "videodsp.h"
46
47
/**
48
 * The spec limits this to 3 for frame coding, but in practice can be as high as 6
49
 */
50
#define MAX_REFERENCE_FRAMES 8
51
#define MAX_DELAY 5         /* limit for main profile for frame coding (TODO: field coding) */
52
#define MAX_FRAMES (MAX_REFERENCE_FRAMES + MAX_DELAY + 1)
53
#define MAX_QUANT 255        /* max quant for VC-2 */
54
#define MAX_BLOCKSIZE 32    /* maximum xblen/yblen we support */
55
56
/**
57
 * DiracBlock->ref flags, if set then the block does MC from the given ref
58
 */
59
#define DIRAC_REF_MASK_REF1   1
60
#define DIRAC_REF_MASK_REF2   2
61
#define DIRAC_REF_MASK_GLOBAL 4
62
63
/**
64
 * Value of Picture.reference when Picture is not a reference picture, but
65
 * is held for delayed output.
66
 */
67
#define DELAYED_PIC_REF 4
68
69
#define CALC_PADDING(size, depth)                       \
70
    (((size + (1 << depth) - 1) >> depth) << depth)
71
72
#define DIVRNDUP(a, b) (((a) + (b) - 1) / (b))
73
74
typedef struct {
75
    AVFrame *avframe;
76
    int interpolated[3];    /* 1 if hpel[] is valid */
77
    uint8_t *hpel[3][4];
78
    uint8_t *hpel_base[3][4];
79
    int reference;
80
} DiracFrame;
81
82
typedef struct {
83
    union {
84
        int16_t mv[2][2];
85
        int16_t dc[3];
86
    } u; /* anonymous unions aren't in C99 :( */
87
    uint8_t ref;
88
} DiracBlock;
89
90
typedef struct SubBand {
91
    int level;
92
    int orientation;
93
    int stride; /* in bytes */
94
    int width;
95
    int height;
96
    int pshift;
97
    int quant;
98
    uint8_t *ibuf;
99
    struct SubBand *parent;
100
101
    /* for low delay */
102
    unsigned length;
103
    const uint8_t *coeff_data;
104
} SubBand;
105
106
typedef struct Plane {
107
    DWTPlane idwt;
108
109
    int width;
110
    int height;
111
    ptrdiff_t stride;
112
113
    /* block length */
114
    uint8_t xblen;
115
    uint8_t yblen;
116
    /* block separation (block n+1 starts after this many pixels in block n) */
117
    uint8_t xbsep;
118
    uint8_t ybsep;
119
    /* amount of overspill on each edge (half of the overlap between blocks) */
120
    uint8_t xoffset;
121
    uint8_t yoffset;
122
123
    SubBand band[MAX_DWT_LEVELS][4];
124
} Plane;
125
126
/* Used by Low Delay and High Quality profiles */
127
typedef struct DiracSlice {
128
    GetBitContext gb;
129
    int slice_x;
130
    int slice_y;
131
    int bytes;
132
} DiracSlice;
133
134
typedef struct DiracContext {
135
    AVCodecContext *avctx;
136
    MpegvideoEncDSPContext mpvencdsp;
137
    VideoDSPContext vdsp;
138
    DiracDSPContext diracdsp;
139
    DiracGolombLUT *reader_ctx;
140
    DiracVersionInfo version;
141
    GetBitContext gb;
142
    AVDiracSeqHeader seq;
143
    int seen_sequence_header;
144
    int64_t frame_number;       /* number of the next frame to display       */
145
    Plane plane[3];
146
    int chroma_x_shift;
147
    int chroma_y_shift;
148
149
    int bit_depth;              /* bit depth                                 */
150
    int pshift;                 /* pixel shift = bit_depth > 8               */
151
152
    int zero_res;               /* zero residue flag                         */
153
    int is_arith;               /* whether coeffs use arith or golomb coding */
154
    int core_syntax;            /* use core syntax only                      */
155
    int low_delay;              /* use the low delay syntax                  */
156
    int hq_picture;             /* high quality picture, enables low_delay   */
157
    int ld_picture;             /* use low delay picture, turns on low_delay */
158
    int dc_prediction;          /* has dc prediction                         */
159
    int globalmc_flag;          /* use global motion compensation            */
160
    int num_refs;               /* number of reference pictures              */
161
162
    /* wavelet decoding */
163
    unsigned wavelet_depth;     /* depth of the IDWT                         */
164
    unsigned wavelet_idx;
165
166
    /**
167
     * schroedinger older than 1.0.8 doesn't store
168
     * quant delta if only one codebook exists in a band
169
     */
170
    unsigned old_delta_quant;
171
    unsigned codeblock_mode;
172
173
    unsigned num_x;              /* number of horizontal slices               */
174
    unsigned num_y;              /* number of vertical slices                 */
175
176
    uint8_t *thread_buf;         /* Per-thread buffer for coefficient storage */
177
    int threads_num_buf;         /* Current # of buffers allocated            */
178
    int thread_buf_size;         /* Each thread has a buffer this size        */
179
180
    DiracSlice *slice_params_buf;
181
    int slice_params_num_buf;
182
183
    struct {
184
        unsigned width;
185
        unsigned height;
186
    } codeblock[MAX_DWT_LEVELS+1];
187
188
    struct {
189
        AVRational bytes;       /* average bytes per slice                   */
190
        uint8_t quant[MAX_DWT_LEVELS][4]; /* [DIRAC_STD] E.1 */
191
    } lowdelay;
192
193
    struct {
194
        unsigned prefix_bytes;
195
        uint64_t size_scaler;
196
    } highquality;
197
198
    struct {
199
        int pan_tilt[2];        /* pan/tilt vector                           */
200
        int zrs[2][2];          /* zoom/rotate/shear matrix                  */
201
        int perspective[2];     /* perspective vector                        */
202
        unsigned zrs_exp;
203
        unsigned perspective_exp;
204
    } globalmc[2];
205
206
    /* motion compensation */
207
    uint8_t mv_precision;       /* [DIRAC_STD] REFS_WT_PRECISION             */
208
    int16_t weight[2];          /* [DIRAC_STD] REF1_WT and REF2_WT           */
209
    unsigned weight_log2denom;  /* [DIRAC_STD] REFS_WT_PRECISION             */
210
211
    int blwidth;                /* number of blocks (horizontally)           */
212
    int blheight;               /* number of blocks (vertically)             */
213
    int sbwidth;                /* number of superblocks (horizontally)      */
214
    int sbheight;               /* number of superblocks (vertically)        */
215
216
    uint8_t *sbsplit;
217
    DiracBlock *blmotion;
218
219
    uint8_t *edge_emu_buffer[4];
220
    uint8_t *edge_emu_buffer_base;
221
222
    uint16_t *mctmp;            /* buffer holding the MC data multiplied by OBMC weights */
223
    uint8_t *mcscratch;
224
    int buffer_stride;
225
226
    DECLARE_ALIGNED(16, uint8_t, obmc_weight)[3][MAX_BLOCKSIZE*MAX_BLOCKSIZE];
227
228
    void (*put_pixels_tab[4])(uint8_t *dst, const uint8_t *src[5], int stride, int h);
229
    void (*avg_pixels_tab[4])(uint8_t *dst, const uint8_t *src[5], int stride, int h);
230
    void (*add_obmc)(uint16_t *dst, const uint8_t *src, int stride, const uint8_t *obmc_weight, int yblen);
231
    dirac_weight_func weight_func;
232
    dirac_biweight_func biweight_func;
233
234
    DiracFrame *current_picture;
235
    DiracFrame *ref_pics[2];
236
237
    DiracFrame *ref_frames[MAX_REFERENCE_FRAMES+1];
238
    DiracFrame *delay_frames[MAX_DELAY+1];
239
    DiracFrame all_frames[MAX_FRAMES];
240
} DiracContext;
241
242
enum dirac_subband {
243
    subband_ll = 0,
244
    subband_hl = 1,
245
    subband_lh = 2,
246
    subband_hh = 3,
247
    subband_nb,
248
};
249
250
/* magic number division by 3 from schroedinger */
251
55371
static inline int divide3(int x)
252
{
253
55371
    return (int)((x+1U)*21845 + 10922) >> 16;
254
}
255
256
14
static DiracFrame *remove_frame(DiracFrame *framelist[], int picnum)
257
{
258
14
    DiracFrame *remove_pic = NULL;
259
14
    int i, remove_idx = -1;
260
261
39
    for (i = 0; framelist[i]; i++)
262
25
        if (framelist[i]->avframe->display_picture_number == picnum) {
263
13
            remove_pic = framelist[i];
264
13
            remove_idx = i;
265
        }
266
267
14
    if (remove_pic)
268
32
        for (i = remove_idx; framelist[i]; i++)
269
19
            framelist[i] = framelist[i+1];
270
271
14
    return remove_pic;
272
}
273
274
18
static int add_frame(DiracFrame *framelist[], int maxframes, DiracFrame *frame)
275
{
276
    int i;
277
33
    for (i = 0; i < maxframes; i++)
278
33
        if (!framelist[i]) {
279
18
            framelist[i] = frame;
280
18
            return 0;
281
        }
282
    return -1;
283
}
284
285
70
static int alloc_sequence_buffers(DiracContext *s)
286
{
287
70
    int sbwidth  = DIVRNDUP(s->seq.width,  4);
288
70
    int sbheight = DIVRNDUP(s->seq.height, 4);
289
    int i, w, h, top_padding;
290
291
    /* todo: think more about this / use or set Plane here */
292
280
    for (i = 0; i < 3; i++) {
293
210
        int max_xblen = MAX_BLOCKSIZE >> (i ? s->chroma_x_shift : 0);
294
210
        int max_yblen = MAX_BLOCKSIZE >> (i ? s->chroma_y_shift : 0);
295
210
        w = s->seq.width  >> (i ? s->chroma_x_shift : 0);
296
210
        h = s->seq.height >> (i ? s->chroma_y_shift : 0);
297
298
        /* we allocate the max we support here since num decompositions can
299
         * change from frame to frame. Stride is aligned to 16 for SIMD, and
300
         * 1<<MAX_DWT_LEVELS top padding to avoid if(y>0) in arith decoding
301
         * MAX_BLOCKSIZE padding for MC: blocks can spill up to half of that
302
         * on each side */
303
210
        top_padding = FFMAX(1<<MAX_DWT_LEVELS, max_yblen/2);
304
210
        w = FFALIGN(CALC_PADDING(w, MAX_DWT_LEVELS), 8); /* FIXME: Should this be 16 for SSE??? */
305
210
        h = top_padding + CALC_PADDING(h, MAX_DWT_LEVELS) + max_yblen/2;
306
307
210
        s->plane[i].idwt.buf_base = av_mallocz_array((w+max_xblen), h * (2 << s->pshift));
308
210
        s->plane[i].idwt.tmp      = av_malloc_array((w+16), 2 << s->pshift);
309
210
        s->plane[i].idwt.buf      = s->plane[i].idwt.buf_base + (top_padding*w)*(2 << s->pshift);
310

210
        if (!s->plane[i].idwt.buf_base || !s->plane[i].idwt.tmp)
311
            return AVERROR(ENOMEM);
312
    }
313
314
    /* fixme: allocate using real stride here */
315
70
    s->sbsplit  = av_malloc_array(sbwidth, sbheight);
316
70
    s->blmotion = av_malloc_array(sbwidth, sbheight * 16 * sizeof(*s->blmotion));
317
318

70
    if (!s->sbsplit || !s->blmotion)
319
        return AVERROR(ENOMEM);
320
70
    return 0;
321
}
322
323
260
static int alloc_buffers(DiracContext *s, int stride)
324
{
325
260
    int w = s->seq.width;
326
260
    int h = s->seq.height;
327
328
260
    av_assert0(stride >= w);
329
260
    stride += 64;
330
331
260
    if (s->buffer_stride >= stride)
332
190
        return 0;
333
70
    s->buffer_stride = 0;
334
335
70
    av_freep(&s->edge_emu_buffer_base);
336
70
    memset(s->edge_emu_buffer, 0, sizeof(s->edge_emu_buffer));
337
70
    av_freep(&s->mctmp);
338
70
    av_freep(&s->mcscratch);
339
340
70
    s->edge_emu_buffer_base = av_malloc_array(stride, MAX_BLOCKSIZE);
341
342
70
    s->mctmp     = av_malloc_array((stride+MAX_BLOCKSIZE), (h+MAX_BLOCKSIZE) * sizeof(*s->mctmp));
343
70
    s->mcscratch = av_malloc_array(stride, MAX_BLOCKSIZE);
344
345

70
    if (!s->edge_emu_buffer_base || !s->mctmp || !s->mcscratch)
346
        return AVERROR(ENOMEM);
347
348
70
    s->buffer_stride = stride;
349
70
    return 0;
350
}
351
352
70
static void free_sequence_buffers(DiracContext *s)
353
{
354
    int i, j, k;
355
356
1050
    for (i = 0; i < MAX_FRAMES; i++) {
357
980
        if (s->all_frames[i].avframe->data[0]) {
358
38
            av_frame_unref(s->all_frames[i].avframe);
359
38
            memset(s->all_frames[i].interpolated, 0, sizeof(s->all_frames[i].interpolated));
360
        }
361
362
3920
        for (j = 0; j < 3; j++)
363
11760
            for (k = 1; k < 4; k++)
364
8820
                av_freep(&s->all_frames[i].hpel_base[j][k]);
365
    }
366
367
70
    memset(s->ref_frames, 0, sizeof(s->ref_frames));
368
70
    memset(s->delay_frames, 0, sizeof(s->delay_frames));
369
370
280
    for (i = 0; i < 3; i++) {
371
210
        av_freep(&s->plane[i].idwt.buf_base);
372
210
        av_freep(&s->plane[i].idwt.tmp);
373
    }
374
375
70
    s->buffer_stride = 0;
376
70
    av_freep(&s->sbsplit);
377
70
    av_freep(&s->blmotion);
378
70
    av_freep(&s->edge_emu_buffer_base);
379
380
70
    av_freep(&s->mctmp);
381
70
    av_freep(&s->mcscratch);
382
70
}
383
384
static AVOnce dirac_arith_init = AV_ONCE_INIT;
385
386
70
static av_cold int dirac_decode_init(AVCodecContext *avctx)
387
{
388
70
    DiracContext *s = avctx->priv_data;
389
    int i, ret;
390
391
70
    s->avctx = avctx;
392
70
    s->frame_number = -1;
393
394
70
    s->thread_buf = NULL;
395
70
    s->threads_num_buf = -1;
396
70
    s->thread_buf_size = -1;
397
398
70
    ff_dirac_golomb_reader_init(&s->reader_ctx);
399
70
    ff_diracdsp_init(&s->diracdsp);
400
70
    ff_mpegvideoencdsp_init(&s->mpvencdsp, avctx);
401
70
    ff_videodsp_init(&s->vdsp, 8);
402
403
1050
    for (i = 0; i < MAX_FRAMES; i++) {
404
980
        s->all_frames[i].avframe = av_frame_alloc();
405
980
        if (!s->all_frames[i].avframe) {
406
            while (i > 0)
407
                av_frame_free(&s->all_frames[--i].avframe);
408
            return AVERROR(ENOMEM);
409
        }
410
    }
411
70
    ret = ff_thread_once(&dirac_arith_init, ff_dirac_init_arith_tables);
412
70
    if (ret != 0)
413
        return AVERROR_UNKNOWN;
414
415
70
    return 0;
416
}
417
418
70
static void dirac_decode_flush(AVCodecContext *avctx)
419
{
420
70
    DiracContext *s = avctx->priv_data;
421
70
    free_sequence_buffers(s);
422
70
    s->seen_sequence_header = 0;
423
70
    s->frame_number = -1;
424
70
}
425
426
70
static av_cold int dirac_decode_end(AVCodecContext *avctx)
427
{
428
70
    DiracContext *s = avctx->priv_data;
429
    int i;
430
431
70
    ff_dirac_golomb_reader_end(&s->reader_ctx);
432
433
70
    dirac_decode_flush(avctx);
434
1050
    for (i = 0; i < MAX_FRAMES; i++)
435
980
        av_frame_free(&s->all_frames[i].avframe);
436
437
70
    av_freep(&s->thread_buf);
438
70
    av_freep(&s->slice_params_buf);
439
440
70
    return 0;
441
}
442
443
1949239
static inline int coeff_unpack_golomb(GetBitContext *gb, int qfactor, int qoffset)
444
{
445
1949239
    int coeff = dirac_get_se_golomb(gb);
446
1949239
    const unsigned sign = FFSIGN(coeff);
447
1949239
    if (coeff)
448
336797
        coeff = sign*((sign * coeff * qfactor + qoffset) >> 2);
449
1949239
    return coeff;
450
}
451
452
#define SIGN_CTX(x) (CTX_SIGN_ZERO + ((x) > 0) - ((x) < 0))
453
454
#define UNPACK_ARITH(n, type) \
455
    static inline void coeff_unpack_arith_##n(DiracArith *c, int qfactor, int qoffset, \
456
                                              SubBand *b, type *buf, int x, int y) \
457
    { \
458
        int sign, sign_pred = 0, pred_ctx = CTX_ZPZN_F1; \
459
        unsigned coeff; \
460
        const int mstride = -(b->stride >> (1+b->pshift)); \
461
        if (b->parent) { \
462
            const type *pbuf = (type *)b->parent->ibuf; \
463
            const int stride = b->parent->stride >> (1+b->parent->pshift); \
464
            pred_ctx += !!pbuf[stride * (y>>1) + (x>>1)] << 1; \
465
        } \
466
        if (b->orientation == subband_hl) \
467
            sign_pred = buf[mstride]; \
468
        if (x) { \
469
            pred_ctx += !(buf[-1] | buf[mstride] | buf[-1 + mstride]); \
470
            if (b->orientation == subband_lh) \
471
                sign_pred = buf[-1]; \
472
        } else { \
473
            pred_ctx += !buf[mstride]; \
474
        } \
475
        coeff = dirac_get_arith_uint(c, pred_ctx, CTX_COEFF_DATA); \
476
        if (coeff) { \
477
            coeff = (coeff * qfactor + qoffset) >> 2; \
478
            sign  = dirac_get_arith_bit(c, SIGN_CTX(sign_pred)); \
479
            coeff = (coeff ^ -sign) + sign; \
480
        } \
481
        *buf = coeff; \
482
    } \
483
484



337100
UNPACK_ARITH(8, int16_t)
485
UNPACK_ARITH(10, int32_t)
486
487
/**
488
 * Decode the coeffs in the rectangle defined by left, right, top, bottom
489
 * [DIRAC_STD] 13.4.3.2 Codeblock unpacking loop. codeblock()
490
 */
491
82699
static inline int codeblock(DiracContext *s, SubBand *b,
492
                             GetBitContext *gb, DiracArith *c,
493
                             int left, int right, int top, int bottom,
494
                             int blockcnt_one, int is_arith)
495
{
496
    int x, y, zero_block;
497
    int qoffset, qfactor;
498
    uint8_t *buf;
499
500
    /* check for any coded coefficients in this codeblock */
501
82699
    if (!blockcnt_one) {
502
82635
        if (is_arith)
503
82635
            zero_block = dirac_get_arith_bit(c, CTX_ZERO_BLOCK);
504
        else
505
            zero_block = get_bits1(gb);
506
507
82635
        if (zero_block)
508
77258
            return 0;
509
    }
510
511

5441
    if (s->codeblock_mode && !(s->old_delta_quant && blockcnt_one)) {
512
        int quant;
513
        if (is_arith)
514
            quant = dirac_get_arith_int(c, CTX_DELTA_Q_F, CTX_DELTA_Q_DATA);
515
        else
516
            quant = dirac_get_se_golomb(gb);
517
        if (quant > INT_MAX - b->quant || b->quant + quant < 0) {
518
            av_log(s->avctx, AV_LOG_ERROR, "Invalid quant\n");
519
            return AVERROR_INVALIDDATA;
520
        }
521
        b->quant += quant;
522
    }
523
524
5441
    if (b->quant > (DIRAC_MAX_QUANT_INDEX - 1)) {
525
        av_log(s->avctx, AV_LOG_ERROR, "Unsupported quant %d\n", b->quant);
526
        b->quant = 0;
527
        return AVERROR_INVALIDDATA;
528
    }
529
530
5441
    qfactor = ff_dirac_qscale_tab[b->quant];
531
    /* TODO: context pointer? */
532
5441
    if (!s->num_refs)
533
1700
        qoffset = ff_dirac_qoffset_intra_tab[b->quant] + 2;
534
    else
535
3741
        qoffset = ff_dirac_qoffset_inter_tab[b->quant] + 2;
536
537
5441
    buf = b->ibuf + top * b->stride;
538
5441
    if (is_arith) {
539
46055
        for (y = top; y < bottom; y++) {
540
40614
            if (c->error)
541
                return c->error;
542
377714
            for (x = left; x < right; x++) {
543
337100
                if (b->pshift) {
544
                    coeff_unpack_arith_10(c, qfactor, qoffset, b, (int32_t*)(buf)+x, x, y);
545
                } else {
546
337100
                    coeff_unpack_arith_8(c, qfactor, qoffset, b, (int16_t*)(buf)+x, x, y);
547
                }
548
            }
549
40614
            buf += b->stride;
550
        }
551
    } else {
552
        for (y = top; y < bottom; y++) {
553
            if (get_bits_left(gb) < 1)
554
                return AVERROR_INVALIDDATA;
555
            for (x = left; x < right; x++) {
556
                int val = coeff_unpack_golomb(gb, qfactor, qoffset);
557
                if (b->pshift) {
558
                    AV_WN32(&buf[4*x], val);
559
                } else {
560
                    AV_WN16(&buf[2*x], val);
561
                }
562
            }
563
            buf += b->stride;
564
         }
565
     }
566
5441
     return 0;
567
}
568
569
/**
570
 * Dirac Specification ->
571
 * 13.3 intra_dc_prediction(band)
572
 */
573
#define INTRA_DC_PRED(n, type) \
574
    static inline void intra_dc_prediction_##n(SubBand *b) \
575
    { \
576
        type *buf = (type*)b->ibuf; \
577
        int x, y; \
578
        \
579
        for (x = 1; x < b->width; x++) \
580
            buf[x] += buf[x-1]; \
581
        buf += (b->stride >> (1+b->pshift)); \
582
        \
583
        for (y = 1; y < b->height; y++) { \
584
            buf[0] += buf[-(b->stride >> (1+b->pshift))]; \
585
            \
586
            for (x = 1; x < b->width; x++) { \
587
                int pred = buf[x - 1] + buf[x - (b->stride >> (1+b->pshift))] + buf[x - (b->stride >> (1+b->pshift))-1]; \
588
                buf[x]  += divide3(pred); \
589
            } \
590
            buf += (b->stride >> (1+b->pshift)); \
591
        } \
592
    } \
593
594

59400
INTRA_DC_PRED(8, int16_t)
595
INTRA_DC_PRED(10, uint32_t)
596
597
/**
598
 * Dirac Specification ->
599
 * 13.4.2 Non-skipped subbands.  subband_coeffs()
600
 */
601
930
static av_always_inline int decode_subband_internal(DiracContext *s, SubBand *b, int is_arith)
602
{
603
    int cb_x, cb_y, left, right, top, bottom;
604
    DiracArith c;
605
    GetBitContext gb;
606
930
    int cb_width  = s->codeblock[b->level + (b->orientation != subband_ll)].width;
607
930
    int cb_height = s->codeblock[b->level + (b->orientation != subband_ll)].height;
608
930
    int blockcnt_one = (cb_width + cb_height) == 2;
609
    int ret;
610
611
930
    if (!b->length)
612
263
        return 0;
613
614
667
    init_get_bits8(&gb, b->coeff_data, b->length);
615
616
667
    if (is_arith)
617
667
        ff_dirac_init_arith_decoder(&c, &gb, b->length);
618
619
667
    top = 0;
620
5972
    for (cb_y = 0; cb_y < cb_height; cb_y++) {
621
5305
        bottom = (b->height * (cb_y+1LL)) / cb_height;
622
5305
        left = 0;
623
88004
        for (cb_x = 0; cb_x < cb_width; cb_x++) {
624
82699
            right = (b->width * (cb_x+1LL)) / cb_width;
625
82699
            ret = codeblock(s, b, &gb, &c, left, right, top, bottom, blockcnt_one, is_arith);
626
82699
            if (ret < 0)
627
                return ret;
628
82699
            left = right;
629
        }
630
5305
        top = bottom;
631
    }
632
633

667
    if (b->orientation == subband_ll && s->num_refs == 0) {
634
6
        if (s->pshift) {
635
            intra_dc_prediction_10(b);
636
        } else {
637
6
            intra_dc_prediction_8(b);
638
        }
639
    }
640
667
    return 0;
641
}
642
643
930
static int decode_subband_arith(AVCodecContext *avctx, void *b)
644
{
645
930
    DiracContext *s = avctx->priv_data;
646
930
    return decode_subband_internal(s, b, 1);
647
}
648
649
static int decode_subband_golomb(AVCodecContext *avctx, void *arg)
650
{
651
    DiracContext *s = avctx->priv_data;
652
    SubBand **b     = arg;
653
    return decode_subband_internal(s, *b, 0);
654
}
655
656
/**
657
 * Dirac Specification ->
658
 * [DIRAC_STD] 13.4.1 core_transform_data()
659
 */
660
93
static int decode_component(DiracContext *s, int comp)
661
{
662
93
    AVCodecContext *avctx = s->avctx;
663
    SubBand *bands[3*MAX_DWT_LEVELS+1];
664
    enum dirac_subband orientation;
665
93
    int level, num_bands = 0;
666
    int ret[3*MAX_DWT_LEVELS+1];
667
    int i;
668
93
    int damaged_count = 0;
669
670
    /* Unpack all subbands at all levels. */
671
372
    for (level = 0; level < s->wavelet_depth; level++) {
672
1209
        for (orientation = !!level; orientation < 4; orientation++) {
673
930
            SubBand *b = &s->plane[comp].band[level][orientation];
674
930
            bands[num_bands++] = b;
675
676
930
            align_get_bits(&s->gb);
677
            /* [DIRAC_STD] 13.4.2 subband() */
678
930
            b->length = get_interleaved_ue_golomb(&s->gb);
679
930
            if (b->length) {
680
667
                b->quant = get_interleaved_ue_golomb(&s->gb);
681
667
                if (b->quant > (DIRAC_MAX_QUANT_INDEX - 1)) {
682
                    av_log(s->avctx, AV_LOG_ERROR, "Unsupported quant %d\n", b->quant);
683
                    b->quant = 0;
684
                    return AVERROR_INVALIDDATA;
685
                }
686
667
                align_get_bits(&s->gb);
687
667
                b->coeff_data = s->gb.buffer + get_bits_count(&s->gb)/8;
688

667
                if (b->length > FFMAX(get_bits_left(&s->gb)/8, 0)) {
689
                    b->length = FFMAX(get_bits_left(&s->gb)/8, 0);
690
                    damaged_count ++;
691
                }
692
667
                skip_bits_long(&s->gb, b->length*8);
693
            }
694
        }
695
        /* arithmetic coding has inter-level dependencies, so we can only execute one level at a time */
696
279
        if (s->is_arith)
697
279
            avctx->execute(avctx, decode_subband_arith, &s->plane[comp].band[level][!!level],
698
279
                           ret + 3*level + !!level, 4-!!level, sizeof(SubBand));
699
    }
700
    /* golomb coding has no inter-level dependencies, so we can execute all subbands in parallel */
701
93
    if (!s->is_arith)
702
        avctx->execute(avctx, decode_subband_golomb, bands, ret, num_bands, sizeof(SubBand*));
703
704
1023
    for (i = 0; i < s->wavelet_depth * 3 + 1; i++) {
705
930
        if (ret[i] < 0)
706
            damaged_count++;
707
    }
708
93
    if (damaged_count > (s->wavelet_depth * 3 + 1) /2)
709
        return AVERROR_INVALIDDATA;
710
711
93
    return 0;
712
}
713
714
#define PARSE_VALUES(type, x, gb, ebits, buf1, buf2) \
715
    type *buf = (type *)buf1; \
716
    buf[x] = coeff_unpack_golomb(gb, qfactor, qoffset); \
717
    if (get_bits_count(gb) >= ebits) \
718
        return; \
719
    if (buf2) { \
720
        buf = (type *)buf2; \
721
        buf[x] = coeff_unpack_golomb(gb, qfactor, qoffset); \
722
        if (get_bits_count(gb) >= ebits) \
723
            return; \
724
    } \
725
726
186000
static void decode_subband(DiracContext *s, GetBitContext *gb, int quant,
727
                           int slice_x, int slice_y, int bits_end,
728
                           SubBand *b1, SubBand *b2)
729
{
730
186000
    int left   = b1->width  * slice_x    / s->num_x;
731
186000
    int right  = b1->width  *(slice_x+1) / s->num_x;
732
186000
    int top    = b1->height * slice_y    / s->num_y;
733
186000
    int bottom = b1->height *(slice_y+1) / s->num_y;
734
735
    int qfactor, qoffset;
736
737
186000
    uint8_t *buf1 =      b1->ibuf + top * b1->stride;
738
186000
    uint8_t *buf2 = b2 ? b2->ibuf + top * b2->stride: NULL;
739
    int x, y;
740
741
186000
    if (quant > (DIRAC_MAX_QUANT_INDEX - 1)) {
742
        av_log(s->avctx, AV_LOG_ERROR, "Unsupported quant %d\n", quant);
743
        return;
744
    }
745
186000
    qfactor = ff_dirac_qscale_tab[quant];
746
186000
    qoffset = ff_dirac_qoffset_intra_tab[quant] + 2;
747
    /* we have to constantly check for overread since the spec explicitly
748
       requires this, with the meaning that all remaining coeffs are set to 0 */
749
186000
    if (get_bits_count(gb) >= bits_end)
750
38746
        return;
751
752
147254
    if (s->pshift) {
753
        for (y = top; y < bottom; y++) {
754
            for (x = left; x < right; x++) {
755
                PARSE_VALUES(int32_t, x, gb, bits_end, buf1, buf2);
756
            }
757
            buf1 += b1->stride;
758
            if (buf2)
759
                buf2 += b2->stride;
760
        }
761
    }
762
    else {
763
518899
        for (y = top; y < bottom; y++) {
764
1836007
            for (x = left; x < right; x++) {
765

1464362
                PARSE_VALUES(int16_t, x, gb, bits_end, buf1, buf2);
766
            }
767
371645
            buf1 += b1->stride;
768
371645
            if (buf2)
769
173605
                buf2 += b2->stride;
770
        }
771
    }
772
}
773
774
/**
775
 * Dirac Specification ->
776
 * 13.5.2 Slices. slice(sx,sy)
777
 */
778
9300
static int decode_lowdelay_slice(AVCodecContext *avctx, void *arg)
779
{
780
9300
    DiracContext *s = avctx->priv_data;
781
9300
    DiracSlice *slice = arg;
782
9300
    GetBitContext *gb = &slice->gb;
783
    enum dirac_subband orientation;
784
    int level, quant, chroma_bits, chroma_end;
785
786
9300
    int quant_base  = get_bits(gb, 7); /*[DIRAC_STD] qindex */
787
9300
    int length_bits = av_log2(8 * slice->bytes)+1;
788
9300
    int luma_bits   = get_bits_long(gb, length_bits);
789
9300
    int luma_end    = get_bits_count(gb) + FFMIN(luma_bits, get_bits_left(gb));
790
791
    /* [DIRAC_STD] 13.5.5.2 luma_slice_band */
792
37200
    for (level = 0; level < s->wavelet_depth; level++)
793
120900
        for (orientation = !!level; orientation < 4; orientation++) {
794
93000
            quant = FFMAX(quant_base - s->lowdelay.quant[level][orientation], 0);
795
93000
            decode_subband(s, gb, quant, slice->slice_x, slice->slice_y, luma_end,
796
                           &s->plane[0].band[level][orientation], NULL);
797
        }
798
799
    /* consume any unused bits from luma */
800
9300
    skip_bits_long(gb, get_bits_count(gb) - luma_end);
801
802
9300
    chroma_bits = 8*slice->bytes - 7 - length_bits - luma_bits;
803
9300
    chroma_end  = get_bits_count(gb) + FFMIN(chroma_bits, get_bits_left(gb));
804
    /* [DIRAC_STD] 13.5.5.3 chroma_slice_band */
805
37200
    for (level = 0; level < s->wavelet_depth; level++)
806
120900
        for (orientation = !!level; orientation < 4; orientation++) {
807
93000
            quant = FFMAX(quant_base - s->lowdelay.quant[level][orientation], 0);
808
93000
            decode_subband(s, gb, quant, slice->slice_x, slice->slice_y, chroma_end,
809
                           &s->plane[1].band[level][orientation],
810
                           &s->plane[2].band[level][orientation]);
811
        }
812
813
9300
    return 0;
814
}
815
816
typedef struct SliceCoeffs {
817
    int left;
818
    int top;
819
    int tot_h;
820
    int tot_v;
821
    int tot;
822
} SliceCoeffs;
823
824
117841
static int subband_coeffs(DiracContext *s, int x, int y, int p,
825
                          SliceCoeffs c[MAX_DWT_LEVELS])
826
{
827
117841
    int level, coef = 0;
828
589174
    for (level = 0; level < s->wavelet_depth; level++) {
829
471333
        SliceCoeffs *o = &c[level];
830
471333
        SubBand *b = &s->plane[p].band[level][3]; /* orientation doens't matter */
831
471333
        o->top   = b->height * y / s->num_y;
832
471333
        o->left  = b->width  * x / s->num_x;
833
471333
        o->tot_h = ((b->width  * (x + 1)) / s->num_x) - o->left;
834
471333
        o->tot_v = ((b->height * (y + 1)) / s->num_y) - o->top;
835
471333
        o->tot   = o->tot_h*o->tot_v;
836
471333
        coef    += o->tot * (4 - !!level);
837
    }
838
117841
    return coef;
839
}
840
841
/**
842
 * VC-2 Specification ->
843
 * 13.5.3 hq_slice(sx,sy)
844
 */
845
39204
static int decode_hq_slice(DiracContext *s, DiracSlice *slice, uint8_t *tmp_buf)
846
{
847
    int i, level, orientation, quant_idx;
848
    int qfactor[MAX_DWT_LEVELS][4], qoffset[MAX_DWT_LEVELS][4];
849
39204
    GetBitContext *gb = &slice->gb;
850
    SliceCoeffs coeffs_num[MAX_DWT_LEVELS];
851
852
39204
    skip_bits_long(gb, 8*s->highquality.prefix_bytes);
853
39204
    quant_idx = get_bits(gb, 8);
854
855
39204
    if (quant_idx > DIRAC_MAX_QUANT_INDEX - 1) {
856
        av_log(s->avctx, AV_LOG_ERROR, "Invalid quantization index - %i\n", quant_idx);
857
        return AVERROR_INVALIDDATA;
858
    }
859
860
    /* Slice quantization (slice_quantizers() in the specs) */
861
196020
    for (level = 0; level < s->wavelet_depth; level++) {
862
666468
        for (orientation = !!level; orientation < 4; orientation++) {
863
509652
            const int quant = FFMAX(quant_idx - s->lowdelay.quant[level][orientation], 0);
864
509652
            qfactor[level][orientation] = ff_dirac_qscale_tab[quant];
865
509652
            qoffset[level][orientation] = ff_dirac_qoffset_intra_tab[quant] + 2;
866
        }
867
    }
868
869
    /* Luma + 2 Chroma planes */
870
156816
    for (i = 0; i < 3; i++) {
871
117612
        int coef_num, coef_par, off = 0;
872
117612
        int64_t length = s->highquality.size_scaler*get_bits(gb, 8);
873
117612
        int64_t bits_end = get_bits_count(gb) + 8*length;
874
117612
        const uint8_t *addr = align_get_bits(gb);
875
876
117612
        if (length*8 > get_bits_left(gb)) {
877
            av_log(s->avctx, AV_LOG_ERROR, "end too far away\n");
878
            return AVERROR_INVALIDDATA;
879
        }
880
881
117612
        coef_num = subband_coeffs(s, slice->slice_x, slice->slice_y, i, coeffs_num);
882
883
117612
        if (s->pshift)
884
85536
            coef_par = ff_dirac_golomb_read_32bit(s->reader_ctx, addr,
885
                                                  length, tmp_buf, coef_num);
886
        else
887
32076
            coef_par = ff_dirac_golomb_read_16bit(s->reader_ctx, addr,
888
                                                  length, tmp_buf, coef_num);
889
890
117612
        if (coef_num > coef_par) {
891
            const int start_b = coef_par * (1 << (s->pshift + 1));
892
            const int end_b   = coef_num * (1 << (s->pshift + 1));
893
            memset(&tmp_buf[start_b], 0, end_b - start_b);
894
        }
895
896
588060
        for (level = 0; level < s->wavelet_depth; level++) {
897
470448
            const SliceCoeffs *c = &coeffs_num[level];
898
1999404
            for (orientation = !!level; orientation < 4; orientation++) {
899
1528956
                const SubBand *b1 = &s->plane[i].band[level][orientation];
900
1528956
                uint8_t *buf = b1->ibuf + c->top * b1->stride + (c->left << (s->pshift + 1));
901
902
                /* Change to c->tot_h <= 4 for AVX2 dequantization */
903
1528956
                const int qfunc = s->pshift + 2*(c->tot_h <= 2);
904
1528956
                s->diracdsp.dequant_subband[qfunc](&tmp_buf[off], buf, b1->stride,
905
                                                   qfactor[level][orientation],
906
                                                   qoffset[level][orientation],
907
                                                   c->tot_v, c->tot_h);
908
909
1528956
                off += c->tot << (s->pshift + 1);
910
            }
911
        }
912
913
117612
        skip_bits_long(gb, bits_end - get_bits_count(gb));
914
    }
915
916
39204
    return 0;
917
}
918
919
3564
static int decode_hq_slice_row(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
920
{
921
    int i;
922
3564
    DiracContext *s = avctx->priv_data;
923
3564
    DiracSlice *slices = ((DiracSlice *)arg) + s->num_x*jobnr;
924
3564
    uint8_t *thread_buf = &s->thread_buf[s->thread_buf_size*threadnr];
925
42768
    for (i = 0; i < s->num_x; i++)
926
39204
        decode_hq_slice(s, &slices[i], thread_buf);
927
3564
    return 0;
928
}
929
930
/**
931
 * Dirac Specification ->
932
 * 13.5.1 low_delay_transform_data()
933
 */
934
229
static int decode_lowdelay(DiracContext *s)
935
{
936
229
    AVCodecContext *avctx = s->avctx;
937
    int slice_x, slice_y, bufsize;
938
229
    int64_t coef_buf_size, bytes = 0;
939
    const uint8_t *buf;
940
    DiracSlice *slices;
941
    SliceCoeffs tmp[MAX_DWT_LEVELS];
942
229
    int slice_num = 0;
943
944
229
    if (s->slice_params_num_buf != (s->num_x * s->num_y)) {
945
68
        s->slice_params_buf = av_realloc_f(s->slice_params_buf, s->num_x * s->num_y, sizeof(DiracSlice));
946
68
        if (!s->slice_params_buf) {
947
            av_log(s->avctx, AV_LOG_ERROR, "slice params buffer allocation failure\n");
948
            s->slice_params_num_buf = 0;
949
            return AVERROR(ENOMEM);
950
        }
951
68
        s->slice_params_num_buf = s->num_x * s->num_y;
952
    }
953
229
    slices = s->slice_params_buf;
954
955
    /* 8 becacuse that's how much the golomb reader could overread junk data
956
     * from another plane/slice at most, and 512 because SIMD */
957
229
    coef_buf_size = subband_coeffs(s, s->num_x - 1, s->num_y - 1, 0, tmp) + 8;
958
229
    coef_buf_size = (coef_buf_size << (1 + s->pshift)) + 512;
959
960
229
    if (s->threads_num_buf != avctx->thread_count ||
961
161
        s->thread_buf_size != coef_buf_size) {
962
68
        s->threads_num_buf  = avctx->thread_count;
963
68
        s->thread_buf_size  = coef_buf_size;
964
68
        s->thread_buf       = av_realloc_f(s->thread_buf, avctx->thread_count, s->thread_buf_size);
965
68
        if (!s->thread_buf) {
966
            av_log(s->avctx, AV_LOG_ERROR, "thread buffer allocation failure\n");
967
            return AVERROR(ENOMEM);
968
        }
969
    }
970
971
229
    align_get_bits(&s->gb);
972
    /*[DIRAC_STD] 13.5.2 Slices. slice(sx,sy) */
973
229
    buf = s->gb.buffer + get_bits_count(&s->gb)/8;
974
229
    bufsize = get_bits_left(&s->gb);
975
976
229
    if (s->hq_picture) {
977
        int i;
978
979

3762
        for (slice_y = 0; bufsize > 0 && slice_y < s->num_y; slice_y++) {
980

42768
            for (slice_x = 0; bufsize > 0 && slice_x < s->num_x; slice_x++) {
981
39204
                bytes = s->highquality.prefix_bytes + 1;
982
156816
                for (i = 0; i < 3; i++) {
983
117612
                    if (bytes <= bufsize/8)
984
117612
                        bytes += buf[bytes] * s->highquality.size_scaler + 1;
985
                }
986

39204
                if (bytes >= INT_MAX || bytes*8 > bufsize) {
987
                    av_log(s->avctx, AV_LOG_ERROR, "too many bytes\n");
988
                    return AVERROR_INVALIDDATA;
989
                }
990
991
39204
                slices[slice_num].bytes   = bytes;
992
39204
                slices[slice_num].slice_x = slice_x;
993
39204
                slices[slice_num].slice_y = slice_y;
994
39204
                init_get_bits(&slices[slice_num].gb, buf, bufsize);
995
39204
                slice_num++;
996
997
39204
                buf     += bytes;
998
39204
                if (bufsize/8 >= bytes)
999
39204
                    bufsize -= bytes*8;
1000
                else
1001
                    bufsize = 0;
1002
            }
1003
        }
1004
1005
198
        if (s->num_x*s->num_y != slice_num) {
1006
            av_log(s->avctx, AV_LOG_ERROR, "too few slices\n");
1007
            return AVERROR_INVALIDDATA;
1008
        }
1009
1010
198
        avctx->execute2(avctx, decode_hq_slice_row, slices, NULL, s->num_y);
1011
    } else {
1012

496
        for (slice_y = 0; bufsize > 0 && slice_y < s->num_y; slice_y++) {
1013

9765
            for (slice_x = 0; bufsize > 0 && slice_x < s->num_x; slice_x++) {
1014
9300
                bytes = (slice_num+1) * (int64_t)s->lowdelay.bytes.num / s->lowdelay.bytes.den
1015
9300
                       - slice_num    * (int64_t)s->lowdelay.bytes.num / s->lowdelay.bytes.den;
1016

9300
                if (bytes >= INT_MAX || bytes*8 > bufsize) {
1017
                    av_log(s->avctx, AV_LOG_ERROR, "too many bytes\n");
1018
                    return AVERROR_INVALIDDATA;
1019
                }
1020
9300
                slices[slice_num].bytes   = bytes;
1021
9300
                slices[slice_num].slice_x = slice_x;
1022
9300
                slices[slice_num].slice_y = slice_y;
1023
9300
                init_get_bits(&slices[slice_num].gb, buf, bufsize);
1024
9300
                slice_num++;
1025
1026
9300
                buf     += bytes;
1027
9300
                if (bufsize/8 >= bytes)
1028
9300
                    bufsize -= bytes*8;
1029
                else
1030
                    bufsize = 0;
1031
            }
1032
        }
1033
31
        avctx->execute(avctx, decode_lowdelay_slice, slices, NULL, slice_num,
1034
                       sizeof(DiracSlice)); /* [DIRAC_STD] 13.5.2 Slices */
1035
    }
1036
1037
229
    if (s->dc_prediction) {
1038
31
        if (s->pshift) {
1039
            intra_dc_prediction_10(&s->plane[0].band[0][0]); /* [DIRAC_STD] 13.3 intra_dc_prediction() */
1040
            intra_dc_prediction_10(&s->plane[1].band[0][0]); /* [DIRAC_STD] 13.3 intra_dc_prediction() */
1041
            intra_dc_prediction_10(&s->plane[2].band[0][0]); /* [DIRAC_STD] 13.3 intra_dc_prediction() */
1042
        } else {
1043
31
            intra_dc_prediction_8(&s->plane[0].band[0][0]);
1044
31
            intra_dc_prediction_8(&s->plane[1].band[0][0]);
1045
31
            intra_dc_prediction_8(&s->plane[2].band[0][0]);
1046
        }
1047
    }
1048
1049
229
    return 0;
1050
}
1051
1052
260
static void init_planes(DiracContext *s)
1053
{
1054
    int i, w, h, level, orientation;
1055
1056
1040
    for (i = 0; i < 3; i++) {
1057
780
        Plane *p = &s->plane[i];
1058
1059
780
        p->width       = s->seq.width  >> (i ? s->chroma_x_shift : 0);
1060
780
        p->height      = s->seq.height >> (i ? s->chroma_y_shift : 0);
1061
780
        p->idwt.width  = w = CALC_PADDING(p->width , s->wavelet_depth);
1062
780
        p->idwt.height = h = CALC_PADDING(p->height, s->wavelet_depth);
1063
780
        p->idwt.stride = FFALIGN(p->idwt.width, 8) << (1 + s->pshift);
1064
1065
3714
        for (level = s->wavelet_depth-1; level >= 0; level--) {
1066
2934
            w = w>>1;
1067
2934
            h = h>>1;
1068
12516
            for (orientation = !!level; orientation < 4; orientation++) {
1069
9582
                SubBand *b = &p->band[level][orientation];
1070
1071
9582
                b->pshift = s->pshift;
1072
9582
                b->ibuf   = p->idwt.buf;
1073
9582
                b->level  = level;
1074
9582
                b->stride = p->idwt.stride << (s->wavelet_depth - level);
1075
9582
                b->width  = w;
1076
9582
                b->height = h;
1077
9582
                b->orientation = orientation;
1078
1079
9582
                if (orientation & 1)
1080
5868
                    b->ibuf += w << (1+b->pshift);
1081
9582
                if (orientation > 1)
1082
5868
                    b->ibuf += (b->stride>>1);
1083
1084
9582
                if (level)
1085
6462
                    b->parent = &p->band[level-1][orientation];
1086
            }
1087
        }
1088
1089
780
        if (i > 0) {
1090
520
            p->xblen = s->plane[0].xblen >> s->chroma_x_shift;
1091
520
            p->yblen = s->plane[0].yblen >> s->chroma_y_shift;
1092
520
            p->xbsep = s->plane[0].xbsep >> s->chroma_x_shift;
1093
520
            p->ybsep = s->plane[0].ybsep >> s->chroma_y_shift;
1094
        }
1095
1096
780
        p->xoffset = (p->xblen - p->xbsep)/2;
1097
780
        p->yoffset = (p->yblen - p->ybsep)/2;
1098
    }
1099
260
}
1100
1101
/**
1102
 * Unpack the motion compensation parameters
1103
 * Dirac Specification ->
1104
 * 11.2 Picture prediction data. picture_prediction()
1105
 */
1106
29
static int dirac_unpack_prediction_parameters(DiracContext *s)
1107
{
1108
    static const uint8_t default_blen[] = { 4, 12, 16, 24 };
1109
1110
29
    GetBitContext *gb = &s->gb;
1111
    unsigned idx, ref;
1112
1113
29
    align_get_bits(gb);
1114
    /* [DIRAC_STD] 11.2.2 Block parameters. block_parameters() */
1115
    /* Luma and Chroma are equal. 11.2.3 */
1116
29
    idx = get_interleaved_ue_golomb(gb); /* [DIRAC_STD] index */
1117
1118
29
    if (idx > 4) {
1119
        av_log(s->avctx, AV_LOG_ERROR, "Block prediction index too high\n");
1120
        return AVERROR_INVALIDDATA;
1121
    }
1122
1123
29
    if (idx == 0) {
1124
29
        s->plane[0].xblen = get_interleaved_ue_golomb(gb);
1125
29
        s->plane[0].yblen = get_interleaved_ue_golomb(gb);
1126
29
        s->plane[0].xbsep = get_interleaved_ue_golomb(gb);
1127
29
        s->plane[0].ybsep = get_interleaved_ue_golomb(gb);
1128
    } else {
1129
        /*[DIRAC_STD] preset_block_params(index). Table 11.1 */
1130
        s->plane[0].xblen = default_blen[idx-1];
1131
        s->plane[0].yblen = default_blen[idx-1];
1132
        s->plane[0].xbsep = 4 * idx;
1133
        s->plane[0].ybsep = 4 * idx;
1134
    }
1135
    /*[DIRAC_STD] 11.2.4 motion_data_dimensions()
1136
      Calculated in function dirac_unpack_block_motion_data */
1137
1138
29
    if (s->plane[0].xblen % (1 << s->chroma_x_shift) != 0 ||
1139
29
        s->plane[0].yblen % (1 << s->chroma_y_shift) != 0 ||
1140

29
        !s->plane[0].xblen || !s->plane[0].yblen) {
1141
        av_log(s->avctx, AV_LOG_ERROR,
1142
               "invalid x/y block length (%d/%d) for x/y chroma shift (%d/%d)\n",
1143
               s->plane[0].xblen, s->plane[0].yblen, s->chroma_x_shift, s->chroma_y_shift);
1144
        return AVERROR_INVALIDDATA;
1145
    }
1146


29
    if (!s->plane[0].xbsep || !s->plane[0].ybsep || s->plane[0].xbsep < s->plane[0].xblen/2 || s->plane[0].ybsep < s->plane[0].yblen/2) {
1147
        av_log(s->avctx, AV_LOG_ERROR, "Block separation too small\n");
1148
        return AVERROR_INVALIDDATA;
1149
    }
1150

29
    if (s->plane[0].xbsep > s->plane[0].xblen || s->plane[0].ybsep > s->plane[0].yblen) {
1151
        av_log(s->avctx, AV_LOG_ERROR, "Block separation greater than size\n");
1152
        return AVERROR_INVALIDDATA;
1153
    }
1154
29
    if (FFMAX(s->plane[0].xblen, s->plane[0].yblen) > MAX_BLOCKSIZE) {
1155
        av_log(s->avctx, AV_LOG_ERROR, "Unsupported large block size\n");
1156
        return AVERROR_PATCHWELCOME;
1157
    }
1158
1159
    /*[DIRAC_STD] 11.2.5 Motion vector precision. motion_vector_precision()
1160
      Read motion vector precision */
1161
29
    s->mv_precision = get_interleaved_ue_golomb(gb);
1162
29
    if (s->mv_precision > 3) {
1163
        av_log(s->avctx, AV_LOG_ERROR, "MV precision finer than eighth-pel\n");
1164
        return AVERROR_INVALIDDATA;
1165
    }
1166
1167
    /*[DIRAC_STD] 11.2.6 Global motion. global_motion()
1168
      Read the global motion compensation parameters */
1169
29
    s->globalmc_flag = get_bits1(gb);
1170
29
    if (s->globalmc_flag) {
1171
        memset(s->globalmc, 0, sizeof(s->globalmc));
1172
        /* [DIRAC_STD] pan_tilt(gparams) */
1173
        for (ref = 0; ref < s->num_refs; ref++) {
1174
            if (get_bits1(gb)) {
1175
                s->globalmc[ref].pan_tilt[0] = dirac_get_se_golomb(gb);
1176
                s->globalmc[ref].pan_tilt[1] = dirac_get_se_golomb(gb);
1177
            }
1178
            /* [DIRAC_STD] zoom_rotate_shear(gparams)
1179
               zoom/rotation/shear parameters */
1180
            if (get_bits1(gb)) {
1181
                s->globalmc[ref].zrs_exp   = get_interleaved_ue_golomb(gb);
1182
                s->globalmc[ref].zrs[0][0] = dirac_get_se_golomb(gb);
1183
                s->globalmc[ref].zrs[0][1] = dirac_get_se_golomb(gb);
1184
                s->globalmc[ref].zrs[1][0] = dirac_get_se_golomb(gb);
1185
                s->globalmc[ref].zrs[1][1] = dirac_get_se_golomb(gb);
1186
            } else {
1187
                s->globalmc[ref].zrs[0][0] = 1;
1188
                s->globalmc[ref].zrs[1][1] = 1;
1189
            }
1190
            /* [DIRAC_STD] perspective(gparams) */
1191
            if (get_bits1(gb)) {
1192
                s->globalmc[ref].perspective_exp = get_interleaved_ue_golomb(gb);
1193
                s->globalmc[ref].perspective[0]  = dirac_get_se_golomb(gb);
1194
                s->globalmc[ref].perspective[1]  = dirac_get_se_golomb(gb);
1195
            }
1196
            if (s->globalmc[ref].perspective_exp + (uint64_t)s->globalmc[ref].zrs_exp > 30) {
1197
                return AVERROR_INVALIDDATA;
1198
            }
1199
1200
        }
1201
    }
1202
1203
    /*[DIRAC_STD] 11.2.7 Picture prediction mode. prediction_mode()
1204
      Picture prediction mode, not currently used. */
1205
29
    if (get_interleaved_ue_golomb(gb)) {
1206
        av_log(s->avctx, AV_LOG_ERROR, "Unknown picture prediction mode\n");
1207
        return AVERROR_INVALIDDATA;
1208
    }
1209
1210
    /* [DIRAC_STD] 11.2.8 Reference picture weight. reference_picture_weights()
1211
       just data read, weight calculation will be done later on. */
1212
29
    s->weight_log2denom = 1;
1213
29
    s->weight[0]        = 1;
1214
29
    s->weight[1]        = 1;
1215
1216
29
    if (get_bits1(gb)) {
1217
        s->weight_log2denom = get_interleaved_ue_golomb(gb);
1218
        if (s->weight_log2denom < 1 || s->weight_log2denom > 8) {
1219
            av_log(s->avctx, AV_LOG_ERROR, "weight_log2denom unsupported or invalid\n");
1220
            s->weight_log2denom = 1;
1221
            return AVERROR_INVALIDDATA;
1222
        }
1223
        s->weight[0] = dirac_get_se_golomb(gb);
1224
        if (s->num_refs == 2)
1225
            s->weight[1] = dirac_get_se_golomb(gb);
1226
    }
1227
29
    return 0;
1228
}
1229
1230
/**
1231
 * Dirac Specification ->
1232
 * 11.3 Wavelet transform data. wavelet_transform()
1233
 */
1234
260
static int dirac_unpack_idwt_params(DiracContext *s)
1235
{
1236
260
    GetBitContext *gb = &s->gb;
1237
    int i, level;
1238
    unsigned tmp;
1239
1240
#define CHECKEDREAD(dst, cond, errmsg) \
1241
    tmp = get_interleaved_ue_golomb(gb); \
1242
    if (cond) { \
1243
        av_log(s->avctx, AV_LOG_ERROR, errmsg); \
1244
        return AVERROR_INVALIDDATA; \
1245
    }\
1246
    dst = tmp;
1247
1248
260
    align_get_bits(gb);
1249
1250
260
    s->zero_res = s->num_refs ? get_bits1(gb) : 0;
1251
260
    if (s->zero_res)
1252
        return 0;
1253
1254
    /*[DIRAC_STD] 11.3.1 Transform parameters. transform_parameters() */
1255
260
    CHECKEDREAD(s->wavelet_idx, tmp > 6, "wavelet_idx is too big\n")
1256
1257

260
    CHECKEDREAD(s->wavelet_depth, tmp > MAX_DWT_LEVELS || tmp < 1, "invalid number of DWT decompositions\n")
1258
1259
260
    if (!s->low_delay) {
1260
        /* Codeblock parameters (core syntax only) */
1261
31
        if (get_bits1(gb)) {
1262
155
            for (i = 0; i <= s->wavelet_depth; i++) {
1263

124
                CHECKEDREAD(s->codeblock[i].width , tmp < 1 || tmp > (s->avctx->width >>s->wavelet_depth-i), "codeblock width invalid\n")
1264

124
                CHECKEDREAD(s->codeblock[i].height, tmp < 1 || tmp > (s->avctx->height>>s->wavelet_depth-i), "codeblock height invalid\n")
1265
            }
1266
1267
31
            CHECKEDREAD(s->codeblock_mode, tmp > 1, "unknown codeblock mode\n")
1268
        }
1269
        else {
1270
            for (i = 0; i <= s->wavelet_depth; i++)
1271
                s->codeblock[i].width = s->codeblock[i].height = 1;
1272
        }
1273
    }
1274
    else {
1275
229
        s->num_x        = get_interleaved_ue_golomb(gb);
1276
229
        s->num_y        = get_interleaved_ue_golomb(gb);
1277

229
        if (s->num_x * s->num_y == 0 || s->num_x * (uint64_t)s->num_y > INT_MAX ||
1278
229
            s->num_x * (uint64_t)s->avctx->width  > INT_MAX ||
1279
229
            s->num_y * (uint64_t)s->avctx->height > INT_MAX ||
1280
229
            s->num_x > s->avctx->width ||
1281
229
            s->num_y > s->avctx->height
1282
        ) {
1283
            av_log(s->avctx,AV_LOG_ERROR,"Invalid numx/y\n");
1284
            s->num_x = s->num_y = 0;
1285
            return AVERROR_INVALIDDATA;
1286
        }
1287
229
        if (s->ld_picture) {
1288
31
            s->lowdelay.bytes.num = get_interleaved_ue_golomb(gb);
1289
31
            s->lowdelay.bytes.den = get_interleaved_ue_golomb(gb);
1290
31
            if (s->lowdelay.bytes.den <= 0) {
1291
                av_log(s->avctx,AV_LOG_ERROR,"Invalid lowdelay.bytes.den\n");
1292
                return AVERROR_INVALIDDATA;
1293
            }
1294
198
        } else if (s->hq_picture) {
1295
198
            s->highquality.prefix_bytes = get_interleaved_ue_golomb(gb);
1296
198
            s->highquality.size_scaler  = get_interleaved_ue_golomb(gb);
1297
198
            if (s->highquality.prefix_bytes >= INT_MAX / 8) {
1298
                av_log(s->avctx,AV_LOG_ERROR,"too many prefix bytes\n");
1299
                return AVERROR_INVALIDDATA;
1300
            }
1301
        }
1302
1303
        /* [DIRAC_STD] 11.3.5 Quantisation matrices (low-delay syntax). quant_matrix() */
1304
229
        if (get_bits1(gb)) {
1305
            av_log(s->avctx,AV_LOG_DEBUG,"Low Delay: Has Custom Quantization Matrix!\n");
1306
            /* custom quantization matrix */
1307
            for (level = 0; level < s->wavelet_depth; level++) {
1308
                for (i = !!level; i < 4; i++) {
1309
                    s->lowdelay.quant[level][i] = get_interleaved_ue_golomb(gb);
1310
                }
1311
            }
1312
        } else {
1313
229
            if (s->wavelet_depth > 4) {
1314
                av_log(s->avctx,AV_LOG_ERROR,"Mandatory custom low delay matrix missing for depth %d\n", s->wavelet_depth);
1315
                return AVERROR_INVALIDDATA;
1316
            }
1317
            /* default quantization matrix */
1318
1114
            for (level = 0; level < s->wavelet_depth; level++)
1319
4425
                for (i = 0; i < 4; i++) {
1320
3540
                    s->lowdelay.quant[level][i] = ff_dirac_default_qmat[s->wavelet_idx][level][i];
1321
                    /* haar with no shift differs for different depths */
1322
3540
                    if (s->wavelet_idx == 3)
1323
                        s->lowdelay.quant[level][i] += 4*(s->wavelet_depth-1 - level);
1324
                }
1325
        }
1326
    }
1327
260
    return 0;
1328
}
1329
1330
2320
static inline int pred_sbsplit(uint8_t *sbsplit, int stride, int x, int y)
1331
{
1332
    static const uint8_t avgsplit[7] = { 0, 0, 1, 1, 1, 2, 2 };
1333
1334
2320
    if (!(x|y))
1335
29
        return 0;
1336
2291
    else if (!y)
1337
261
        return sbsplit[-1];
1338
2030
    else if (!x)
1339
203
        return sbsplit[-stride];
1340
1341
1827
    return avgsplit[sbsplit[-1] + sbsplit[-stride] + sbsplit[-stride-1]];
1342
}
1343
1344
8493
static inline int pred_block_mode(DiracBlock *block, int stride, int x, int y, int refmask)
1345
{
1346
    int pred;
1347
1348
8493
    if (!(x|y))
1349
57
        return 0;
1350
8436
    else if (!y)
1351
545
        return block[-1].ref & refmask;
1352
7891
    else if (!x)
1353
399
        return block[-stride].ref & refmask;
1354
1355
    /* return the majority */
1356
7492
    pred = (block[-1].ref & refmask) + (block[-stride].ref & refmask) + (block[-stride-1].ref & refmask);
1357
7492
    return (pred >> 1) & refmask;
1358
}
1359
1360
754
static inline void pred_block_dc(DiracBlock *block, int stride, int x, int y)
1361
{
1362
754
    int i, n = 0;
1363
1364
754
    memset(block->u.dc, 0, sizeof(block->u.dc));
1365
1366

754
    if (x && !(block[-1].ref & 3)) {
1367
1752
        for (i = 0; i < 3; i++)
1368
1314
            block->u.dc[i] += block[-1].u.dc[i];
1369
438
        n++;
1370
    }
1371
1372

754
    if (y && !(block[-stride].ref & 3)) {
1373
1616
        for (i = 0; i < 3; i++)
1374
1212
            block->u.dc[i] += block[-stride].u.dc[i];
1375
404
        n++;
1376
    }
1377
1378

754
    if (x && y && !(block[-1-stride].ref & 3)) {
1379
1372
        for (i = 0; i < 3; i++)
1380
1029
            block->u.dc[i] += block[-1-stride].u.dc[i];
1381
343
        n++;
1382
    }
1383
1384
754
    if (n == 2) {
1385
880
        for (i = 0; i < 3; i++)
1386
660
            block->u.dc[i] = (block->u.dc[i]+1)>>1;
1387
534
    } else if (n == 3) {
1388
656
        for (i = 0; i < 3; i++)
1389
492
            block->u.dc[i] = divide3(block->u.dc[i]);
1390
    }
1391
754
}
1392
1393
5951
static inline void pred_mv(DiracBlock *block, int stride, int x, int y, int ref)
1394
{
1395
    int16_t *pred[3];
1396
5951
    int refmask = ref+1;
1397
5951
    int mask = refmask | DIRAC_REF_MASK_GLOBAL; /*  exclude gmc blocks */
1398
5951
    int n = 0;
1399
1400

5951
    if (x && (block[-1].ref & mask) == refmask)
1401
4890
        pred[n++] = block[-1].u.mv[ref];
1402
1403

5951
    if (y && (block[-stride].ref & mask) == refmask)
1404
4719
        pred[n++] = block[-stride].u.mv[ref];
1405
1406

5951
    if (x && y && (block[-stride-1].ref & mask) == refmask)
1407
4313
        pred[n++] = block[-stride-1].u.mv[ref];
1408
1409

5951
    switch (n) {
1410
304
    case 0:
1411
304
        block->u.mv[ref][0] = 0;
1412
304
        block->u.mv[ref][1] = 0;
1413
304
        break;
1414
1266
    case 1:
1415
1266
        block->u.mv[ref][0] = pred[0][0];
1416
1266
        block->u.mv[ref][1] = pred[0][1];
1417
1266
        break;
1418
487
    case 2:
1419
487
        block->u.mv[ref][0] = (pred[0][0] + pred[1][0] + 1) >> 1;
1420
487
        block->u.mv[ref][1] = (pred[0][1] + pred[1][1] + 1) >> 1;
1421
487
        break;
1422
3894
    case 3:
1423
3894
        block->u.mv[ref][0] = mid_pred(pred[0][0], pred[1][0], pred[2][0]);
1424
3894
        block->u.mv[ref][1] = mid_pred(pred[0][1], pred[1][1], pred[2][1]);
1425
3894
        break;
1426
    }
1427
5951
}
1428
1429
static void global_mv(DiracContext *s, DiracBlock *block, int x, int y, int ref)
1430
{
1431
    int ez      = s->globalmc[ref].zrs_exp;
1432
    int ep      = s->globalmc[ref].perspective_exp;
1433
    int (*A)[2] = s->globalmc[ref].zrs;
1434
    int *b      = s->globalmc[ref].pan_tilt;
1435
    int *c      = s->globalmc[ref].perspective;
1436
1437
    int64_t m   = (1<<ep) - (c[0]*(int64_t)x + c[1]*(int64_t)y);
1438
    int64_t mx  = m * (int64_t)((A[0][0] * (int64_t)x + A[0][1]*(int64_t)y) + (1LL<<ez) * b[0]);
1439
    int64_t my  = m * (int64_t)((A[1][0] * (int64_t)x + A[1][1]*(int64_t)y) + (1LL<<ez) * b[1]);
1440
1441
    block->u.mv[ref][0] = (mx + (1<<(ez+ep))) >> (ez+ep);
1442
    block->u.mv[ref][1] = (my + (1<<(ez+ep))) >> (ez+ep);
1443
}
1444
1445
4348
static void decode_block_params(DiracContext *s, DiracArith arith[8], DiracBlock *block,
1446
                                int stride, int x, int y)
1447
{
1448
    int i;
1449
1450
4348
    block->ref  = pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_REF1);
1451
4348
    block->ref ^= dirac_get_arith_bit(arith, CTX_PMODE_REF1);
1452
1453
4348
    if (s->num_refs == 2) {
1454
4145
        block->ref |= pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_REF2);
1455
4145
        block->ref ^= dirac_get_arith_bit(arith, CTX_PMODE_REF2) << 1;
1456
    }
1457
1458
4348
    if (!block->ref) {
1459
754
        pred_block_dc(block, stride, x, y);
1460
3016
        for (i = 0; i < 3; i++)
1461
2262
            block->u.dc[i] += (unsigned)dirac_get_arith_int(arith+1+i, CTX_DC_F1, CTX_DC_DATA);
1462
754
        return;
1463
    }
1464
1465
3594
    if (s->globalmc_flag) {
1466
        block->ref |= pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_GLOBAL);
1467
        block->ref ^= dirac_get_arith_bit(arith, CTX_GLOBAL_BLOCK) << 2;
1468
    }
1469
1470
10636
    for (i = 0; i < s->num_refs; i++)
1471
7042
        if (block->ref & (i+1)) {
1472
5951
            if (block->ref & DIRAC_REF_MASK_GLOBAL) {
1473
                global_mv(s, block, x, y, i);
1474
            } else {
1475
5951
                pred_mv(block, stride, x, y, i);
1476
5951
                block->u.mv[i][0] += (unsigned)dirac_get_arith_int(arith + 4 + 2 * i, CTX_MV_F1, CTX_MV_DATA);
1477
5951
                block->u.mv[i][1] += (unsigned)dirac_get_arith_int(arith + 5 + 2 * i, CTX_MV_F1, CTX_MV_DATA);
1478
            }
1479
        }
1480
}
1481
1482
/**
1483
 * Copies the current block to the other blocks covered by the current superblock split mode
1484
 */
1485
4348
static void propagate_block_data(DiracBlock *block, int stride, int size)
1486
{
1487
    int x, y;
1488
4348
    DiracBlock *dst = block;
1489
1490
11112
    for (x = 1; x < size; x++)
1491
6764
        dst[x] = *block;
1492
1493
11112
    for (y = 1; y < size; y++) {
1494
6764
        dst += stride;
1495
32772
        for (x = 0; x < size; x++)
1496
26008
            dst[x] = *block;
1497
    }
1498
4348
}
1499
1500
/**
1501
 * Dirac Specification ->
1502
 * 12. Block motion data syntax
1503
 */
1504
29
static int dirac_unpack_block_motion_data(DiracContext *s)
1505
{
1506
29
    GetBitContext *gb = &s->gb;
1507
29
    uint8_t *sbsplit = s->sbsplit;
1508
    int i, x, y, q, p;
1509
    DiracArith arith[8];
1510
1511
29
    align_get_bits(gb);
1512
1513
    /* [DIRAC_STD] 11.2.4 and 12.2.1 Number of blocks and superblocks */
1514
29
    s->sbwidth  = DIVRNDUP(s->seq.width,  4*s->plane[0].xbsep);
1515
29
    s->sbheight = DIVRNDUP(s->seq.height, 4*s->plane[0].ybsep);
1516
29
    s->blwidth  = 4 * s->sbwidth;
1517
29
    s->blheight = 4 * s->sbheight;
1518
1519
    /* [DIRAC_STD] 12.3.1 Superblock splitting modes. superblock_split_modes()
1520
       decode superblock split modes */
1521
29
    ff_dirac_init_arith_decoder(arith, gb, get_interleaved_ue_golomb(gb));     /* get_interleaved_ue_golomb(gb) is the length */
1522
261
    for (y = 0; y < s->sbheight; y++) {
1523
2552
        for (x = 0; x < s->sbwidth; x++) {
1524
2320
            unsigned int split  = dirac_get_arith_uint(arith, CTX_SB_F1, CTX_SB_DATA);
1525
2320
            if (split > 2)
1526
                return AVERROR_INVALIDDATA;
1527
2320
            sbsplit[x] = (split + pred_sbsplit(sbsplit+x, s->sbwidth, x, y)) % 3;
1528
        }
1529
232
        sbsplit += s->sbwidth;
1530
    }
1531
1532
    /* setup arith decoding */
1533
29
    ff_dirac_init_arith_decoder(arith, gb, get_interleaved_ue_golomb(gb));
1534
86
    for (i = 0; i < s->num_refs; i++) {
1535
57
        ff_dirac_init_arith_decoder(arith + 4 + 2 * i, gb, get_interleaved_ue_golomb(gb));
1536
57
        ff_dirac_init_arith_decoder(arith + 5 + 2 * i, gb, get_interleaved_ue_golomb(gb));
1537
    }
1538
116
    for (i = 0; i < 3; i++)
1539
87
        ff_dirac_init_arith_decoder(arith+1+i, gb, get_interleaved_ue_golomb(gb));
1540
1541
261
    for (y = 0; y < s->sbheight; y++)
1542
2552
        for (x = 0; x < s->sbwidth; x++) {
1543
2320
            int blkcnt = 1 << s->sbsplit[y * s->sbwidth + x];
1544
2320
            int step   = 4 >> s->sbsplit[y * s->sbwidth + x];
1545
1546
5098
            for (q = 0; q < blkcnt; q++)
1547
7126
                for (p = 0; p < blkcnt; p++) {
1548
4348
                    int bx = 4 * x + p*step;
1549
4348
                    int by = 4 * y + q*step;
1550
4348
                    DiracBlock *block = &s->blmotion[by*s->blwidth + bx];
1551
4348
                    decode_block_params(s, arith, block, s->blwidth, bx, by);
1552
4348
                    propagate_block_data(block, s->blwidth, step);
1553
                }
1554
        }
1555
1556
259
    for (i = 0; i < 4 + 2*s->num_refs; i++) {
1557
230
        if (arith[i].error)
1558
            return arith[i].error;
1559
    }
1560
1561
29
    return 0;
1562
}
1563
1564
72384
static int weight(int i, int blen, int offset)
1565
{
1566
#define ROLLOFF(i) offset == 1 ? ((i) ? 5 : 3) :        \
1567
    (1 + (6*(i) + offset - 1) / (2*offset - 1))
1568
1569
72384
    if (i < 2*offset)
1570

36192
        return ROLLOFF(i);
1571
36192
    else if (i > blen-1 - 2*offset)
1572

36192
        return ROLLOFF(blen-1 - i);
1573
    return 8;
1574
}
1575
1576
8352
static void init_obmc_weight_row(Plane *p, uint8_t *obmc_weight, int stride,
1577
                                 int left, int right, int wy)
1578
{
1579
    int x;
1580

25056
    for (x = 0; left && x < p->xblen >> 1; x++)
1581
16704
        obmc_weight[x] = wy*8;
1582
75168
    for (; x < p->xblen >> right; x++)
1583
66816
        obmc_weight[x] = wy*weight(x, p->xblen, p->xoffset);
1584
25056
    for (; x < p->xblen; x++)
1585
16704
        obmc_weight[x] = wy*8;
1586
175392
    for (; x < stride; x++)
1587
167040
        obmc_weight[x] = 0;
1588
8352
}
1589
1590
783
static void init_obmc_weight(Plane *p, uint8_t *obmc_weight, int stride,
1591
                             int left, int right, int top, int bottom)
1592
{
1593
    int y;
1594

2175
    for (y = 0; top && y < p->yblen >> 1; y++) {
1595
1392
        init_obmc_weight_row(p, obmc_weight, stride, left, right, 8);
1596
1392
        obmc_weight += stride;
1597
    }
1598
6351
    for (; y < p->yblen >> bottom; y++) {
1599
5568
        int wy = weight(y, p->yblen, p->yoffset);
1600
5568
        init_obmc_weight_row(p, obmc_weight, stride, left, right, wy);
1601
5568
        obmc_weight += stride;
1602
    }
1603
2175
    for (; y < p->yblen; y++) {
1604
1392
        init_obmc_weight_row(p, obmc_weight, stride, left, right, 8);
1605
1392
        obmc_weight += stride;
1606
    }
1607
783
}
1608
1609
2784
static void init_obmc_weights(DiracContext *s, Plane *p, int by)
1610
{
1611
2784
    int top = !by;
1612
2784
    int bottom = by == s->blheight-1;
1613
1614
    /* don't bother re-initing for rows 2 to blheight-2, the weights don't change */
1615

2784
    if (top || bottom || by == 1) {
1616
261
        init_obmc_weight(p, s->obmc_weight[0], MAX_BLOCKSIZE, 1, 0, top, bottom);
1617
261
        init_obmc_weight(p, s->obmc_weight[1], MAX_BLOCKSIZE, 0, 0, top, bottom);
1618
261
        init_obmc_weight(p, s->obmc_weight[2], MAX_BLOCKSIZE, 0, 1, top, bottom);
1619
    }
1620
2784
}
1621
1622
static const uint8_t epel_weights[4][4][4] = {
1623
    {{ 16,  0,  0,  0 },
1624
     { 12,  4,  0,  0 },
1625
     {  8,  8,  0,  0 },
1626
     {  4, 12,  0,  0 }},
1627
    {{ 12,  0,  4,  0 },
1628
     {  9,  3,  3,  1 },
1629
     {  6,  6,  2,  2 },
1630
     {  3,  9,  1,  3 }},
1631
    {{  8,  0,  8,  0 },
1632
     {  6,  2,  6,  2 },
1633
     {  4,  4,  4,  4 },
1634
     {  2,  6,  2,  6 }},
1635
    {{  4,  0, 12,  0 },
1636
     {  3,  1,  9,  3 },
1637
     {  2,  2,  6,  6 },
1638
     {  1,  3,  3,  9 }}
1639
};
1640
1641
/**
1642
 * For block x,y, determine which of the hpel planes to do bilinear
1643
 * interpolation from and set src[] to the location in each hpel plane
1644
 * to MC from.
1645
 *
1646
 * @return the index of the put_dirac_pixels_tab function to use
1647
 *  0 for 1 plane (fpel,hpel), 1 for 2 planes (qpel), 2 for 4 planes (qpel), and 3 for epel
1648
 */
1649
199452
static int mc_subpel(DiracContext *s, DiracBlock *block, const uint8_t *src[5],
1650
                     int x, int y, int ref, int plane)
1651
{
1652
199452
    Plane *p = &s->plane[plane];
1653
199452
    uint8_t **ref_hpel = s->ref_pics[ref]->hpel[plane];
1654
199452
    int motion_x = block->u.mv[ref][0];
1655
199452
    int motion_y = block->u.mv[ref][1];
1656
199452
    int mx, my, i, epel, nplanes = 0;
1657
1658
199452
    if (plane) {
1659
132968
        motion_x >>= s->chroma_x_shift;
1660
132968
        motion_y >>= s->chroma_y_shift;
1661
    }
1662
1663
199452
    mx         = motion_x & ~(-1U << s->mv_precision);
1664
199452
    my         = motion_y & ~(-1U << s->mv_precision);
1665
199452
    motion_x >>= s->mv_precision;
1666
199452
    motion_y >>= s->mv_precision;
1667
    /* normalize subpel coordinates to epel */
1668
    /* TODO: template this function? */
1669
199452
    mx      <<= 3 - s->mv_precision;
1670
199452
    my      <<= 3 - s->mv_precision;
1671
1672
199452
    x += motion_x;
1673
199452
    y += motion_y;
1674
199452
    epel = (mx|my)&1;
1675
1676
    /* hpel position */
1677
199452
    if (!((mx|my)&3)) {
1678
199452
        nplanes = 1;
1679
199452
        src[0] = ref_hpel[(my>>1)+(mx>>2)] + y*p->stride + x;
1680
    } else {
1681
        /* qpel or epel */
1682
        nplanes = 4;
1683
        for (i = 0; i < 4; i++)
1684
            src[i] = ref_hpel[i] + y*p->stride + x;
1685
1686
        /* if we're interpolating in the right/bottom halves, adjust the planes as needed
1687
           we increment x/y because the edge changes for half of the pixels */
1688
        if (mx > 4) {
1689
            src[0] += 1;
1690
            src[2] += 1;
1691
            x++;
1692
        }
1693
        if (my > 4) {
1694
            src[0] += p->stride;
1695
            src[1] += p->stride;
1696
            y++;
1697
        }
1698
1699
        /* hpel planes are:
1700
           [0]: F  [1]: H
1701
           [2]: V  [3]: C */
1702
        if (!epel) {
1703
            /* check if we really only need 2 planes since either mx or my is
1704
               a hpel position. (epel weights of 0 handle this there) */
1705
            if (!(mx&3)) {
1706
                /* mx == 0: average [0] and [2]
1707
                   mx == 4: average [1] and [3] */
1708
                src[!mx] = src[2 + !!mx];
1709
                nplanes = 2;
1710
            } else if (!(my&3)) {
1711
                src[0] = src[(my>>1)  ];
1712
                src[1] = src[(my>>1)+1];
1713
                nplanes = 2;
1714
            }
1715
        } else {
1716
            /* adjust the ordering if needed so the weights work */
1717
            if (mx > 4) {
1718
                FFSWAP(const uint8_t *, src[0], src[1]);
1719
                FFSWAP(const uint8_t *, src[2], src[3]);
1720
            }
1721
            if (my > 4) {
1722
                FFSWAP(const uint8_t *, src[0], src[2]);
1723
                FFSWAP(const uint8_t *, src[1], src[3]);
1724
            }
1725
            src[4] = epel_weights[my&3][mx&3];
1726
        }
1727
    }
1728
1729
    /* fixme: v/h _edge_pos */
1730
199452
    if (x + p->xblen > p->width +EDGE_WIDTH/2 ||
1731

199293
        y + p->yblen > p->height+EDGE_WIDTH/2 ||
1732
191702
        x < 0 || y < 0) {
1733
27830
        for (i = 0; i < nplanes; i++) {
1734
13915
            s->vdsp.emulated_edge_mc(s->edge_emu_buffer[i], src[i],
1735
                                     p->stride, p->stride,
1736
13915
                                     p->xblen, p->yblen, x, y,
1737
13915
                                     p->width+EDGE_WIDTH/2, p->height+EDGE_WIDTH/2);
1738
13915
            src[i] = s->edge_emu_buffer[i];
1739
        }
1740
    }
1741
199452
    return (nplanes>>1) + epel;
1742
}
1743
1744
2262
static void add_dc(uint16_t *dst, int dc, int stride,
1745
                   uint8_t *obmc_weight, int xblen, int yblen)
1746
{
1747
    int x, y;
1748
2262
    dc += 128;
1749
1750
26390
    for (y = 0; y < yblen; y++) {
1751
168896
        for (x = 0; x < xblen; x += 2) {
1752
144768
            dst[x  ] += dc * obmc_weight[x  ];
1753
144768
            dst[x+1] += dc * obmc_weight[x+1];
1754
        }
1755
24128
        dst          += stride;
1756
24128
        obmc_weight  += MAX_BLOCKSIZE;
1757
    }
1758
2262
}
1759
1760
107880
static void block_mc(DiracContext *s, DiracBlock *block,
1761
                     uint16_t *mctmp, uint8_t *obmc_weight,
1762
                     int plane, int dstx, int dsty)
1763
{
1764
107880
    Plane *p = &s->plane[plane];
1765
    const uint8_t *src[5];
1766
    int idx;
1767
1768

107880
    switch (block->ref&3) {
1769
2262
    case 0: /* DC */
1770
2262
        add_dc(mctmp, block->u.dc[plane], p->stride, obmc_weight, p->xblen, p->yblen);
1771
2262
        return;
1772
11784
    case 1:
1773
    case 2:
1774
11784
        idx = mc_subpel(s, block, src, dstx, dsty, (block->ref&3)-1, plane);
1775
11784
        s->put_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen);
1776
11784
        if (s->weight_func)
1777
            s->weight_func(s->mcscratch, p->stride, s->weight_log2denom,
1778
                           s->weight[0] + s->weight[1], p->yblen);
1779
11784
        break;
1780
93834
    case 3:
1781
93834
        idx = mc_subpel(s, block, src, dstx, dsty, 0, plane);
1782
93834
        s->put_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen);
1783
93834
        idx = mc_subpel(s, block, src, dstx, dsty, 1, plane);
1784
93834
        if (s->biweight_func) {
1785
            /* fixme: +32 is a quick hack */
1786
            s->put_pixels_tab[idx](s->mcscratch + 32, src, p->stride, p->yblen);
1787
            s->biweight_func(s->mcscratch, s->mcscratch+32, p->stride, s->weight_log2denom,
1788
                             s->weight[0], s->weight[1], p->yblen);
1789
        } else
1790
93834
            s->avg_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen);
1791
93834
        break;
1792
    }
1793
105618
    s->add_obmc(mctmp, s->mcscratch, p->stride, obmc_weight, p->yblen);
1794
}
1795
1796
2697
static void mc_row(DiracContext *s, DiracBlock *block, uint16_t *mctmp, int plane, int dsty)
1797
{
1798
2697
    Plane *p = &s->plane[plane];
1799
2697
    int x, dstx = p->xbsep - p->xoffset;
1800
1801
2697
    block_mc(s, block, mctmp, s->obmc_weight[0], plane, -p->xoffset, dsty);
1802
2697
    mctmp += p->xbsep;
1803
1804
105183
    for (x = 1; x < s->blwidth-1; x++) {
1805
102486
        block_mc(s, block+x, mctmp, s->obmc_weight[1], plane, dstx, dsty);
1806
102486
        dstx  += p->xbsep;
1807
102486
        mctmp += p->xbsep;
1808
    }
1809
2697
    block_mc(s, block+x, mctmp, s->obmc_weight[2], plane, dstx, dsty);
1810
2697
}
1811
1812
87
static void select_dsp_funcs(DiracContext *s, int width, int height, int xblen, int yblen)
1813
{
1814
87
    int idx = 0;
1815
87
    if (xblen > 8)
1816
29
        idx = 1;
1817
87
    if (xblen > 16)
1818
        idx = 2;
1819
1820
87
    memcpy(s->put_pixels_tab, s->diracdsp.put_dirac_pixels_tab[idx], sizeof(s->put_pixels_tab));
1821
87
    memcpy(s->avg_pixels_tab, s->diracdsp.avg_dirac_pixels_tab[idx], sizeof(s->avg_pixels_tab));
1822
87
    s->add_obmc = s->diracdsp.add_dirac_obmc[idx];
1823

87
    if (s->weight_log2denom > 1 || s->weight[0] != 1 || s->weight[1] != 1) {
1824
        s->weight_func   = s->diracdsp.weight_dirac_pixels_tab[idx];
1825
        s->biweight_func = s->diracdsp.biweight_dirac_pixels_tab[idx];
1826
    } else {
1827
87
        s->weight_func   = NULL;
1828
87
        s->biweight_func = NULL;
1829
    }
1830
87
}
1831
1832
171
static int interpolate_refplane(DiracContext *s, DiracFrame *ref, int plane, int width, int height)
1833
{
1834
    /* chroma allocates an edge of 8 when subsampled
1835
       which for 4:2:2 means an h edge of 16 and v edge of 8
1836
       just use 8 for everything for the moment */
1837
171
    int i, edge = EDGE_WIDTH/2;
1838
1839
171
    ref->hpel[plane][0] = ref->avframe->data[plane];
1840
171
    s->mpvencdsp.draw_edges(ref->hpel[plane][0], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM); /* EDGE_TOP | EDGE_BOTTOM values just copied to make it build, this needs to be ensured */
1841
1842
    /* no need for hpel if we only have fpel vectors */
1843
171
    if (!s->mv_precision)
1844
171
        return 0;
1845
1846
    for (i = 1; i < 4; i++) {
1847
        if (!ref->hpel_base[plane][i])
1848
            ref->hpel_base[plane][i] = av_malloc((height+2*edge) * ref->avframe->linesize[plane] + 32);
1849
        if (!ref->hpel_base[plane][i]) {
1850
            return AVERROR(ENOMEM);
1851
        }
1852
        /* we need to be 16-byte aligned even for chroma */
1853
        ref->hpel[plane][i] = ref->hpel_base[plane][i] + edge*ref->avframe->linesize[plane] + 16;
1854
    }
1855
1856
    if (!ref->interpolated[plane]) {
1857
        s->diracdsp.dirac_hpel_filter(ref->hpel[plane][1], ref->hpel[plane][2],
1858
                                      ref->hpel[plane][3], ref->hpel[plane][0],
1859
                                      ref->avframe->linesize[plane], width, height);
1860
        s->mpvencdsp.draw_edges(ref->hpel[plane][1], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);
1861
        s->mpvencdsp.draw_edges(ref->hpel[plane][2], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);
1862
        s->mpvencdsp.draw_edges(ref->hpel[plane][3], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);
1863
    }
1864
    ref->interpolated[plane] = 1;
1865
1866
    return 0;
1867
}
1868
1869
/**
1870
 * Dirac Specification ->
1871
 * 13.0 Transform data syntax. transform_data()
1872
 */
1873
260
static int dirac_decode_frame_internal(DiracContext *s)
1874
{
1875
    DWTContext d;
1876
    int y, i, comp, dsty;
1877
    int ret;
1878
1879
260
    if (s->low_delay) {
1880
        /* [DIRAC_STD] 13.5.1 low_delay_transform_data() */
1881
229
        if (!s->hq_picture) {
1882
124
            for (comp = 0; comp < 3; comp++) {
1883
93
                Plane *p = &s->plane[comp];
1884
93
                memset(p->idwt.buf, 0, p->idwt.stride * p->idwt.height);
1885
            }
1886
        }
1887
229
        if (!s->zero_res) {
1888
229
            if ((ret = decode_lowdelay(s)) < 0)
1889
                return ret;
1890
        }
1891
    }
1892
1893
1040
    for (comp = 0; comp < 3; comp++) {
1894
780
        Plane *p       = &s->plane[comp];
1895
780
        uint8_t *frame = s->current_picture->avframe->data[comp];
1896
1897
        /* FIXME: small resolutions */
1898
3900
        for (i = 0; i < 4; i++)
1899
3120
            s->edge_emu_buffer[i] = s->edge_emu_buffer_base + i*FFALIGN(p->width, 16);
1900
1901

780
        if (!s->zero_res && !s->low_delay)
1902
        {
1903
93
            memset(p->idwt.buf, 0, p->idwt.stride * p->idwt.height);
1904
93
            ret = decode_component(s, comp); /* [DIRAC_STD] 13.4.1 core_transform_data() */
1905
93
            if (ret < 0)
1906
                return ret;
1907
        }
1908
780
        ret = ff_spatial_idwt_init(&d, &p->idwt, s->wavelet_idx+2,
1909
780
                                   s->wavelet_depth, s->bit_depth);
1910
780
        if (ret < 0)
1911
            return ret;
1912
1913
780
        if (!s->num_refs) { /* intra */
1914
11436
            for (y = 0; y < p->height; y += 16) {
1915
10743
                int idx = (s->bit_depth - 8) >> 1;
1916
10743
                ff_spatial_idwt_slice2(&d, y+16); /* decode */
1917
10743
                s->diracdsp.put_signed_rect_clamped[idx](frame + y*p->stride,
1918
10743
                                                         p->stride,
1919
10743
                                                         p->idwt.buf + y*p->idwt.stride,
1920
                                                         p->idwt.stride, p->width, 16);
1921
            }
1922
        } else { /* inter */
1923
87
            int rowheight = p->ybsep*p->stride;
1924
1925
87
            select_dsp_funcs(s, p->width, p->height, p->xblen, p->yblen);
1926
1927
258
            for (i = 0; i < s->num_refs; i++) {
1928
171
                int ret = interpolate_refplane(s, s->ref_pics[i], comp, p->width, p->height);
1929
171
                if (ret < 0)
1930
                    return ret;
1931
            }
1932
1933
87
            memset(s->mctmp, 0, 4*p->yoffset*p->stride);
1934
1935
87
            dsty = -p->yoffset;
1936
2784
            for (y = 0; y < s->blheight; y++) {
1937
2784
                int h     = 0,
1938
2784
                    start = FFMAX(dsty, 0);
1939
2784
                uint16_t *mctmp    = s->mctmp + y*rowheight;
1940
2784
                DiracBlock *blocks = s->blmotion + y*s->blwidth;
1941
1942
2784
                init_obmc_weights(s, p, y);
1943
1944

2784
                if (y == s->blheight-1 || start+p->ybsep > p->height)
1945
174
                    h = p->height - start;
1946
                else
1947
2610
                    h = p->ybsep - (start - dsty);
1948
2784
                if (h < 0)
1949
87
                    break;
1950
1951
2697
                memset(mctmp+2*p->yoffset*p->stride, 0, 2*rowheight);
1952
2697
                mc_row(s, blocks, mctmp, comp, dsty);
1953
1954
2697
                mctmp += (start - dsty)*p->stride + p->xoffset;
1955
2697
                ff_spatial_idwt_slice2(&d, start + h); /* decode */
1956
                /* NOTE: add_rect_clamped hasn't been templated hence the shifts.
1957
                 * idwt.stride is passed as pixels, not in bytes as in the rest of the decoder */
1958
2697
                s->diracdsp.add_rect_clamped(frame + start*p->stride, mctmp, p->stride,
1959
2697
                                             (int16_t*)(p->idwt.buf) + start*(p->idwt.stride >> 1), (p->idwt.stride >> 1), p->width, h);
1960
1961
2697
                dsty += p->ybsep;
1962
            }
1963
        }
1964
    }
1965
1966
1967
260
    return 0;
1968
}
1969
1970
260
static int get_buffer_with_edge(AVCodecContext *avctx, AVFrame *f, int flags)
1971
{
1972
    int ret, i;
1973
    int chroma_x_shift, chroma_y_shift;
1974
260
    ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &chroma_x_shift,
1975
                                           &chroma_y_shift);
1976
260
    if (ret < 0)
1977
        return ret;
1978
1979
260
    f->width  = avctx->width  + 2 * EDGE_WIDTH;
1980
260
    f->height = avctx->height + 2 * EDGE_WIDTH + 2;
1981
260
    ret = ff_get_buffer(avctx, f, flags);
1982
260
    if (ret < 0)
1983
        return ret;
1984
1985
1040
    for (i = 0; f->data[i]; i++) {
1986

780
        int offset = (EDGE_WIDTH >> (i && i<3 ? chroma_y_shift : 0)) *
1987
780
                     f->linesize[i] + 32;
1988
780
        f->data[i] += offset;
1989
    }
1990
260
    f->width  = avctx->width;
1991
260
    f->height = avctx->height;
1992
1993
260
    return 0;
1994
}
1995
1996
/**
1997
 * Dirac Specification ->
1998
 * 11.1.1 Picture Header. picture_header()
1999
 */
2000
260
static int dirac_decode_picture_header(DiracContext *s)
2001
{
2002
    unsigned retire, picnum;
2003
    int i, j, ret;
2004
    int64_t refdist, refnum;
2005
260
    GetBitContext *gb = &s->gb;
2006
2007
    /* [DIRAC_STD] 11.1.1 Picture Header. picture_header() PICTURE_NUM */
2008
260
    picnum = s->current_picture->avframe->display_picture_number = get_bits_long(gb, 32);
2009
2010
2011
260
    av_log(s->avctx,AV_LOG_DEBUG,"PICTURE_NUM: %d\n",picnum);
2012
2013
    /* if this is the first keyframe after a sequence header, start our
2014
       reordering from here */
2015
260
    if (s->frame_number < 0)
2016
70
        s->frame_number = picnum;
2017
2018
260
    s->ref_pics[0] = s->ref_pics[1] = NULL;
2019
317
    for (i = 0; i < s->num_refs; i++) {
2020
57
        refnum = (picnum + dirac_get_se_golomb(gb)) & 0xFFFFFFFF;
2021
57
        refdist = INT64_MAX;
2022
2023
        /* find the closest reference to the one we want */
2024
        /* Jordi: this is needed if the referenced picture hasn't yet arrived */
2025

184
        for (j = 0; j < MAX_REFERENCE_FRAMES && refdist; j++)
2026
127
            if (s->ref_frames[j]
2027
127
                && FFABS(s->ref_frames[j]->avframe->display_picture_number - refnum) < refdist) {
2028
127
                s->ref_pics[i] = s->ref_frames[j];
2029
127
                refdist = FFABS(s->ref_frames[j]->avframe->display_picture_number - refnum);
2030
            }
2031
2032

57
        if (!s->ref_pics[i] || refdist)
2033
            av_log(s->avctx, AV_LOG_DEBUG, "Reference not found\n");
2034
2035
        /* if there were no references at all, allocate one */
2036
57
        if (!s->ref_pics[i])
2037
            for (j = 0; j < MAX_FRAMES; j++)
2038
                if (!s->all_frames[j].avframe->data[0]) {
2039
                    s->ref_pics[i] = &s->all_frames[j];
2040
                    ret = get_buffer_with_edge(s->avctx, s->ref_pics[i]->avframe, AV_GET_BUFFER_FLAG_REF);
2041
                    if (ret < 0)
2042
                        return ret;
2043
                    break;
2044
                }
2045
2046
57
        if (!s->ref_pics[i]) {
2047
            av_log(s->avctx, AV_LOG_ERROR, "Reference could not be allocated\n");
2048
            return AVERROR_INVALIDDATA;
2049
        }
2050
2051
    }
2052
2053
    /* retire the reference frames that are not used anymore */
2054
260
    if (s->current_picture->reference) {
2055
10
        retire = (picnum + dirac_get_se_golomb(gb)) & 0xFFFFFFFF;
2056
10
        if (retire != picnum) {
2057
6
            DiracFrame *retire_pic = remove_frame(s->ref_frames, retire);
2058
2059
6
            if (retire_pic)
2060
6
                retire_pic->reference &= DELAYED_PIC_REF;
2061
            else
2062
                av_log(s->avctx, AV_LOG_DEBUG, "Frame to retire not found\n");
2063
        }
2064
2065
        /* if reference array is full, remove the oldest as per the spec */
2066
10
        while (add_frame(s->ref_frames, MAX_REFERENCE_FRAMES, s->current_picture)) {
2067
            av_log(s->avctx, AV_LOG_ERROR, "Reference frame overflow\n");
2068
            remove_frame(s->ref_frames, s->ref_frames[0]->avframe->display_picture_number)->reference &= DELAYED_PIC_REF;
2069
        }
2070
    }
2071
2072
260
    if (s->num_refs) {
2073
29
        ret = dirac_unpack_prediction_parameters(s);  /* [DIRAC_STD] 11.2 Picture Prediction Data. picture_prediction() */
2074
29
        if (ret < 0)
2075
            return ret;
2076
29
        ret = dirac_unpack_block_motion_data(s);      /* [DIRAC_STD] 12. Block motion data syntax                       */
2077
29
        if (ret < 0)
2078
            return ret;
2079
    }
2080
260
    ret = dirac_unpack_idwt_params(s);                /* [DIRAC_STD] 11.3 Wavelet transform data                        */
2081
260
    if (ret < 0)
2082
        return ret;
2083
2084
260
    init_planes(s);
2085
260
    return 0;
2086
}
2087
2088
36
static int get_delayed_pic(DiracContext *s, AVFrame *picture, int *got_frame)
2089
{
2090
36
    DiracFrame *out = s->delay_frames[0];
2091
36
    int i, out_idx  = 0;
2092
    int ret;
2093
2094
    /* find frame with lowest picture number */
2095
36
    for (i = 1; s->delay_frames[i]; i++)
2096
        if (s->delay_frames[i]->avframe->display_picture_number < out->avframe->display_picture_number) {
2097
            out     = s->delay_frames[i];
2098
            out_idx = i;
2099
        }
2100
2101
37
    for (i = out_idx; s->delay_frames[i]; i++)
2102
1
        s->delay_frames[i] = s->delay_frames[i+1];
2103
2104
36
    if (out) {
2105
1
        out->reference ^= DELAYED_PIC_REF;
2106
1
        if((ret = av_frame_ref(picture, out->avframe)) < 0)
2107
            return ret;
2108
1
        *got_frame = 1;
2109
    }
2110
2111
36
    return 0;
2112
}
2113
2114
/**
2115
 * Dirac Specification ->
2116
 * 9.6 Parse Info Header Syntax. parse_info()
2117
 * 4 byte start code + byte parse code + 4 byte size + 4 byte previous size
2118
 */
2119
#define DATA_UNIT_HEADER_SIZE 13
2120
2121
/* [DIRAC_STD] dirac_decode_data_unit makes reference to the while defined in 9.3
2122
   inside the function parse_sequence() */
2123
757
static int dirac_decode_data_unit(AVCodecContext *avctx, const uint8_t *buf, int size)
2124
{
2125
757
    DiracContext *s   = avctx->priv_data;
2126
757
    DiracFrame *pic   = NULL;
2127
    AVDiracSeqHeader *dsh;
2128
    int ret, i;
2129
    uint8_t parse_code;
2130
    unsigned tmp;
2131
2132
757
    if (size < DATA_UNIT_HEADER_SIZE)
2133
        return AVERROR_INVALIDDATA;
2134
2135
757
    parse_code = buf[4];
2136
2137
757
    init_get_bits(&s->gb, &buf[13], 8*(size - DATA_UNIT_HEADER_SIZE));
2138
2139
757
    if (parse_code == DIRAC_PCODE_SEQ_HEADER) {
2140
231
        if (s->seen_sequence_header)
2141
161
            return 0;
2142
2143
        /* [DIRAC_STD] 10. Sequence header */
2144
70
        ret = av_dirac_parse_sequence_header(&dsh, buf + DATA_UNIT_HEADER_SIZE, size - DATA_UNIT_HEADER_SIZE, avctx);
2145
70
        if (ret < 0) {
2146
            av_log(avctx, AV_LOG_ERROR, "error parsing sequence header");
2147
            return ret;
2148
        }
2149
2150
70
        if (CALC_PADDING((int64_t)dsh->width, MAX_DWT_LEVELS) * CALC_PADDING((int64_t)dsh->height, MAX_DWT_LEVELS) * 5LL > avctx->max_pixels)
2151
            ret = AVERROR(ERANGE);
2152
70
        if (ret >= 0)
2153
70
            ret = ff_set_dimensions(avctx, dsh->width, dsh->height);
2154
70
        if (ret < 0) {
2155
            av_freep(&dsh);
2156
            return ret;
2157
        }
2158
2159
70
        ff_set_sar(avctx, dsh->sample_aspect_ratio);
2160
70
        avctx->pix_fmt         = dsh->pix_fmt;
2161
70
        avctx->color_range     = dsh->color_range;
2162
70
        avctx->color_trc       = dsh->color_trc;
2163
70
        avctx->color_primaries = dsh->color_primaries;
2164
70
        avctx->colorspace      = dsh->colorspace;
2165
70
        avctx->profile         = dsh->profile;
2166
70
        avctx->level           = dsh->level;
2167
70
        avctx->framerate       = dsh->framerate;
2168
70
        s->bit_depth           = dsh->bit_depth;
2169
70
        s->version.major       = dsh->version.major;
2170
70
        s->version.minor       = dsh->version.minor;
2171
70
        s->seq                 = *dsh;
2172
70
        av_freep(&dsh);
2173
2174
70
        s->pshift = s->bit_depth > 8;
2175
2176
70
        ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt,
2177
                                               &s->chroma_x_shift,
2178
                                               &s->chroma_y_shift);
2179
70
        if (ret < 0)
2180
            return ret;
2181
2182
70
        ret = alloc_sequence_buffers(s);
2183
70
        if (ret < 0)
2184
            return ret;
2185
2186
70
        s->seen_sequence_header = 1;
2187
526
    } else if (parse_code == DIRAC_PCODE_END_SEQ) { /* [DIRAC_STD] End of Sequence */
2188
        free_sequence_buffers(s);
2189
        s->seen_sequence_header = 0;
2190
526
    } else if (parse_code == DIRAC_PCODE_AUX) {
2191
266
        if (buf[13] == 1) {     /* encoder implementation/version */
2192
            int ver[3];
2193
            /* versions older than 1.0.8 don't store quant delta for
2194
               subbands with only one codeblock */
2195
4
            if (sscanf(buf+14, "Schroedinger %d.%d.%d", ver, ver+1, ver+2) == 3)
2196

4
                if (ver[0] == 1 && ver[1] == 0 && ver[2] <= 7)
2197
                    s->old_delta_quant = 1;
2198
        }
2199
260
    } else if (parse_code & 0x8) {  /* picture data unit */
2200
260
        if (!s->seen_sequence_header) {
2201
            av_log(avctx, AV_LOG_DEBUG, "Dropping frame without sequence header\n");
2202
            return AVERROR_INVALIDDATA;
2203
        }
2204
2205
        /* find an unused frame */
2206
3900
        for (i = 0; i < MAX_FRAMES; i++)
2207
3640
            if (s->all_frames[i].avframe->data[0] == NULL)
2208
3559
                pic = &s->all_frames[i];
2209
260
        if (!pic) {
2210
            av_log(avctx, AV_LOG_ERROR, "framelist full\n");
2211
            return AVERROR_INVALIDDATA;
2212
        }
2213
2214
260
        av_frame_unref(pic->avframe);
2215
2216
        /* [DIRAC_STD] Defined in 9.6.1 ... */
2217
260
        tmp            =  parse_code & 0x03;                   /* [DIRAC_STD] num_refs()      */
2218
260
        if (tmp > 2) {
2219
            av_log(avctx, AV_LOG_ERROR, "num_refs of 3\n");
2220
            return AVERROR_INVALIDDATA;
2221
        }
2222
260
        s->num_refs      = tmp;
2223
260
        s->is_arith      = (parse_code & 0x48) == 0x08;          /* [DIRAC_STD] using_ac()            */
2224
260
        s->low_delay     = (parse_code & 0x88) == 0x88;          /* [DIRAC_STD] is_low_delay()        */
2225
260
        s->core_syntax   = (parse_code & 0x88) == 0x08;          /* [DIRAC_STD] is_core_syntax()      */
2226
260
        s->ld_picture    = (parse_code & 0xF8) == 0xC8;          /* [DIRAC_STD] is_ld_picture()       */
2227
260
        s->hq_picture    = (parse_code & 0xF8) == 0xE8;          /* [DIRAC_STD] is_hq_picture()       */
2228
260
        s->dc_prediction = (parse_code & 0x28) == 0x08;          /* [DIRAC_STD] using_dc_prediction() */
2229
260
        pic->reference   = (parse_code & 0x0C) == 0x0C;          /* [DIRAC_STD] is_reference()        */
2230
260
        pic->avframe->key_frame = s->num_refs == 0;              /* [DIRAC_STD] is_intra()            */
2231
260
        pic->avframe->pict_type = s->num_refs + 1;               /* Definition of AVPictureType in avutil.h */
2232
2233
        /* VC-2 Low Delay has a different parse code than the Dirac Low Delay */
2234

260
        if (s->version.minor == 2 && parse_code == 0x88)
2235
31
            s->ld_picture = 1;
2236
2237

260
        if (s->low_delay && !(s->ld_picture || s->hq_picture) ) {
2238
            av_log(avctx, AV_LOG_ERROR, "Invalid low delay flag\n");
2239
            return AVERROR_INVALIDDATA;
2240
        }
2241
2242
260
        if ((ret = get_buffer_with_edge(avctx, pic->avframe, (parse_code & 0x0C) == 0x0C ? AV_GET_BUFFER_FLAG_REF : 0)) < 0)
2243
            return ret;
2244
260
        s->current_picture = pic;
2245
260
        s->plane[0].stride = pic->avframe->linesize[0];
2246
260
        s->plane[1].stride = pic->avframe->linesize[1];
2247
260
        s->plane[2].stride = pic->avframe->linesize[2];
2248
2249
260
        if (alloc_buffers(s, FFMAX3(FFABS(s->plane[0].stride), FFABS(s->plane[1].stride), FFABS(s->plane[2].stride))) < 0)
2250
            return AVERROR(ENOMEM);
2251
2252
        /* [DIRAC_STD] 11.1 Picture parse. picture_parse() */
2253
260
        ret = dirac_decode_picture_header(s);
2254
260
        if (ret < 0)
2255
            return ret;
2256
2257
        /* [DIRAC_STD] 13.0 Transform data syntax. transform_data() */
2258
260
        ret = dirac_decode_frame_internal(s);
2259
260
        if (ret < 0)
2260
            return ret;
2261
    }
2262
596
    return 0;
2263
}
2264
2265
298
static int dirac_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt)
2266
{
2267
298
    DiracContext *s     = avctx->priv_data;
2268
298
    AVFrame *picture    = data;
2269
298
    uint8_t *buf        = pkt->data;
2270
298
    int buf_size        = pkt->size;
2271
298
    int i, buf_idx      = 0;
2272
    int ret;
2273
    unsigned data_unit_size;
2274
2275
    /* release unused frames */
2276
4470
    for (i = 0; i < MAX_FRAMES; i++)
2277

4172
        if (s->all_frames[i].avframe->data[0] && !s->all_frames[i].reference) {
2278
222
            av_frame_unref(s->all_frames[i].avframe);
2279
222
            memset(s->all_frames[i].interpolated, 0, sizeof(s->all_frames[i].interpolated));
2280
        }
2281
2282
298
    s->current_picture = NULL;
2283
298
    *got_frame = 0;
2284
2285
    /* end of stream, so flush delayed pics */
2286
298
    if (buf_size == 0)
2287
36
        return get_delayed_pic(s, (AVFrame *)data, got_frame);
2288
2289
    for (;;) {
2290
        /*[DIRAC_STD] Here starts the code from parse_info() defined in 9.6
2291
          [DIRAC_STD] PARSE_INFO_PREFIX = "BBCD" as defined in ISO/IEC 646
2292
          BBCD start code search */
2293
1019
        for (; buf_idx + DATA_UNIT_HEADER_SIZE < buf_size; buf_idx++) {
2294

757
            if (buf[buf_idx  ] == 'B' && buf[buf_idx+1] == 'B' &&
2295

757
                buf[buf_idx+2] == 'C' && buf[buf_idx+3] == 'D')
2296
757
                break;
2297
        }
2298
        /* BBCD found or end of data */
2299
1019
        if (buf_idx + DATA_UNIT_HEADER_SIZE >= buf_size)
2300
262
            break;
2301
2302
757
        data_unit_size = AV_RB32(buf+buf_idx+5);
2303

757
        if (data_unit_size > buf_size - buf_idx || !data_unit_size) {
2304
            if(data_unit_size > buf_size - buf_idx)
2305
            av_log(s->avctx, AV_LOG_ERROR,
2306
                   "Data unit with size %d is larger than input buffer, discarding\n",
2307
                   data_unit_size);
2308
            buf_idx += 4;
2309
            continue;
2310
        }
2311
        /* [DIRAC_STD] dirac_decode_data_unit makes reference to the while defined in 9.3 inside the function parse_sequence() */
2312
757
        ret = dirac_decode_data_unit(avctx, buf+buf_idx, data_unit_size);
2313
757
        if (ret < 0)
2314
        {
2315
            av_log(s->avctx, AV_LOG_ERROR,"Error in dirac_decode_data_unit\n");
2316
            return ret;
2317
        }
2318
757
        buf_idx += data_unit_size;
2319
    }
2320
2321
262
    if (!s->current_picture)
2322
2
        return buf_size;
2323
2324
260
    if (s->current_picture->avframe->display_picture_number > s->frame_number) {
2325
8
        DiracFrame *delayed_frame = remove_frame(s->delay_frames, s->frame_number);
2326
2327
8
        s->current_picture->reference |= DELAYED_PIC_REF;
2328
2329
8
        if (add_frame(s->delay_frames, MAX_DELAY, s->current_picture)) {
2330
            int min_num = s->delay_frames[0]->avframe->display_picture_number;
2331
            /* Too many delayed frames, so we display the frame with the lowest pts */
2332
            av_log(avctx, AV_LOG_ERROR, "Delay frame overflow\n");
2333
2334
            for (i = 1; s->delay_frames[i]; i++)
2335
                if (s->delay_frames[i]->avframe->display_picture_number < min_num)
2336
                    min_num = s->delay_frames[i]->avframe->display_picture_number;
2337
2338
            delayed_frame = remove_frame(s->delay_frames, min_num);
2339
            add_frame(s->delay_frames, MAX_DELAY, s->current_picture);
2340
        }
2341
2342
8
        if (delayed_frame) {
2343
7
            delayed_frame->reference ^= DELAYED_PIC_REF;
2344
7
            if((ret=av_frame_ref(data, delayed_frame->avframe)) < 0)
2345
                return ret;
2346
7
            *got_frame = 1;
2347
        }
2348
252
    } else if (s->current_picture->avframe->display_picture_number == s->frame_number) {
2349
        /* The right frame at the right time :-) */
2350
252
        if((ret=av_frame_ref(data, s->current_picture->avframe)) < 0)
2351
            return ret;
2352
252
        *got_frame = 1;
2353
    }
2354
2355
260
    if (*got_frame)
2356
259
        s->frame_number = picture->display_picture_number + 1LL;
2357
2358
260
    return buf_idx;
2359
}
2360
2361
AVCodec ff_dirac_decoder = {
2362
    .name           = "dirac",
2363
    .long_name      = NULL_IF_CONFIG_SMALL("BBC Dirac VC-2"),
2364
    .type           = AVMEDIA_TYPE_VIDEO,
2365
    .id             = AV_CODEC_ID_DIRAC,
2366
    .priv_data_size = sizeof(DiracContext),
2367
    .init           = dirac_decode_init,
2368
    .close          = dirac_decode_end,
2369
    .decode         = dirac_decode_frame,
2370
    .capabilities   = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS | AV_CODEC_CAP_DR1,
2371
    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
2372
    .flush          = dirac_decode_flush,
2373
};