diracdec.c 65.8 KB
Newer Older
1 2 3
/*
 * Copyright (C) 2007 Marco Gerards <marco@gnu.org>
 * Copyright (C) 2009 David Conrad
4
 * Copyright (C) 2011 Jordi Ortiz
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
24
 * @file
25
 * Dirac Decoder
26
 * @author Marco Gerards <marco@gnu.org>, David Conrad, Jordi Ortiz <nenjordi@gmail.com>
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
 */

#include "avcodec.h"
#include "dsputil.h"
#include "get_bits.h"
#include "bytestream.h"
#include "golomb.h"
#include "dirac_arith.h"
#include "mpeg12data.h"
#include "dwt.h"
#include "dirac.h"
#include "diracdsp.h"

/**
 * The spec limits the number of wavelet decompositions to 4 for both
 * level 1 (VC-2) and 128 (long-gop default).
 * 5 decompositions is the maximum before >16-bit buffers are needed.
 * Schroedinger allows this for DD 9,7 and 13,7 wavelets only, limiting
 * the others to 4 decompositions (or 3 for the fidelity filter).
 *
 * We use this instead of MAX_DECOMPOSITIONS to save some memory.
 */
#define MAX_DWT_LEVELS 5

/**
 * The spec limits this to 3 for frame coding, but in practice can be as high as 6
 */
#define MAX_REFERENCE_FRAMES 8
55
#define MAX_DELAY 5         /* limit for main profile for frame coding (TODO: field coding) */
56
#define MAX_FRAMES (MAX_REFERENCE_FRAMES + MAX_DELAY + 1)
57 58
#define MAX_QUANT 68        /* max quant for VC-2 */
#define MAX_BLOCKSIZE 32    /* maximum xblen/yblen we support */
59 60 61 62 63 64 65 66 67 68 69 70 71 72

/**
 * DiracBlock->ref flags, if set then the block does MC from the given ref
 */
#define DIRAC_REF_MASK_REF1   1
#define DIRAC_REF_MASK_REF2   2
#define DIRAC_REF_MASK_GLOBAL 4

/**
 * Value of Picture.reference when Picture is not a reference picture, but
 * is held for delayed output.
 */
#define DELAYED_PIC_REF 4

73
#define ff_emulated_edge_mc ff_emulated_edge_mc_8 /* Fix: change the calls to this function regarding bit depth */
74

Jordi Ortiz's avatar
Jordi Ortiz committed
75 76
#define CALC_PADDING(size, depth)                       \
    (((size + (1 << depth) - 1) >> depth) << depth)
77 78 79 80

#define DIVRNDUP(a, b) (((a) + (b) - 1) / (b))

typedef struct {
Jordi Ortiz's avatar
Jordi Ortiz committed
81
    AVFrame avframe;
82
    int interpolated[3];    /* 1 if hpel[] is valid */
Jordi Ortiz's avatar
Jordi Ortiz committed
83 84
    uint8_t *hpel[3][4];
    uint8_t *hpel_base[3][4];
85 86 87 88 89 90
} DiracFrame;

typedef struct {
    union {
        int16_t mv[2][2];
        int16_t dc[3];
91
    } u; /* anonymous unions aren't in C99 :( */
92 93 94 95 96 97 98 99 100 101 102 103 104
    uint8_t ref;
} DiracBlock;

typedef struct SubBand {
    int level;
    int orientation;
    int stride;
    int width;
    int height;
    int quant;
    IDWTELEM *ibuf;
    struct SubBand *parent;

105
    /* for low delay */
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    unsigned length;
    const uint8_t *coeff_data;
} SubBand;

typedef struct Plane {
    int width;
    int height;
    int stride;

    int idwt_width;
    int idwt_height;
    int idwt_stride;
    IDWTELEM *idwt_buf;
    IDWTELEM *idwt_buf_base;
    IDWTELEM *idwt_tmp;

122
    /* block length */
123 124
    uint8_t xblen;
    uint8_t yblen;
125
    /* block separation (block n+1 starts after this many pixels in block n) */
126 127
    uint8_t xbsep;
    uint8_t ybsep;
128
    /* amount of overspill on each edge (half of the overlap between blocks) */
129 130 131 132 133 134 135 136 137 138 139 140 141
    uint8_t xoffset;
    uint8_t yoffset;

    SubBand band[MAX_DWT_LEVELS][4];
} Plane;

typedef struct DiracContext {
    AVCodecContext *avctx;
    DSPContext dsp;
    DiracDSPContext diracdsp;
    GetBitContext gb;
    dirac_source_params source;
    int seen_sequence_header;
142
    int frame_number;           /* number of the next frame to display       */
143 144 145 146
    Plane plane[3];
    int chroma_x_shift;
    int chroma_y_shift;

147 148 149 150 151
    int zero_res;               /* zero residue flag                         */
    int is_arith;               /* whether coeffs use arith or golomb coding */
    int low_delay;              /* use the low delay syntax                  */
    int globalmc_flag;          /* use global motion compensation            */
    int num_refs;               /* number of reference pictures              */
152

153 154
    /* wavelet decoding */
    unsigned wavelet_depth;     /* depth of the IDWT                         */
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    unsigned wavelet_idx;

    /**
     * schroedinger older than 1.0.8 doesn't store
     * quant delta if only one codebook exists in a band
     */
    unsigned old_delta_quant;
    unsigned codeblock_mode;

    struct {
        unsigned width;
        unsigned height;
    } codeblock[MAX_DWT_LEVELS+1];

    struct {
170 171 172 173
        unsigned num_x;         /* number of horizontal slices               */
        unsigned num_y;         /* number of vertical slices                 */
        AVRational bytes;       /* average bytes per slice                   */
        uint8_t quant[MAX_DWT_LEVELS][4]; /* [DIRAC_STD] E.1 */
174 175 176
    } lowdelay;

    struct {
177 178 179
        int pan_tilt[2];        /* pan/tilt vector                           */
        int zrs[2][2];          /* zoom/rotate/shear matrix                  */
        int perspective[2];     /* perspective vector                        */
180 181 182 183
        unsigned zrs_exp;
        unsigned perspective_exp;
    } globalmc[2];

184 185 186 187
    /* motion compensation */
    uint8_t mv_precision;       /* [DIRAC_STD] REFS_WT_PRECISION             */
    int16_t weight[2];          /* [DIRAC_STD] REF1_WT and REF2_WT           */
    unsigned weight_log2denom;  /* [DIRAC_STD] REFS_WT_PRECISION             */
188

189 190 191 192
    int blwidth;                /* number of blocks (horizontally)           */
    int blheight;               /* number of blocks (vertically)             */
    int sbwidth;                /* number of superblocks (horizontally)      */
    int sbheight;               /* number of superblocks (vertically)        */
193 194 195 196 197 198 199

    uint8_t *sbsplit;
    DiracBlock *blmotion;

    uint8_t *edge_emu_buffer[4];
    uint8_t *edge_emu_buffer_base;

200
    uint16_t *mctmp;            /* buffer holding the MC data multipled by OBMC weights */
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    uint8_t *mcscratch;

    DECLARE_ALIGNED(16, uint8_t, obmc_weight)[3][MAX_BLOCKSIZE*MAX_BLOCKSIZE];

    void (*put_pixels_tab[4])(uint8_t *dst, const uint8_t *src[5], int stride, int h);
    void (*avg_pixels_tab[4])(uint8_t *dst, const uint8_t *src[5], int stride, int h);
    void (*add_obmc)(uint16_t *dst, const uint8_t *src, int stride, const uint8_t *obmc_weight, int yblen);
    dirac_weight_func weight_func;
    dirac_biweight_func biweight_func;

    DiracFrame *current_picture;
    DiracFrame *ref_pics[2];

    DiracFrame *ref_frames[MAX_REFERENCE_FRAMES+1];
    DiracFrame *delay_frames[MAX_DELAY+1];
    DiracFrame all_frames[MAX_FRAMES];
} DiracContext;

219 220 221 222
/**
 * Dirac Specification ->
 * Parse code values. 9.6.1 Table 9.1
 */
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
enum dirac_parse_code {
    pc_seq_header         = 0x00,
    pc_eos                = 0x10,
    pc_aux_data           = 0x20,
    pc_padding            = 0x30,
};

enum dirac_subband {
    subband_ll = 0,
    subband_hl = 1,
    subband_lh = 2,
    subband_hh = 3
};

static const uint8_t default_qmat[][4][4] = {
    { { 5,  3,  3,  0}, { 0,  4,  4,  1}, { 0,  5,  5,  2}, { 0,  6,  6,  3} },
    { { 4,  2,  2,  0}, { 0,  4,  4,  2}, { 0,  5,  5,  3}, { 0,  7,  7,  5} },
    { { 5,  3,  3,  0}, { 0,  4,  4,  1}, { 0,  5,  5,  2}, { 0,  6,  6,  3} },
    { { 8,  4,  4,  0}, { 0,  4,  4,  0}, { 0,  4,  4,  0}, { 0,  4,  4,  0} },
    { { 8,  4,  4,  0}, { 0,  4,  4,  0}, { 0,  4,  4,  0}, { 0,  4,  4,  0} },
    { { 0,  4,  4,  8}, { 0,  8,  8, 12}, { 0, 13, 13, 17}, { 0, 17, 17, 21} },
    { { 3,  1,  1,  0}, { 0,  4,  4,  2}, { 0,  6,  6,  5}, { 0,  9,  9,  7} },
};

static const int qscale_tab[MAX_QUANT+1] = {
Jordi Ortiz's avatar
Jordi Ortiz committed
248 249 250 251 252 253
    4,     5,     6,     7,     8,    10,    11,    13,
    16,    19,    23,    27,    32,    38,    45,    54,
    64,    76,    91,   108,   128,   152,   181,   215,
    256,   304,   362,   431,   512,   609,   724,   861,
    1024,  1218,  1448,  1722,  2048,  2435,  2896,  3444,
    4096,  4871,  5793,  6889,  8192,  9742, 11585, 13777,
254 255 256 257 258
    16384, 19484, 23170, 27554, 32768, 38968, 46341, 55109,
    65536, 77936
};

static const int qoffset_intra_tab[MAX_QUANT+1] = {
Jordi Ortiz's avatar
Jordi Ortiz committed
259 260 261 262 263 264 265
    1,     2,     3,     4,     4,     5,     6,     7,
    8,    10,    12,    14,    16,    19,    23,    27,
    32,    38,    46,    54,    64,    76,    91,   108,
    128,   152,   181,   216,   256,   305,   362,   431,
    512,   609,   724,   861,  1024,  1218,  1448,  1722,
    2048,  2436,  2897,  3445,  4096,  4871,  5793,  6889,
    8192,  9742, 11585, 13777, 16384, 19484, 23171, 27555,
266 267 268 269
    32768, 38968
};

static const int qoffset_inter_tab[MAX_QUANT+1] = {
Jordi Ortiz's avatar
Jordi Ortiz committed
270 271 272 273 274 275 276
    1,     2,     2,     3,     3,     4,     4,     5,
    6,     7,     9,    10,    12,    14,    17,    20,
    24,    29,    34,    41,    48,    57,    68,    81,
    96,   114,   136,   162,   192,   228,   272,   323,
    384,   457,   543,   646,   768,   913,  1086,  1292,
    1536,  1827,  2172,  2583,  3072,  3653,  4344,  5166,
    6144,  7307,  8689, 10333, 12288, 14613, 17378, 20666,
277 278 279
    24576, 29226
};

280
/* magic number division by 3 from schroedinger */
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
static inline int divide3(int x)
{
    return ((x+1)*21845 + 10922) >> 16;
}

static DiracFrame *remove_frame(DiracFrame *framelist[], int picnum)
{
    DiracFrame *remove_pic = NULL;
    int i, remove_idx = -1;

    for (i = 0; framelist[i]; i++)
        if (framelist[i]->avframe.display_picture_number == picnum) {
            remove_pic = framelist[i];
            remove_idx = i;
        }

    if (remove_pic)
        for (i = remove_idx; framelist[i]; i++)
            framelist[i] = framelist[i+1];

    return remove_pic;
}

static int add_frame(DiracFrame *framelist[], int maxframes, DiracFrame *frame)
{
    int i;
    for (i = 0; i < maxframes; i++)
        if (!framelist[i]) {
            framelist[i] = frame;
            return 0;
        }
    return -1;
}

static int alloc_sequence_buffers(DiracContext *s)
{
    int sbwidth  = DIVRNDUP(s->source.width,  4);
    int sbheight = DIVRNDUP(s->source.height, 4);
    int i, w, h, top_padding;

321
    /* todo: think more about this / use or set Plane here */
322 323 324 325 326 327
    for (i = 0; i < 3; i++) {
        int max_xblen = MAX_BLOCKSIZE >> (i ? s->chroma_x_shift : 0);
        int max_yblen = MAX_BLOCKSIZE >> (i ? s->chroma_y_shift : 0);
        w = s->source.width  >> (i ? s->chroma_x_shift : 0);
        h = s->source.height >> (i ? s->chroma_y_shift : 0);

328 329 330 331 332
        /* we allocate the max we support here since num decompositions can
         * change from frame to frame. Stride is aligned to 16 for SIMD, and
         * 1<<MAX_DWT_LEVELS top padding to avoid if(y>0) in arith decoding
         * MAX_BLOCKSIZE padding for MC: blocks can spill up to half of that
         * on each side */
333
        top_padding = FFMAX(1<<MAX_DWT_LEVELS, max_yblen/2);
334
        w = FFALIGN(CALC_PADDING(w, MAX_DWT_LEVELS), 8); /* FIXME: Should this be 16 for SSE??? */
335 336 337 338 339 340 341 342 343 344 345 346
        h = top_padding + CALC_PADDING(h, MAX_DWT_LEVELS) + max_yblen/2;

        s->plane[i].idwt_buf_base = av_mallocz((w+max_xblen)*h * sizeof(IDWTELEM));
        s->plane[i].idwt_tmp      = av_malloc((w+16) * sizeof(IDWTELEM));
        s->plane[i].idwt_buf      = s->plane[i].idwt_buf_base + top_padding*w;
        if (!s->plane[i].idwt_buf_base || !s->plane[i].idwt_tmp)
            return AVERROR(ENOMEM);
    }

    w = s->source.width;
    h = s->source.height;

347
    /* fixme: allocate using real stride here */
348 349 350 351
    s->sbsplit  = av_malloc(sbwidth * sbheight);
    s->blmotion = av_malloc(sbwidth * sbheight * 4 * sizeof(*s->blmotion));
    s->edge_emu_buffer_base = av_malloc((w+64)*MAX_BLOCKSIZE);

352 353
    s->mctmp     = av_malloc((w+64+MAX_BLOCKSIZE) * (h*MAX_BLOCKSIZE) * sizeof(*s->mctmp));
    s->mcscratch = av_malloc((w+64)*MAX_BLOCKSIZE);
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401

    if (!s->sbsplit || !s->blmotion)
        return AVERROR(ENOMEM);
    return 0;
}

static void free_sequence_buffers(DiracContext *s)
{
    int i, j, k;

    for (i = 0; i < MAX_FRAMES; i++) {
        if (s->all_frames[i].avframe.data[0]) {
            s->avctx->release_buffer(s->avctx, &s->all_frames[i].avframe);
            memset(s->all_frames[i].interpolated, 0, sizeof(s->all_frames[i].interpolated));
        }

        for (j = 0; j < 3; j++)
            for (k = 1; k < 4; k++)
                av_freep(&s->all_frames[i].hpel_base[j][k]);
    }

    memset(s->ref_frames, 0, sizeof(s->ref_frames));
    memset(s->delay_frames, 0, sizeof(s->delay_frames));

    for (i = 0; i < 3; i++) {
        av_freep(&s->plane[i].idwt_buf_base);
        av_freep(&s->plane[i].idwt_tmp);
    }

    av_freep(&s->sbsplit);
    av_freep(&s->blmotion);
    av_freep(&s->edge_emu_buffer_base);

    av_freep(&s->mctmp);
    av_freep(&s->mcscratch);
}

static av_cold int dirac_decode_init(AVCodecContext *avctx)
{
    DiracContext *s = avctx->priv_data;
    s->avctx = avctx;
    s->frame_number = -1;

    if (avctx->flags&CODEC_FLAG_EMU_EDGE) {
        av_log(avctx, AV_LOG_ERROR, "Edge emulation not supported!\n");
        return AVERROR_PATCHWELCOME;
    }

402
    ff_dsputil_init(&s->dsp, avctx);
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    ff_diracdsp_init(&s->diracdsp);

    return 0;
}

static void dirac_decode_flush(AVCodecContext *avctx)
{
    DiracContext *s = avctx->priv_data;
    free_sequence_buffers(s);
    s->seen_sequence_header = 0;
    s->frame_number = -1;
}

static av_cold int dirac_decode_end(AVCodecContext *avctx)
{
    dirac_decode_flush(avctx);
    return 0;
}

#define SIGN_CTX(x) (CTX_SIGN_ZERO + ((x) > 0) - ((x) < 0))

static inline void coeff_unpack_arith(DiracArith *c, int qfactor, int qoffset,
                                      SubBand *b, IDWTELEM *buf, int x, int y)
{
    int coeff, sign;
    int sign_pred = 0;
    int pred_ctx = CTX_ZPZN_F1;

431
    /* Check if the parent subband has a 0 in the corresponding position */
432 433 434 435 436 437
    if (b->parent)
        pred_ctx += !!b->parent->ibuf[b->parent->stride * (y>>1) + (x>>1)] << 1;

    if (b->orientation == subband_hl)
        sign_pred = buf[-b->stride];

438
    /* Determine if the pixel has only zeros in its neighbourhood */
439 440 441 442 443 444 445 446 447 448
    if (x) {
        pred_ctx += !(buf[-1] | buf[-b->stride] | buf[-1-b->stride]);
        if (b->orientation == subband_lh)
            sign_pred = buf[-1];
    } else {
        pred_ctx += !buf[-b->stride];
    }

    coeff = dirac_get_arith_uint(c, pred_ctx, CTX_COEFF_DATA);
    if (coeff) {
449 450
        coeff = (coeff * qfactor + qoffset + 2) >> 2;
        sign  = dirac_get_arith_bit(c, SIGN_CTX(sign_pred));
451 452 453 454 455 456 457 458 459 460 461
        coeff = (coeff ^ -sign) + sign;
    }
    *buf = coeff;
}

static inline int coeff_unpack_golomb(GetBitContext *gb, int qfactor, int qoffset)
{
    int sign, coeff;

    coeff = svq3_get_ue_golomb(gb);
    if (coeff) {
462 463
        coeff = (coeff * qfactor + qoffset + 2) >> 2;
        sign  = get_bits1(gb);
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        coeff = (coeff ^ -sign) + sign;
    }
    return coeff;
}

/**
 * Decode the coeffs in the rectangle defined by left, right, top, bottom
 * [DIRAC_STD] 13.4.3.2 Codeblock unpacking loop. codeblock()
 */
static inline void codeblock(DiracContext *s, SubBand *b,
                             GetBitContext *gb, DiracArith *c,
                             int left, int right, int top, int bottom,
                             int blockcnt_one, int is_arith)
{
    int x, y, zero_block;
    int qoffset, qfactor;
    IDWTELEM *buf;

482
    /* check for any coded coefficients in this codeblock */
483 484 485 486 487 488 489 490 491 492 493
    if (!blockcnt_one) {
        if (is_arith)
            zero_block = dirac_get_arith_bit(c, CTX_ZERO_BLOCK);
        else
            zero_block = get_bits1(gb);

        if (zero_block)
            return;
    }

    if (s->codeblock_mode && !(s->old_delta_quant && blockcnt_one)) {
494
        int quant = b->quant;
495
        if (is_arith)
496
            quant += dirac_get_arith_int(c, CTX_DELTA_Q_F, CTX_DELTA_Q_DATA);
497
        else
498 499 500 501 502 503
            quant += dirac_get_se_golomb(gb);
        if (quant < 0) {
            av_log(s->avctx, AV_LOG_ERROR, "Invalid quant\n");
            return;
        }
        b->quant = quant;
504 505 506 507 508
    }

    b->quant = FFMIN(b->quant, MAX_QUANT);

    qfactor = qscale_tab[b->quant];
509
    /* TODO: context pointer? */
510 511 512 513 514
    if (!s->num_refs)
        qoffset = qoffset_intra_tab[b->quant];
    else
        qoffset = qoffset_inter_tab[b->quant];

515
    buf = b->ibuf + top * b->stride;
516 517
    for (y = top; y < bottom; y++) {
        for (x = left; x < right; x++) {
518
            /* [DIRAC_STD] 13.4.4 Subband coefficients. coeff_unpack() */
519 520 521 522 523 524 525 526 527
            if (is_arith)
                coeff_unpack_arith(c, qfactor, qoffset, b, buf+x, x, y);
            else
                buf[x] = coeff_unpack_golomb(gb, qfactor, qoffset);
        }
        buf += b->stride;
    }
}

528 529 530 531
/**
 * Dirac Specification ->
 * 13.3 intra_dc_prediction(band)
 */
532 533 534 535 536 537 538 539 540 541 542 543 544 545
static inline void intra_dc_prediction(SubBand *b)
{
    IDWTELEM *buf = b->ibuf;
    int x, y;

    for (x = 1; x < b->width; x++)
        buf[x] += buf[x-1];
    buf += b->stride;

    for (y = 1; y < b->height; y++) {
        buf[0] += buf[-b->stride];

        for (x = 1; x < b->width; x++) {
            int pred = buf[x - 1] + buf[x - b->stride] + buf[x - b->stride-1];
546
            buf[x]  += divide3(pred);
547 548 549 550 551
        }
        buf += b->stride;
    }
}

552 553 554 555
/**
 * Dirac Specification ->
 * 13.4.2 Non-skipped subbands.  subband_coeffs()
 */
556
static av_always_inline void decode_subband_internal(DiracContext *s, SubBand *b, int is_arith)
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
{
    int cb_x, cb_y, left, right, top, bottom;
    DiracArith c;
    GetBitContext gb;
    int cb_width  = s->codeblock[b->level + (b->orientation != subband_ll)].width;
    int cb_height = s->codeblock[b->level + (b->orientation != subband_ll)].height;
    int blockcnt_one = (cb_width + cb_height) == 2;

    if (!b->length)
        return;

    init_get_bits(&gb, b->coeff_data, b->length*8);

    if (is_arith)
        ff_dirac_init_arith_decoder(&c, &gb, b->length);

    top = 0;
    for (cb_y = 0; cb_y < cb_height; cb_y++) {
        bottom = (b->height * (cb_y+1)) / cb_height;
        left = 0;
        for (cb_x = 0; cb_x < cb_width; cb_x++) {
            right = (b->width * (cb_x+1)) / cb_width;
            codeblock(s, b, &gb, &c, left, right, top, bottom, blockcnt_one, is_arith);
            left = right;
        }
        top = bottom;
    }

    if (b->orientation == subband_ll && s->num_refs == 0)
        intra_dc_prediction(b);
}

static int decode_subband_arith(AVCodecContext *avctx, void *b)
{
    DiracContext *s = avctx->priv_data;
    decode_subband_internal(s, b, 1);
    return 0;
}

static int decode_subband_golomb(AVCodecContext *avctx, void *arg)
{
    DiracContext *s = avctx->priv_data;
599
    SubBand **b     = arg;
600 601 602 603
    decode_subband_internal(s, *b, 0);
    return 0;
}

604 605 606 607
/**
 * Dirac Specification ->
 * [DIRAC_STD] 13.4.1 core_transform_data()
 */
608 609 610 611 612 613 614
static void decode_component(DiracContext *s, int comp)
{
    AVCodecContext *avctx = s->avctx;
    SubBand *bands[3*MAX_DWT_LEVELS+1];
    enum dirac_subband orientation;
    int level, num_bands = 0;

615
    /* Unpack all subbands at all levels. */
616 617 618 619 620 621
    for (level = 0; level < s->wavelet_depth; level++) {
        for (orientation = !!level; orientation < 4; orientation++) {
            SubBand *b = &s->plane[comp].band[level][orientation];
            bands[num_bands++] = b;

            align_get_bits(&s->gb);
622
            /* [DIRAC_STD] 13.4.2 subband() */
623 624 625 626 627
            b->length = svq3_get_ue_golomb(&s->gb);
            if (b->length) {
                b->quant = svq3_get_ue_golomb(&s->gb);
                align_get_bits(&s->gb);
                b->coeff_data = s->gb.buffer + get_bits_count(&s->gb)/8;
628
                b->length = FFMIN(b->length, FFMAX(get_bits_left(&s->gb)/8, 0));
629 630 631
                skip_bits_long(&s->gb, b->length*8);
            }
        }
632
        /* arithmetic coding has inter-level dependencies, so we can only execute one level at a time */
633 634 635 636
        if (s->is_arith)
            avctx->execute(avctx, decode_subband_arith, &s->plane[comp].band[level][!!level],
                           NULL, 4-!!level, sizeof(SubBand));
    }
637
    /* golomb coding has no inter-level dependencies, so we can execute all subbands in parallel */
638 639 640 641
    if (!s->is_arith)
        avctx->execute(avctx, decode_subband_golomb, bands, NULL, num_bands, sizeof(SubBand*));
}

642 643
/* [DIRAC_STD] 13.5.5.2 Luma slice subband data. luma_slice_band(level,orient,sx,sy) --> if b2 == NULL */
/* [DIRAC_STD] 13.5.5.3 Chroma slice subband data. chroma_slice_band(level,orient,sx,sy) --> if b2 != NULL */
644 645 646 647
static void lowdelay_subband(DiracContext *s, GetBitContext *gb, int quant,
                             int slice_x, int slice_y, int bits_end,
                             SubBand *b1, SubBand *b2)
{
648 649 650 651
    int left   = b1->width  * slice_x    / s->lowdelay.num_x;
    int right  = b1->width  *(slice_x+1) / s->lowdelay.num_x;
    int top    = b1->height * slice_y    / s->lowdelay.num_y;
    int bottom = b1->height *(slice_y+1) / s->lowdelay.num_y;
652 653 654 655

    int qfactor = qscale_tab[FFMIN(quant, MAX_QUANT)];
    int qoffset = qoffset_intra_tab[FFMIN(quant, MAX_QUANT)];

656 657
    IDWTELEM *buf1 =      b1->ibuf + top * b1->stride;
    IDWTELEM *buf2 = b2 ? b2->ibuf + top * b2->stride : NULL;
658
    int x, y;
659 660
    /* we have to constantly check for overread since the spec explictly
       requires this, with the meaning that all remaining coeffs are set to 0 */
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
    if (get_bits_count(gb) >= bits_end)
        return;

    for (y = top; y < bottom; y++) {
        for (x = left; x < right; x++) {
            buf1[x] = coeff_unpack_golomb(gb, qfactor, qoffset);
            if (get_bits_count(gb) >= bits_end)
                return;
            if (buf2) {
                buf2[x] = coeff_unpack_golomb(gb, qfactor, qoffset);
                if (get_bits_count(gb) >= bits_end)
                    return;
            }
        }
        buf1 += b1->stride;
        if (buf2)
            buf2 += b2->stride;
    }
}

struct lowdelay_slice {
    GetBitContext gb;
    int slice_x;
    int slice_y;
    int bytes;
};


689 690 691 692
/**
 * Dirac Specification ->
 * 13.5.2 Slices. slice(sx,sy)
 */
693 694 695 696 697 698 699 700
static int decode_lowdelay_slice(AVCodecContext *avctx, void *arg)
{
    DiracContext *s = avctx->priv_data;
    struct lowdelay_slice *slice = arg;
    GetBitContext *gb = &slice->gb;
    enum dirac_subband orientation;
    int level, quant, chroma_bits, chroma_end;

701
    int quant_base  = get_bits(gb, 7); /*[DIRAC_STD] qindex */
702
    int length_bits = av_log2(8 * slice->bytes)+1;
703 704 705
    int luma_bits   = get_bits_long(gb, length_bits);
    int luma_end    = get_bits_count(gb) + FFMIN(luma_bits, get_bits_left(gb));

706
    /* [DIRAC_STD] 13.5.5.2 luma_slice_band */
707 708 709 710 711 712 713
    for (level = 0; level < s->wavelet_depth; level++)
        for (orientation = !!level; orientation < 4; orientation++) {
            quant = FFMAX(quant_base - s->lowdelay.quant[level][orientation], 0);
            lowdelay_subband(s, gb, quant, slice->slice_x, slice->slice_y, luma_end,
                             &s->plane[0].band[level][orientation], NULL);
        }

714
    /* consume any unused bits from luma */
715 716 717
    skip_bits_long(gb, get_bits_count(gb) - luma_end);

    chroma_bits = 8*slice->bytes - 7 - length_bits - luma_bits;
718
    chroma_end  = get_bits_count(gb) + FFMIN(chroma_bits, get_bits_left(gb));
719
    /* [DIRAC_STD] 13.5.5.3 chroma_slice_band */
720 721 722 723 724 725 726 727 728 729 730
    for (level = 0; level < s->wavelet_depth; level++)
        for (orientation = !!level; orientation < 4; orientation++) {
            quant = FFMAX(quant_base - s->lowdelay.quant[level][orientation], 0);
            lowdelay_subband(s, gb, quant, slice->slice_x, slice->slice_y, chroma_end,
                             &s->plane[1].band[level][orientation],
                             &s->plane[2].band[level][orientation]);
        }

    return 0;
}

731 732 733 734
/**
 * Dirac Specification ->
 * 13.5.1 low_delay_transform_data()
 */
735 736 737 738 739 740 741 742 743 744 745
static void decode_lowdelay(DiracContext *s)
{
    AVCodecContext *avctx = s->avctx;
    int slice_x, slice_y, bytes, bufsize;
    const uint8_t *buf;
    struct lowdelay_slice *slices;
    int slice_num = 0;

    slices = av_mallocz(s->lowdelay.num_x * s->lowdelay.num_y * sizeof(struct lowdelay_slice));

    align_get_bits(&s->gb);
746
    /*[DIRAC_STD] 13.5.2 Slices. slice(sx,sy) */
747 748 749
    buf = s->gb.buffer + get_bits_count(&s->gb)/8;
    bufsize = get_bits_left(&s->gb);

750 751
    for (slice_y = 0; bufsize > 0 && slice_y < s->lowdelay.num_y; slice_y++)
        for (slice_x = 0; bufsize > 0 && slice_x < s->lowdelay.num_x; slice_x++) {
752
            bytes = (slice_num+1) * s->lowdelay.bytes.num / s->lowdelay.bytes.den
753
                - slice_num    * s->lowdelay.bytes.num / s->lowdelay.bytes.den;
754 755 756 757 758 759 760 761 762 763 764 765

            slices[slice_num].bytes   = bytes;
            slices[slice_num].slice_x = slice_x;
            slices[slice_num].slice_y = slice_y;
            init_get_bits(&slices[slice_num].gb, buf, bufsize);
            slice_num++;

            buf     += bytes;
            bufsize -= bytes*8;
        }

    avctx->execute(avctx, decode_lowdelay_slice, slices, NULL, slice_num,
766 767 768 769
                   sizeof(struct lowdelay_slice)); /* [DIRAC_STD] 13.5.2 Slices */
    intra_dc_prediction(&s->plane[0].band[0][0]);  /* [DIRAC_STD] 13.3 intra_dc_prediction() */
    intra_dc_prediction(&s->plane[1].band[0][0]);  /* [DIRAC_STD] 13.3 intra_dc_prediction() */
    intra_dc_prediction(&s->plane[2].band[0][0]);  /* [DIRAC_STD] 13.3 intra_dc_prediction() */
770 771 772 773 774 775 776 777 778 779
    av_free(slices);
}

static void init_planes(DiracContext *s)
{
    int i, w, h, level, orientation;

    for (i = 0; i < 3; i++) {
        Plane *p = &s->plane[i];

780 781
        p->width       = s->source.width  >> (i ? s->chroma_x_shift : 0);
        p->height      = s->source.height >> (i ? s->chroma_y_shift : 0);
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
        p->idwt_width  = w = CALC_PADDING(p->width , s->wavelet_depth);
        p->idwt_height = h = CALC_PADDING(p->height, s->wavelet_depth);
        p->idwt_stride = FFALIGN(p->idwt_width, 8);

        for (level = s->wavelet_depth-1; level >= 0; level--) {
            w = w>>1;
            h = h>>1;
            for (orientation = !!level; orientation < 4; orientation++) {
                SubBand *b = &p->band[level][orientation];

                b->ibuf   = p->idwt_buf;
                b->level  = level;
                b->stride = p->idwt_stride << (s->wavelet_depth - level);
                b->width  = w;
                b->height = h;
                b->orientation = orientation;

                if (orientation & 1)
                    b->ibuf += w;
                if (orientation > 1)
                    b->ibuf += b->stride>>1;

                if (level)
                    b->parent = &p->band[level-1][orientation];
            }
        }

        if (i > 0) {
            p->xblen = s->plane[0].xblen >> s->chroma_x_shift;
            p->yblen = s->plane[0].yblen >> s->chroma_y_shift;
            p->xbsep = s->plane[0].xbsep >> s->chroma_x_shift;
            p->ybsep = s->plane[0].ybsep >> s->chroma_y_shift;
        }

        p->xoffset = (p->xblen - p->xbsep)/2;
        p->yoffset = (p->yblen - p->ybsep)/2;
    }
}

/**
 * Unpack the motion compensation parameters
823 824
 * Dirac Specification ->
 * 11.2 Picture prediction data. picture_prediction()
825 826 827 828 829 830 831 832 833 834
 */
static int dirac_unpack_prediction_parameters(DiracContext *s)
{
    static const uint8_t default_blen[] = { 4, 12, 16, 24 };
    static const uint8_t default_bsep[] = { 4,  8, 12, 16 };

    GetBitContext *gb = &s->gb;
    unsigned idx, ref;

    align_get_bits(gb);
835 836 837
    /* [DIRAC_STD] 11.2.2 Block parameters. block_parameters() */
    /* Luma and Chroma are equal. 11.2.3 */
    idx = svq3_get_ue_golomb(gb); /* [DIRAC_STD] index */
838

839
    if (idx > 4) {
840
        av_log(s->avctx, AV_LOG_ERROR, "Block prediction index too high\n");
841
        return -1;
842
    }
843 844 845 846 847 848 849

    if (idx == 0) {
        s->plane[0].xblen = svq3_get_ue_golomb(gb);
        s->plane[0].yblen = svq3_get_ue_golomb(gb);
        s->plane[0].xbsep = svq3_get_ue_golomb(gb);
        s->plane[0].ybsep = svq3_get_ue_golomb(gb);
    } else {
850
        /*[DIRAC_STD] preset_block_params(index). Table 11.1 */
851 852 853 854 855
        s->plane[0].xblen = default_blen[idx-1];
        s->plane[0].yblen = default_blen[idx-1];
        s->plane[0].xbsep = default_bsep[idx-1];
        s->plane[0].ybsep = default_bsep[idx-1];
    }
856 857
    /*[DIRAC_STD] 11.2.4 motion_data_dimensions()
      Calculated in function dirac_unpack_block_motion_data */
858

859
    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) {
860 861 862 863
        av_log(s->avctx, AV_LOG_ERROR, "Block separation too small\n");
        return -1;
    }
    if (s->plane[0].xbsep > s->plane[0].xblen || s->plane[0].ybsep > s->plane[0].yblen) {
864
        av_log(s->avctx, AV_LOG_ERROR, "Block separation greater than size\n");
865 866 867 868 869 870 871
        return -1;
    }
    if (FFMAX(s->plane[0].xblen, s->plane[0].yblen) > MAX_BLOCKSIZE) {
        av_log(s->avctx, AV_LOG_ERROR, "Unsupported large block size\n");
        return -1;
    }

872 873
    /*[DIRAC_STD] 11.2.5 Motion vector precision. motion_vector_precision()
      Read motion vector precision */
874 875 876 877 878 879
    s->mv_precision = svq3_get_ue_golomb(gb);
    if (s->mv_precision > 3) {
        av_log(s->avctx, AV_LOG_ERROR, "MV precision finer than eighth-pel\n");
        return -1;
    }

880 881
    /*[DIRAC_STD] 11.2.6 Global motion. global_motion()
      Read the global motion compensation parameters */
882 883 884
    s->globalmc_flag = get_bits1(gb);
    if (s->globalmc_flag) {
        memset(s->globalmc, 0, sizeof(s->globalmc));
885
        /* [DIRAC_STD] pan_tilt(gparams) */
886 887 888 889 890
        for (ref = 0; ref < s->num_refs; ref++) {
            if (get_bits1(gb)) {
                s->globalmc[ref].pan_tilt[0] = dirac_get_se_golomb(gb);
                s->globalmc[ref].pan_tilt[1] = dirac_get_se_golomb(gb);
            }
891 892
            /* [DIRAC_STD] zoom_rotate_shear(gparams)
               zoom/rotation/shear parameters */
893
            if (get_bits1(gb)) {
894
                s->globalmc[ref].zrs_exp   = svq3_get_ue_golomb(gb);
895 896 897 898 899 900 901 902
                s->globalmc[ref].zrs[0][0] = dirac_get_se_golomb(gb);
                s->globalmc[ref].zrs[0][1] = dirac_get_se_golomb(gb);
                s->globalmc[ref].zrs[1][0] = dirac_get_se_golomb(gb);
                s->globalmc[ref].zrs[1][1] = dirac_get_se_golomb(gb);
            } else {
                s->globalmc[ref].zrs[0][0] = 1;
                s->globalmc[ref].zrs[1][1] = 1;
            }
903
            /* [DIRAC_STD] perspective(gparams) */
904 905
            if (get_bits1(gb)) {
                s->globalmc[ref].perspective_exp = svq3_get_ue_golomb(gb);
906 907
                s->globalmc[ref].perspective[0]  = dirac_get_se_golomb(gb);
                s->globalmc[ref].perspective[1]  = dirac_get_se_golomb(gb);
908 909 910 911
            }
        }
    }

912 913
    /*[DIRAC_STD] 11.2.7 Picture prediction mode. prediction_mode()
      Picture prediction mode, not currently used. */
914 915 916 917 918
    if (svq3_get_ue_golomb(gb)) {
        av_log(s->avctx, AV_LOG_ERROR, "Unknown picture prediction mode\n");
        return -1;
    }

919 920
    /* [DIRAC_STD] 11.2.8 Reference picture weight. reference_picture_weights()
       just data read, weight calculation will be done later on. */
921 922 923 924 925 926 927 928 929 930 931 932 933
    s->weight_log2denom = 1;
    s->weight[0]        = 1;
    s->weight[1]        = 1;

    if (get_bits1(gb)) {
        s->weight_log2denom = svq3_get_ue_golomb(gb);
        s->weight[0] = dirac_get_se_golomb(gb);
        if (s->num_refs == 2)
            s->weight[1] = dirac_get_se_golomb(gb);
    }
    return 0;
}

934 935 936 937
/**
 * Dirac Specification ->
 * 11.3 Wavelet transform data. wavelet_transform()
 */
938 939 940 941
static int dirac_unpack_idwt_params(DiracContext *s)
{
    GetBitContext *gb = &s->gb;
    int i, level;
942 943 944 945 946 947 948 949 950
    unsigned tmp;

#define CHECKEDREAD(dst, cond, errmsg) \
    tmp = svq3_get_ue_golomb(gb); \
    if (cond) { \
        av_log(s->avctx, AV_LOG_ERROR, errmsg); \
        return -1; \
    }\
    dst = tmp;
951 952 953 954 955 956 957

    align_get_bits(gb);

    s->zero_res = s->num_refs ? get_bits1(gb) : 0;
    if (s->zero_res)
        return 0;

958
    /*[DIRAC_STD] 11.3.1 Transform parameters. transform_parameters() */
959
    CHECKEDREAD(s->wavelet_idx, tmp > 6, "wavelet_idx is too big\n")
960

961
    CHECKEDREAD(s->wavelet_depth, tmp > MAX_DWT_LEVELS || tmp < 1, "invalid number of DWT decompositions\n")
962 963

    if (!s->low_delay) {
964
        /* Codeblock parameters (core syntax only) */
965 966
        if (get_bits1(gb)) {
            for (i = 0; i <= s->wavelet_depth; i++) {
967 968
                CHECKEDREAD(s->codeblock[i].width , tmp < 1, "codeblock width invalid\n")
                CHECKEDREAD(s->codeblock[i].height, tmp < 1, "codeblock height invalid\n")
969 970
            }

971
            CHECKEDREAD(s->codeblock_mode, tmp > 1, "unknown codeblock mode\n")
972 973 974 975
        } else
            for (i = 0; i <= s->wavelet_depth; i++)
                s->codeblock[i].width = s->codeblock[i].height = 1;
    } else {
976 977
        /* Slice parameters + quantization matrix*/
        /*[DIRAC_STD] 11.3.4 Slice coding Parameters (low delay syntax only). slice_parameters() */
978 979 980 981 982
        s->lowdelay.num_x     = svq3_get_ue_golomb(gb);
        s->lowdelay.num_y     = svq3_get_ue_golomb(gb);
        s->lowdelay.bytes.num = svq3_get_ue_golomb(gb);
        s->lowdelay.bytes.den = svq3_get_ue_golomb(gb);

983 984 985 986 987
        if (s->lowdelay.bytes.den <= 0) {
            av_log(s->avctx,AV_LOG_ERROR,"Invalid lowdelay.bytes.den\n");
            return AVERROR_INVALIDDATA;
        }

988
        /* [DIRAC_STD] 11.3.5 Quantisation matrices (low-delay syntax). quant_matrix() */
989
        if (get_bits1(gb)) {
990 991
            av_log(s->avctx,AV_LOG_DEBUG,"Low Delay: Has Custom Quantization Matrix!\n");
            /* custom quantization matrix */
992 993 994 995 996 997 998
            s->lowdelay.quant[0][0] = svq3_get_ue_golomb(gb);
            for (level = 0; level < s->wavelet_depth; level++) {
                s->lowdelay.quant[level][1] = svq3_get_ue_golomb(gb);
                s->lowdelay.quant[level][2] = svq3_get_ue_golomb(gb);
                s->lowdelay.quant[level][3] = svq3_get_ue_golomb(gb);
            }
        } else {
999
            /* default quantization matrix */
1000 1001 1002
            for (level = 0; level < s->wavelet_depth; level++)
                for (i = 0; i < 4; i++) {
                    s->lowdelay.quant[level][i] = default_qmat[s->wavelet_idx][level][i];
1003
                    /* haar with no shift differs for different depths */
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
                    if (s->wavelet_idx == 3)
                        s->lowdelay.quant[level][i] += 4*(s->wavelet_depth-1 - level);
                }
        }
    }
    return 0;
}

static inline int pred_sbsplit(uint8_t *sbsplit, int stride, int x, int y)
{
    static const uint8_t avgsplit[7] = { 0, 0, 1, 1, 1, 2, 2 };

    if (!(x|y))
        return 0;
    else if (!y)
        return sbsplit[-1];
    else if (!x)
        return sbsplit[-stride];

    return avgsplit[sbsplit[-1] + sbsplit[-stride] + sbsplit[-stride-1]];
}

static inline int pred_block_mode(DiracBlock *block, int stride, int x, int y, int refmask)
{
    int pred;

    if (!(x|y))
        return 0;
    else if (!y)
        return block[-1].ref & refmask;
    else if (!x)
        return block[-stride].ref & refmask;

1037
    /* return the majority */
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    pred = (block[-1].ref & refmask) + (block[-stride].ref & refmask) + (block[-stride-1].ref & refmask);
    return (pred >> 1) & refmask;
}

static inline void pred_block_dc(DiracBlock *block, int stride, int x, int y)
{
    int i, n = 0;

    memset(block->u.dc, 0, sizeof(block->u.dc));

    if (x && !(block[-1].ref & 3)) {
        for (i = 0; i < 3; i++)
            block->u.dc[i] += block[-1].u.dc[i];
        n++;
    }

    if (y && !(block[-stride].ref & 3)) {
        for (i = 0; i < 3; i++)
            block->u.dc[i] += block[-stride].u.dc[i];
        n++;
    }

    if (x && y && !(block[-1-stride].ref & 3)) {
        for (i = 0; i < 3; i++)
            block->u.dc[i] += block[-1-stride].u.dc[i];
        n++;
    }

    if (n == 2) {
        for (i = 0; i < 3; i++)
            block->u.dc[i] = (block->u.dc[i]+1)>>1;
    } else if (n == 3) {
        for (i = 0; i < 3; i++)
            block->u.dc[i] = divide3(block->u.dc[i]);
    }
}

static inline void pred_mv(DiracBlock *block, int stride, int x, int y, int ref)
{
    int16_t *pred[3];
    int refmask = ref+1;
1079
    int mask = refmask | DIRAC_REF_MASK_GLOBAL; /*  exclude gmc blocks */
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
    int n = 0;

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

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

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

    switch (n) {
    case 0:
        block->u.mv[ref][0] = 0;
        block->u.mv[ref][1] = 0;
        break;
    case 1:
        block->u.mv[ref][0] = pred[0][0];
        block->u.mv[ref][1] = pred[0][1];
        break;
    case 2:
        block->u.mv[ref][0] = (pred[0][0] + pred[1][0] + 1) >> 1;
        block->u.mv[ref][1] = (pred[0][1] + pred[1][1] + 1) >> 1;
        break;
    case 3:
        block->u.mv[ref][0] = mid_pred(pred[0][0], pred[1][0], pred[2][0]);
        block->u.mv[ref][1] = mid_pred(pred[0][1], pred[1][1], pred[2][1]);
        break;
    }
}

static void global_mv(DiracContext *s, DiracBlock *block, int x, int y, int ref)
{
1113 1114
    int ez      = s->globalmc[ref].zrs_exp;
    int ep      = s->globalmc[ref].perspective_exp;
1115
    int (*A)[2] = s->globalmc[ref].zrs;
1116 1117
    int *b      = s->globalmc[ref].pan_tilt;
    int *c      = s->globalmc[ref].perspective;
1118

1119 1120 1121
    int m       = (1<<ep) - (c[0]*x + c[1]*y);
    int mx      = m * ((A[0][0] * x + A[0][1]*y) + (1<<ez) * b[0]);
    int my      = m * ((A[1][0] * x + A[1][1]*y) + (1<<ez) * b[1]);
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131

    block->u.mv[ref][0] = (mx + (1<<(ez+ep))) >> (ez+ep);
    block->u.mv[ref][1] = (my + (1<<(ez+ep))) >> (ez+ep);
}

static void decode_block_params(DiracContext *s, DiracArith arith[8], DiracBlock *block,
                                int stride, int x, int y)
{
    int i;

1132
    block->ref  = pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_REF1);
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
    block->ref ^= dirac_get_arith_bit(arith, CTX_PMODE_REF1);

    if (s->num_refs == 2) {
        block->ref |= pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_REF2);
        block->ref ^= dirac_get_arith_bit(arith, CTX_PMODE_REF2) << 1;
    }

    if (!block->ref) {
        pred_block_dc(block, stride, x, y);
        for (i = 0; i < 3; i++)
            block->u.dc[i] += dirac_get_arith_int(arith+1+i, CTX_DC_F1, CTX_DC_DATA);
        return;
    }

    if (s->globalmc_flag) {
        block->ref |= pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_GLOBAL);
        block->ref ^= dirac_get_arith_bit(arith, CTX_GLOBAL_BLOCK) << 2;
    }

    for (i = 0; i < s->num_refs; i++)
        if (block->ref & (i+1)) {
            if (block->ref & DIRAC_REF_MASK_GLOBAL) {
                global_mv(s, block, x, y, i);
            } else {
                pred_mv(block, stride, x, y, i);
1158 1159
                block->u.mv[i][0] += dirac_get_arith_int(arith + 4 + 2 * i, CTX_MV_F1, CTX_MV_DATA);
                block->u.mv[i][1] += dirac_get_arith_int(arith + 5 + 2 * i, CTX_MV_F1, CTX_MV_DATA);
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
            }
        }
}

/**
 * Copies the current block to the other blocks covered by the current superblock split mode
 */
static void propagate_block_data(DiracBlock *block, int stride, int size)
{
    int x, y;
    DiracBlock *dst = block;

    for (x = 1; x < size; x++)
        dst[x] = *block;

    for (y = 1; y < size; y++) {
        dst += stride;
        for (x = 0; x < size; x++)
            dst[x] = *block;
    }
}

1182 1183 1184 1185
/**
 * Dirac Specification ->
 * 12. Block motion data syntax
 */
1186
static int dirac_unpack_block_motion_data(DiracContext *s)
1187 1188 1189 1190 1191 1192 1193 1194
{
    GetBitContext *gb = &s->gb;
    uint8_t *sbsplit = s->sbsplit;
    int i, x, y, q, p;
    DiracArith arith[8];

    align_get_bits(gb);

1195
    /* [DIRAC_STD] 11.2.4 and 12.2.1 Number of blocks and superblocks */
1196 1197
    s->sbwidth  = DIVRNDUP(s->source.width,  4*s->plane[0].xbsep);
    s->sbheight = DIVRNDUP(s->source.height, 4*s->plane[0].ybsep);
1198 1199
    s->blwidth  = 4 * s->sbwidth;
    s->blheight = 4 * s->sbheight;
1200

1201 1202 1203
    /* [DIRAC_STD] 12.3.1 Superblock splitting modes. superblock_split_modes()
       decode superblock split modes */
    ff_dirac_init_arith_decoder(arith, gb, svq3_get_ue_golomb(gb));     /* svq3_get_ue_golomb(gb) is the length */
1204 1205
    for (y = 0; y < s->sbheight; y++) {
        for (x = 0; x < s->sbwidth; x++) {
1206 1207 1208
            unsigned int split  = dirac_get_arith_uint(arith, CTX_SB_F1, CTX_SB_DATA);
            if (split > 2)
                return -1;
1209 1210 1211 1212 1213
            sbsplit[x] = (split + pred_sbsplit(sbsplit+x, s->sbwidth, x, y)) % 3;
        }
        sbsplit += s->sbwidth;
    }

1214
    /* setup arith decoding */
1215 1216
    ff_dirac_init_arith_decoder(arith, gb, svq3_get_ue_golomb(gb));
    for (i = 0; i < s->num_refs; i++) {
1217 1218
        ff_dirac_init_arith_decoder(arith + 4 + 2 * i, gb, svq3_get_ue_golomb(gb));
        ff_dirac_init_arith_decoder(arith + 5 + 2 * i, gb, svq3_get_ue_golomb(gb));
1219 1220 1221 1222 1223 1224
    }
    for (i = 0; i < 3; i++)
        ff_dirac_init_arith_decoder(arith+1+i, gb, svq3_get_ue_golomb(gb));

    for (y = 0; y < s->sbheight; y++)
        for (x = 0; x < s->sbwidth; x++) {
1225 1226
            int blkcnt = 1 << s->sbsplit[y * s->sbwidth + x];
            int step   = 4 >> s->sbsplit[y * s->sbwidth + x];
1227 1228 1229

            for (q = 0; q < blkcnt; q++)
                for (p = 0; p < blkcnt; p++) {
1230 1231
                    int bx = 4 * x + p*step;
                    int by = 4 * y + q*step;
1232 1233 1234 1235 1236
                    DiracBlock *block = &s->blmotion[by*s->blwidth + bx];
                    decode_block_params(s, arith, block, s->blwidth, bx, by);
                    propagate_block_data(block, s->blwidth, step);
                }
        }
1237 1238

    return 0;
1239 1240 1241 1242
}

static int weight(int i, int blen, int offset)
{
1243
#define ROLLOFF(i) offset == 1 ? ((i) ? 5 : 3) :        \
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
    (1 + (6*(i) + offset - 1) / (2*offset - 1))

    if (i < 2*offset)
        return ROLLOFF(i);
    else if (i > blen-1 - 2*offset)
        return ROLLOFF(blen-1 - i);
    return 8;
}

static void init_obmc_weight_row(Plane *p, uint8_t *obmc_weight, int stride,
                                 int left, int right, int wy)
{
    int x;
    for (x = 0; left && x < p->xblen >> 1; x++)
        obmc_weight[x] = wy*8;
    for (; x < p->xblen >> right; x++)
        obmc_weight[x] = wy*weight(x, p->xblen, p->xoffset);
    for (; x < p->xblen; x++)
        obmc_weight[x] = wy*8;
    for (; x < stride; x++)
        obmc_weight[x] = 0;
}

static void init_obmc_weight(Plane *p, uint8_t *obmc_weight, int stride,
                             int left, int right, int top, int bottom)
{
    int y;
    for (y = 0; top && y < p->yblen >> 1; y++) {
        init_obmc_weight_row(p, obmc_weight, stride, left, right, 8);
        obmc_weight += stride;
    }
    for (; y < p->yblen >> bottom; y++) {
        int wy = weight(y, p->yblen, p->yoffset);
        init_obmc_weight_row(p, obmc_weight, stride, left, right, wy);
        obmc_weight += stride;
    }
    for (; y < p->yblen; y++) {
        init_obmc_weight_row(p, obmc_weight, stride, left, right, 8);
        obmc_weight += stride;
    }
}

static void init_obmc_weights(DiracContext *s, Plane *p, int by)
{
    int top = !by;
    int bottom = by == s->blheight-1;

1291
    /* don't bother re-initing for rows 2 to blheight-2, the weights don't change */
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
    if (top || bottom || by == 1) {
        init_obmc_weight(p, s->obmc_weight[0], MAX_BLOCKSIZE, 1, 0, top, bottom);
        init_obmc_weight(p, s->obmc_weight[1], MAX_BLOCKSIZE, 0, 0, top, bottom);
        init_obmc_weight(p, s->obmc_weight[2], MAX_BLOCKSIZE, 0, 1, top, bottom);
    }
}

static const uint8_t epel_weights[4][4][4] = {
    {{ 16,  0,  0,  0 },
     { 12,  4,  0,  0 },
     {  8,  8,  0,  0 },
     {  4, 12,  0,  0 }},
    {{ 12,  0,  4,  0 },
     {  9,  3,  3,  1 },
     {  6,  6,  2,  2 },
     {  3,  9,  1,  3 }},
    {{  8,  0,  8,  0 },
     {  6,  2,  6,  2 },
     {  4,  4,  4,  4 },
     {  2,  6,  2,  6 }},
    {{  4,  0, 12,  0 },
     {  3,  1,  9,  3 },
     {  2,  2,  6,  6 },
     {  1,  3,  3,  9 }}
};

/**
 * For block x,y, determine which of the hpel planes to do bilinear
 * interpolation from and set src[] to the location in each hpel plane
 * to MC from.
 *
 * @return the index of the put_dirac_pixels_tab function to use
 *  0 for 1 plane (fpel,hpel), 1 for 2 planes (qpel), 2 for 4 planes (qpel), and 3 for epel
 */
static int mc_subpel(DiracContext *s, DiracBlock *block, const uint8_t *src[5],
                     int x, int y, int ref, int plane)
{
    Plane *p = &s->plane[plane];
    uint8_t **ref_hpel = s->ref_pics[ref]->hpel[plane];
    int motion_x = block->u.mv[ref][0];
    int motion_y = block->u.mv[ref][1];
    int mx, my, i, epel, nplanes = 0;

    if (plane) {
        motion_x >>= s->chroma_x_shift;
        motion_y >>= s->chroma_y_shift;
    }

1340 1341
    mx         = motion_x & ~(-1 << s->mv_precision);
    my         = motion_y & ~(-1 << s->mv_precision);
1342 1343
    motion_x >>= s->mv_precision;
    motion_y >>= s->mv_precision;
1344 1345
    /* normalize subpel coordinates to epel */
    /* TODO: template this function? */
1346 1347
    mx      <<= 3 - s->mv_precision;
    my      <<= 3 - s->mv_precision;
1348 1349 1350 1351 1352

    x += motion_x;
    y += motion_y;
    epel = (mx|my)&1;

1353
    /* hpel position */
1354 1355 1356 1357
    if (!((mx|my)&3)) {
        nplanes = 1;
        src[0] = ref_hpel[(my>>1)+(mx>>2)] + y*p->stride + x;
    } else {
1358
        /* qpel or epel */
1359 1360 1361 1362
        nplanes = 4;
        for (i = 0; i < 4; i++)
            src[i] = ref_hpel[i] + y*p->stride + x;

1363 1364
        /* if we're interpolating in the right/bottom halves, adjust the planes as needed
           we increment x/y because the edge changes for half of the pixels */
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
        if (mx > 4) {
            src[0] += 1;
            src[2] += 1;
            x++;
        }
        if (my > 4) {
            src[0] += p->stride;
            src[1] += p->stride;
            y++;
        }

1376 1377 1378
        /* hpel planes are:
           [0]: F  [1]: H
           [2]: V  [3]: C */
1379
        if (!epel) {
1380 1381
            /* check if we really only need 2 planes since either mx or my is
               a hpel position. (epel weights of 0 handle this there) */
1382
            if (!(mx&3)) {
1383 1384
                /* mx == 0: average [0] and [2]
                   mx == 4: average [1] and [3] */
1385 1386 1387 1388 1389 1390 1391 1392
                src[!mx] = src[2 + !!mx];
                nplanes = 2;
            } else if (!(my&3)) {
                src[0] = src[(my>>1)  ];
                src[1] = src[(my>>1)+1];
                nplanes = 2;
            }
        } else {
1393
            /* adjust the ordering if needed so the weights work */
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
            if (mx > 4) {
                FFSWAP(const uint8_t *, src[0], src[1]);
                FFSWAP(const uint8_t *, src[2], src[3]);
            }
            if (my > 4) {
                FFSWAP(const uint8_t *, src[0], src[2]);
                FFSWAP(const uint8_t *, src[1], src[3]);
            }
            src[4] = epel_weights[my&3][mx&3];
        }
    }

1406
    /* fixme: v/h _edge_pos */
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
    if ((unsigned)x > p->width +EDGE_WIDTH/2 - p->xblen ||
        (unsigned)y > p->height+EDGE_WIDTH/2 - p->yblen) {
        for (i = 0; i < nplanes; i++) {
            ff_emulated_edge_mc(s->edge_emu_buffer[i], src[i], p->stride,
                                p->xblen, p->yblen, x, y,
                                p->width+EDGE_WIDTH/2, p->height+EDGE_WIDTH/2);
            src[i] = s->edge_emu_buffer[i];
        }
    }
    return (nplanes>>1) + epel;
}

static void add_dc(uint16_t *dst, int dc, int stride,
                   uint8_t *obmc_weight, int xblen, int yblen)
{
    int x, y;
    dc += 128;

    for (y = 0; y < yblen; y++) {
        for (x = 0; x < xblen; x += 2) {
            dst[x  ] += dc * obmc_weight[x  ];
            dst[x+1] += dc * obmc_weight[x+1];
        }
1430 1431
        dst          += stride;
        obmc_weight  += MAX_BLOCKSIZE;
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
    }
}

static void block_mc(DiracContext *s, DiracBlock *block,
                     uint16_t *mctmp, uint8_t *obmc_weight,
                     int plane, int dstx, int dsty)
{
    Plane *p = &s->plane[plane];
    const uint8_t *src[5];
    int idx;

    switch (block->ref&3) {
1444
    case 0: /* DC */
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
        add_dc(mctmp, block->u.dc[plane], p->stride, obmc_weight, p->xblen, p->yblen);
        return;
    case 1:
    case 2:
        idx = mc_subpel(s, block, src, dstx, dsty, (block->ref&3)-1, plane);
        s->put_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen);
        if (s->weight_func)
            s->weight_func(s->mcscratch, p->stride, s->weight_log2denom,
                           s->weight[0] + s->weight[1], p->yblen);
        break;
    case 3:
        idx = mc_subpel(s, block, src, dstx, dsty, 0, plane);
        s->put_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen);
        idx = mc_subpel(s, block, src, dstx, dsty, 1, plane);
        if (s->biweight_func) {
1460
            /* fixme: +32 is a quick hack */
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
            s->put_pixels_tab[idx](s->mcscratch + 32, src, p->stride, p->yblen);
            s->biweight_func(s->mcscratch, s->mcscratch+32, p->stride, s->weight_log2denom,
                             s->weight[0], s->weight[1], p->yblen);
        } else
            s->avg_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen);
        break;
    }
    s->add_obmc(mctmp, s->mcscratch, p->stride, obmc_weight, p->yblen);
}

static void mc_row(DiracContext *s, DiracBlock *block, uint16_t *mctmp, int plane, int dsty)
{
    Plane *p = &s->plane[plane];
    int x, dstx = p->xbsep - p->xoffset;

    block_mc(s, block, mctmp, s->obmc_weight[0], plane, -p->xoffset, dsty);
    mctmp += p->xbsep;

    for (x = 1; x < s->blwidth-1; x++) {
        block_mc(s, block+x, mctmp, s->obmc_weight[1], plane, dstx, dsty);
        dstx  += p->xbsep;
        mctmp += p->xbsep;
    }
    block_mc(s, block+x, mctmp, s->obmc_weight[2], plane, dstx, dsty);
}

static void select_dsp_funcs(DiracContext *s, int width, int height, int xblen, int yblen)
{
    int idx = 0;
    if (xblen > 8)
        idx = 1;
    if (xblen > 16)
        idx = 2;

    memcpy(s->put_pixels_tab, s->diracdsp.put_dirac_pixels_tab[idx], sizeof(s->put_pixels_tab));
    memcpy(s->avg_pixels_tab, s->diracdsp.avg_dirac_pixels_tab[idx], sizeof(s->avg_pixels_tab));
    s->add_obmc = s->diracdsp.add_dirac_obmc[idx];
    if (s->weight_log2denom > 1 || s->weight[0] != 1 || s->weight[1] != 1) {
        s->weight_func   = s->diracdsp.weight_dirac_pixels_tab[idx];
        s->biweight_func = s->diracdsp.biweight_dirac_pixels_tab[idx];
    } else {
        s->weight_func   = NULL;
        s->biweight_func = NULL;
    }
}

static void interpolate_refplane(DiracContext *s, DiracFrame *ref, int plane, int width, int height)
{
1509 1510 1511
    /* chroma allocates an edge of 8 when subsampled
       which for 4:2:2 means an h edge of 16 and v edge of 8
       just use 8 for everything for the moment */
1512 1513 1514
    int i, edge = EDGE_WIDTH/2;

    ref->hpel[plane][0] = ref->avframe.data[plane];
1515
    s->dsp.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 */
1516

1517
    /* no need for hpel if we only have fpel vectors */
1518 1519 1520 1521 1522 1523
    if (!s->mv_precision)
        return;

    for (i = 1; i < 4; i++) {
        if (!ref->hpel_base[plane][i])
            ref->hpel_base[plane][i] = av_malloc((height+2*edge) * ref->avframe.linesize[plane] + 32);
1524
        /* we need to be 16-byte aligned even for chroma */
1525 1526 1527 1528 1529 1530 1531 1532
        ref->hpel[plane][i] = ref->hpel_base[plane][i] + edge*ref->avframe.linesize[plane] + 16;
    }

    if (!ref->interpolated[plane]) {
        s->diracdsp.dirac_hpel_filter(ref->hpel[plane][1], ref->hpel[plane][2],
                                      ref->hpel[plane][3], ref->hpel[plane][0],
                                      ref->avframe.linesize[plane], width, height);
        s->dsp.draw_edges(ref->hpel[plane][1], ref->avframe.linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);
1533
        s->dsp.draw_edges(ref->hpel[plane][2], ref->avframe.linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);
1534 1535 1536 1537 1538
        s->dsp.draw_edges(ref->hpel[plane][3], ref->avframe.linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);
    }
    ref->interpolated[plane] = 1;
}

1539 1540 1541 1542
/**
 * Dirac Specification ->
 * 13.0 Transform data syntax. transform_data()
 */
1543 1544
static int dirac_decode_frame_internal(DiracContext *s)
{
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
    DWTContext d;
    int y, i, comp, dsty;

    if (s->low_delay) {
        /* [DIRAC_STD] 13.5.1 low_delay_transform_data() */
        for (comp = 0; comp < 3; comp++) {
            Plane *p = &s->plane[comp];
            memset(p->idwt_buf, 0, p->idwt_stride * p->idwt_height * sizeof(IDWTELEM));
        }
        if (!s->zero_res)
            decode_lowdelay(s);
    }
1557 1558

    for (comp = 0; comp < 3; comp++) {
1559
        Plane *p       = &s->plane[comp];
1560 1561 1562 1563 1564
        uint8_t *frame = s->current_picture->avframe.data[comp];

        /* FIXME: small resolutions */
        for (i = 0; i < 4; i++)
            s->edge_emu_buffer[i] = s->edge_emu_buffer_base + i*FFALIGN(p->width, 16);
1565

1566 1567 1568 1569 1570 1571 1572 1573
        if (!s->zero_res && !s->low_delay)
        {
            memset(p->idwt_buf, 0, p->idwt_stride * p->idwt_height * sizeof(IDWTELEM));
            decode_component(s, comp); /* [DIRAC_STD] 13.4.1 core_transform_data() */
        }
        if (ff_spatial_idwt_init2(&d, p->idwt_buf, p->idwt_width, p->idwt_height, p->idwt_stride,
                                  s->wavelet_idx+2, s->wavelet_depth, p->idwt_tmp))
            return -1;
1574

1575 1576 1577 1578 1579 1580 1581 1582
        if (!s->num_refs) { /* intra */
            for (y = 0; y < p->height; y += 16) {
                ff_spatial_idwt_slice2(&d, y+16); /* decode */
                s->diracdsp.put_signed_rect_clamped(frame + y*p->stride, p->stride,
                                                    p->idwt_buf + y*p->idwt_stride, p->idwt_stride, p->width, 16);
            }
        } else { /* inter */
            int rowheight = p->ybsep*p->stride;
1583

1584
            select_dsp_funcs(s, p->width, p->height, p->xblen, p->yblen);
1585

1586 1587
            for (i = 0; i < s->num_refs; i++)
                interpolate_refplane(s, s->ref_pics[i], comp, p->width, p->height);
1588

1589
            memset(s->mctmp, 0, 4*p->yoffset*p->stride);
1590

1591 1592
            dsty = -p->yoffset;
            for (y = 0; y < s->blheight; y++) {
1593 1594 1595
                int h     = 0,
                    start = FFMAX(dsty, 0);
                uint16_t *mctmp    = s->mctmp + y*rowheight;
1596
                DiracBlock *blocks = s->blmotion + y*s->blwidth;
1597

1598
                init_obmc_weights(s, p, y);
1599

1600 1601 1602 1603 1604 1605
                if (y == s->blheight-1 || start+p->ybsep > p->height)
                    h = p->height - start;
                else
                    h = p->ybsep - (start - dsty);
                if (h < 0)
                    break;
1606

1607 1608
                memset(mctmp+2*p->yoffset*p->stride, 0, 2*rowheight);
                mc_row(s, blocks, mctmp, comp, dsty);
1609

1610 1611 1612 1613 1614 1615 1616 1617
                mctmp += (start - dsty)*p->stride + p->xoffset;
                ff_spatial_idwt_slice2(&d, start + h); /* decode */
                s->diracdsp.add_rect_clamped(frame + start*p->stride, mctmp, p->stride,
                                             p->idwt_buf + start*p->idwt_stride, p->idwt_stride, p->width, h);

                dsty += p->ybsep;
            }
        }
1618 1619 1620
    }


1621
    return 0;
1622 1623
}

1624 1625 1626 1627
/**
 * Dirac Specification ->
 * 11.1.1 Picture Header. picture_header()
 */
1628 1629 1630 1631 1632 1633
static int dirac_decode_picture_header(DiracContext *s)
{
    int retire, picnum;
    int i, j, refnum, refdist;
    GetBitContext *gb = &s->gb;

1634
    /* [DIRAC_STD] 11.1.1 Picture Header. picture_header() PICTURE_NUM */
1635 1636 1637 1638 1639
    picnum = s->current_picture->avframe.display_picture_number = get_bits_long(gb, 32);


    av_log(s->avctx,AV_LOG_DEBUG,"PICTURE_NUM: %d\n",picnum);

1640 1641
    /* if this is the first keyframe after a sequence header, start our
       reordering from here */
1642 1643 1644 1645 1646 1647 1648 1649
    if (s->frame_number < 0)
        s->frame_number = picnum;

    s->ref_pics[0] = s->ref_pics[1] = NULL;
    for (i = 0; i < s->num_refs; i++) {
        refnum = picnum + dirac_get_se_golomb(gb);
        refdist = INT_MAX;

1650 1651
        /* find the closest reference to the one we want */
        /* Jordi: this is needed if the referenced picture hasn't yet arrived */
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
        for (j = 0; j < MAX_REFERENCE_FRAMES && refdist; j++)
            if (s->ref_frames[j]
                && FFABS(s->ref_frames[j]->avframe.display_picture_number - refnum) < refdist) {
                s->ref_pics[i] = s->ref_frames[j];
                refdist = FFABS(s->ref_frames[j]->avframe.display_picture_number - refnum);
            }

        if (!s->ref_pics[i] || refdist)
            av_log(s->avctx, AV_LOG_DEBUG, "Reference not found\n");

1662
        /* if there were no references at all, allocate one */
1663 1664 1665 1666 1667 1668 1669 1670
        if (!s->ref_pics[i])
            for (j = 0; j < MAX_FRAMES; j++)
                if (!s->all_frames[j].avframe.data[0]) {
                    s->ref_pics[i] = &s->all_frames[j];
                    s->avctx->get_buffer(s->avctx, &s->ref_pics[i]->avframe);
                }
    }

1671
    /* retire the reference frames that are not used anymore */
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
    if (s->current_picture->avframe.reference) {
        retire = picnum + dirac_get_se_golomb(gb);
        if (retire != picnum) {
            DiracFrame *retire_pic = remove_frame(s->ref_frames, retire);

            if (retire_pic)
                retire_pic->avframe.reference &= DELAYED_PIC_REF;
            else
                av_log(s->avctx, AV_LOG_DEBUG, "Frame to retire not found\n");
        }

1683
        /* if reference array is full, remove the oldest as per the spec */
1684 1685 1686 1687 1688 1689 1690
        while (add_frame(s->ref_frames, MAX_REFERENCE_FRAMES, s->current_picture)) {
            av_log(s->avctx, AV_LOG_ERROR, "Reference frame overflow\n");
            remove_frame(s->ref_frames, s->ref_frames[0]->avframe.display_picture_number)->avframe.reference &= DELAYED_PIC_REF;
        }
    }

    if (s->num_refs) {
1691
        if (dirac_unpack_prediction_parameters(s))  /* [DIRAC_STD] 11.2 Picture Prediction Data. picture_prediction() */
1692
            return -1;
1693 1694
        if (dirac_unpack_block_motion_data(s))      /* [DIRAC_STD] 12. Block motion data syntax                       */
            return -1;
1695
    }
1696
    if (dirac_unpack_idwt_params(s))                /* [DIRAC_STD] 11.3 Wavelet transform data                        */
1697 1698
        return -1;

1699
    init_planes(s);
1700 1701 1702
    return 0;
}

1703
static int get_delayed_pic(DiracContext *s, AVFrame *picture, int *data_size)
1704 1705
{
    DiracFrame *out = s->delay_frames[0];
1706
    int i, out_idx  = 0;
1707

1708
    /* find frame with lowest picture number */
1709 1710
    for (i = 1; s->delay_frames[i]; i++)
        if (s->delay_frames[i]->avframe.display_picture_number < out->avframe.display_picture_number) {
1711
            out     = s->delay_frames[i];
1712 1713 1714 1715 1716 1717 1718 1719
            out_idx = i;
        }

    for (i = out_idx; s->delay_frames[i]; i++)
        s->delay_frames[i] = s->delay_frames[i+1];

    if (out) {
        out->avframe.reference ^= DELAYED_PIC_REF;
1720 1721
        *data_size = sizeof(AVFrame);
        *(AVFrame *)picture = out->avframe;
1722 1723 1724 1725 1726
    }

    return 0;
}

1727 1728 1729 1730 1731
/**
 * Dirac Specification ->
 * 9.6 Parse Info Header Syntax. parse_info()
 * 4 byte start code + byte parse code + 4 byte size + 4 byte previous size
 */
1732 1733
#define DATA_UNIT_HEADER_SIZE 13

1734 1735
/* [DIRAC_STD] dirac_decode_data_unit makes reference to the while defined in 9.3
   inside the function parse_sequence() */
1736 1737
static int dirac_decode_data_unit(AVCodecContext *avctx, const uint8_t *buf, int size)
{
1738 1739
    DiracContext *s   = avctx->priv_data;
    DiracFrame *pic   = NULL;
1740
    int i, parse_code = buf[4];
1741
    unsigned tmp;
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751

    if (size < DATA_UNIT_HEADER_SIZE)
        return -1;

    init_get_bits(&s->gb, &buf[13], 8*(size - DATA_UNIT_HEADER_SIZE));

    if (parse_code == pc_seq_header) {
        if (s->seen_sequence_header)
            return 0;

1752
        /* [DIRAC_STD] 10. Sequence header */
1753 1754 1755 1756 1757 1758 1759 1760 1761
        if (avpriv_dirac_parse_sequence_header(avctx, &s->gb, &s->source))
            return -1;

        avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);

        if (alloc_sequence_buffers(s))
            return -1;

        s->seen_sequence_header = 1;
1762
    } else if (parse_code == pc_eos) { /* [DIRAC_STD] End of Sequence */
1763 1764 1765
        free_sequence_buffers(s);
        s->seen_sequence_header = 0;
    } else if (parse_code == pc_aux_data) {
1766
        if (buf[13] == 1) {     /* encoder implementation/version */
1767
            int ver[3];
1768 1769
            /* versions older than 1.0.8 don't store quant delta for
               subbands with only one codeblock */
1770 1771 1772 1773
            if (sscanf(buf+14, "Schroedinger %d.%d.%d", ver, ver+1, ver+2) == 3)
                if (ver[0] == 1 && ver[1] == 0 && ver[2] <= 7)
                    s->old_delta_quant = 1;
        }
1774
    } else if (parse_code & 0x8) {  /* picture data unit */
1775 1776 1777 1778 1779
        if (!s->seen_sequence_header) {
            av_log(avctx, AV_LOG_DEBUG, "Dropping frame without sequence header\n");
            return -1;
        }

1780
        /* find an unused frame */
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
        for (i = 0; i < MAX_FRAMES; i++)
            if (s->all_frames[i].avframe.data[0] == NULL)
                pic = &s->all_frames[i];
        if (!pic) {
            av_log(avctx, AV_LOG_ERROR, "framelist full\n");
            return -1;
        }

        avcodec_get_frame_defaults(&pic->avframe);

1791
        /* [DIRAC_STD] Defined in 9.6.1 ... */
1792 1793 1794 1795 1796 1797
        tmp            =  parse_code & 0x03;                   /* [DIRAC_STD] num_refs()      */
        if (tmp > 2) {
            av_log(avctx, AV_LOG_ERROR, "num_refs of 3\n");
            return -1;
        }
        s->num_refs    = tmp;
1798 1799 1800 1801 1802
        s->is_arith    = (parse_code & 0x48) == 0x08;          /* [DIRAC_STD] using_ac()      */
        s->low_delay   = (parse_code & 0x88) == 0x88;          /* [DIRAC_STD] is_low_delay()  */
        pic->avframe.reference = (parse_code & 0x0C) == 0x0C;  /* [DIRAC_STD]  is_reference() */
        pic->avframe.key_frame = s->num_refs == 0;             /* [DIRAC_STD] is_intra()      */
        pic->avframe.pict_type = s->num_refs + 1;              /* Definition of AVPictureType in avutil.h */
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812

        if (avctx->get_buffer(avctx, &pic->avframe) < 0) {
            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
            return -1;
        }
        s->current_picture = pic;
        s->plane[0].stride = pic->avframe.linesize[0];
        s->plane[1].stride = pic->avframe.linesize[1];
        s->plane[2].stride = pic->avframe.linesize[2];

1813
        /* [DIRAC_STD] 11.1 Picture parse. picture_parse() */
1814 1815 1816
        if (dirac_decode_picture_header(s))
            return -1;

1817
        /* [DIRAC_STD] 13.0 Transform data syntax. transform_data() */
1818 1819 1820 1821 1822 1823 1824 1825
        if (dirac_decode_frame_internal(s))
            return -1;
    }
    return 0;
}

static int dirac_decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *pkt)
{
1826
    DiracContext *s     = avctx->priv_data;
1827
    DiracFrame *picture = data;
1828 1829
    uint8_t *buf        = pkt->data;
    int buf_size        = pkt->size;
1830 1831
    int i, data_unit_size, buf_idx = 0;

1832
    /* release unused frames */
1833 1834 1835 1836 1837 1838 1839 1840 1841
    for (i = 0; i < MAX_FRAMES; i++)
        if (s->all_frames[i].avframe.data[0] && !s->all_frames[i].avframe.reference) {
            avctx->release_buffer(avctx, &s->all_frames[i].avframe);
            memset(s->all_frames[i].interpolated, 0, sizeof(s->all_frames[i].interpolated));
        }

    s->current_picture = NULL;
    *data_size = 0;

1842
    /* end of stream, so flush delayed pics */
1843
    if (buf_size == 0)
1844
        return get_delayed_pic(s, (AVFrame *)data, data_size);
1845 1846

    for (;;) {
1847 1848 1849
        /*[DIRAC_STD] Here starts the code from parse_info() defined in 9.6
          [DIRAC_STD] PARSE_INFO_PREFIX = "BBCD" as defined in ISO/IEC 646
          BBCD start code search */
1850 1851 1852 1853 1854
        for (; buf_idx + DATA_UNIT_HEADER_SIZE < buf_size; buf_idx++) {
            if (buf[buf_idx  ] == 'B' && buf[buf_idx+1] == 'B' &&
                buf[buf_idx+2] == 'C' && buf[buf_idx+3] == 'D')
                break;
        }
1855
        /* BBCD found or end of data */
1856 1857 1858 1859
        if (buf_idx + DATA_UNIT_HEADER_SIZE >= buf_size)
            break;

        data_unit_size = AV_RB32(buf+buf_idx+5);
1860 1861
        if (buf_idx + data_unit_size > buf_size || !data_unit_size) {
            if(buf_idx + data_unit_size > buf_size)
1862
            av_log(s->avctx, AV_LOG_ERROR,
1863 1864
                   "Data unit with size %d is larger than input buffer, discarding\n",
                   data_unit_size);
1865 1866 1867
            buf_idx += 4;
            continue;
        }
1868
        /* [DIRAC_STD] dirac_decode_data_unit makes reference to the while defined in 9.3 inside the function parse_sequence() */
1869
        if (dirac_decode_data_unit(avctx, buf+buf_idx, data_unit_size))
1870
        {
1871
            av_log(s->avctx, AV_LOG_ERROR,"Error in dirac_decode_data_unit\n");
1872
            return -1;
1873
        }
1874 1875 1876 1877
        buf_idx += data_unit_size;
    }

    if (!s->current_picture)
1878
        return buf_size;
1879 1880 1881 1882 1883 1884 1885 1886

    if (s->current_picture->avframe.display_picture_number > s->frame_number) {
        DiracFrame *delayed_frame = remove_frame(s->delay_frames, s->frame_number);

        s->current_picture->avframe.reference |= DELAYED_PIC_REF;

        if (add_frame(s->delay_frames, MAX_DELAY, s->current_picture)) {
            int min_num = s->delay_frames[0]->avframe.display_picture_number;
1887
            /* Too many delayed frames, so we display the frame with the lowest pts */
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
            av_log(avctx, AV_LOG_ERROR, "Delay frame overflow\n");
            delayed_frame = s->delay_frames[0];

            for (i = 1; s->delay_frames[i]; i++)
                if (s->delay_frames[i]->avframe.display_picture_number < min_num)
                    min_num = s->delay_frames[i]->avframe.display_picture_number;

            delayed_frame = remove_frame(s->delay_frames, min_num);
            add_frame(s->delay_frames, MAX_DELAY, s->current_picture);
        }

        if (delayed_frame) {
            delayed_frame->avframe.reference ^= DELAYED_PIC_REF;
1901 1902
            *(AVFrame*)data = delayed_frame->avframe;
            *data_size = sizeof(AVFrame);
1903 1904
        }
    } else if (s->current_picture->avframe.display_picture_number == s->frame_number) {
1905 1906 1907
        /* The right frame at the right time :-) */
        *(AVFrame*)data = s->current_picture->avframe;
        *data_size = sizeof(AVFrame);
1908 1909 1910 1911 1912 1913 1914 1915 1916
    }

    if (*data_size)
        s->frame_number = picture->avframe.display_picture_number + 1;

    return buf_idx;
}

AVCodec ff_dirac_decoder = {
1917 1918
    .name           = "dirac",
    .type           = AVMEDIA_TYPE_VIDEO,
1919
    .id             = AV_CODEC_ID_DIRAC,
1920 1921 1922 1923 1924 1925 1926
    .priv_data_size = sizeof(DiracContext),
    .init           = dirac_decode_init,
    .close          = dirac_decode_end,
    .decode         = dirac_decode_frame,
    .capabilities   = CODEC_CAP_DELAY,
    .flush          = dirac_decode_flush,
    .long_name      = NULL_IF_CONFIG_SMALL("BBC Dirac VC-2"),
1927
};