]> git.sesse.net Git - ffmpeg/blob - libavcodec/diracdec.c
libavformat/matroskaenc: omit segment UID for webm
[ffmpeg] / libavcodec / diracdec.c
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 "avcodec.h"
30 #include "get_bits.h"
31 #include "bytestream.h"
32 #include "internal.h"
33 #include "golomb.h"
34 #include "dirac_arith.h"
35 #include "mpeg12data.h"
36 #include "libavcodec/mpegvideo.h"
37 #include "mpegvideoencdsp.h"
38 #include "dirac_dwt.h"
39 #include "dirac.h"
40 #include "diractab.h"
41 #include "diracdsp.h"
42 #include "videodsp.h"
43
44 /**
45  * The spec limits this to 3 for frame coding, but in practice can be as high as 6
46  */
47 #define MAX_REFERENCE_FRAMES 8
48 #define MAX_DELAY 5         /* limit for main profile for frame coding (TODO: field coding) */
49 #define MAX_FRAMES (MAX_REFERENCE_FRAMES + MAX_DELAY + 1)
50 #define MAX_QUANT 255        /* max quant for VC-2 */
51 #define MAX_BLOCKSIZE 32    /* maximum xblen/yblen we support */
52
53 /**
54  * DiracBlock->ref flags, if set then the block does MC from the given ref
55  */
56 #define DIRAC_REF_MASK_REF1   1
57 #define DIRAC_REF_MASK_REF2   2
58 #define DIRAC_REF_MASK_GLOBAL 4
59
60 /**
61  * Value of Picture.reference when Picture is not a reference picture, but
62  * is held for delayed output.
63  */
64 #define DELAYED_PIC_REF 4
65
66 #define CALC_PADDING(size, depth)                       \
67     (((size + (1 << depth) - 1) >> depth) << depth)
68
69 #define DIVRNDUP(a, b) (((a) + (b) - 1) / (b))
70
71 typedef struct {
72     AVFrame *avframe;
73     int interpolated[3];    /* 1 if hpel[] is valid */
74     uint8_t *hpel[3][4];
75     uint8_t *hpel_base[3][4];
76     int reference;
77 } DiracFrame;
78
79 typedef struct {
80     union {
81         int16_t mv[2][2];
82         int16_t dc[3];
83     } u; /* anonymous unions aren't in C99 :( */
84     uint8_t ref;
85 } DiracBlock;
86
87 typedef struct SubBand {
88     int level;
89     int orientation;
90     int stride; /* in bytes */
91     int width;
92     int height;
93     int pshift;
94     int quant;
95     uint8_t *ibuf;
96     struct SubBand *parent;
97
98     /* for low delay */
99     unsigned length;
100     const uint8_t *coeff_data;
101 } SubBand;
102
103 typedef struct Plane {
104     DWTPlane idwt;
105
106     int width;
107     int height;
108     ptrdiff_t stride;
109
110     /* block length */
111     uint8_t xblen;
112     uint8_t yblen;
113     /* block separation (block n+1 starts after this many pixels in block n) */
114     uint8_t xbsep;
115     uint8_t ybsep;
116     /* amount of overspill on each edge (half of the overlap between blocks) */
117     uint8_t xoffset;
118     uint8_t yoffset;
119
120     SubBand band[MAX_DWT_LEVELS][4];
121 } Plane;
122
123 typedef struct DiracContext {
124     AVCodecContext *avctx;
125     MpegvideoEncDSPContext mpvencdsp;
126     VideoDSPContext vdsp;
127     DiracDSPContext diracdsp;
128     DiracVersionInfo version;
129     GetBitContext gb;
130     AVDiracSeqHeader seq;
131     int seen_sequence_header;
132     int frame_number;           /* number of the next frame to display       */
133     Plane plane[3];
134     int chroma_x_shift;
135     int chroma_y_shift;
136
137     int bit_depth;              /* bit depth                                 */
138     int pshift;                 /* pixel shift = bit_depth > 8               */
139
140     int zero_res;               /* zero residue flag                         */
141     int is_arith;               /* whether coeffs use arith or golomb coding */
142     int core_syntax;            /* use core syntax only                      */
143     int low_delay;              /* use the low delay syntax                  */
144     int hq_picture;             /* high quality picture, enables low_delay   */
145     int ld_picture;             /* use low delay picture, turns on low_delay */
146     int dc_prediction;          /* has dc prediction                         */
147     int globalmc_flag;          /* use global motion compensation            */
148     int num_refs;               /* number of reference pictures              */
149
150     /* wavelet decoding */
151     unsigned wavelet_depth;     /* depth of the IDWT                         */
152     unsigned wavelet_idx;
153
154     /**
155      * schroedinger older than 1.0.8 doesn't store
156      * quant delta if only one codebook exists in a band
157      */
158     unsigned old_delta_quant;
159     unsigned codeblock_mode;
160
161     unsigned num_x;              /* number of horizontal slices               */
162     unsigned num_y;              /* number of vertical slices                 */
163
164     struct {
165         unsigned width;
166         unsigned height;
167     } codeblock[MAX_DWT_LEVELS+1];
168
169     struct {
170         AVRational bytes;       /* average bytes per slice                   */
171         uint8_t quant[MAX_DWT_LEVELS][4]; /* [DIRAC_STD] E.1 */
172     } lowdelay;
173
174     struct {
175         unsigned prefix_bytes;
176         uint64_t size_scaler;
177     } highquality;
178
179     struct {
180         int pan_tilt[2];        /* pan/tilt vector                           */
181         int zrs[2][2];          /* zoom/rotate/shear matrix                  */
182         int perspective[2];     /* perspective vector                        */
183         unsigned zrs_exp;
184         unsigned perspective_exp;
185     } globalmc[2];
186
187     /* motion compensation */
188     uint8_t mv_precision;       /* [DIRAC_STD] REFS_WT_PRECISION             */
189     int16_t weight[2];          /* [DIRAC_STD] REF1_WT and REF2_WT           */
190     unsigned weight_log2denom;  /* [DIRAC_STD] REFS_WT_PRECISION             */
191
192     int blwidth;                /* number of blocks (horizontally)           */
193     int blheight;               /* number of blocks (vertically)             */
194     int sbwidth;                /* number of superblocks (horizontally)      */
195     int sbheight;               /* number of superblocks (vertically)        */
196
197     uint8_t *sbsplit;
198     DiracBlock *blmotion;
199
200     uint8_t *edge_emu_buffer[4];
201     uint8_t *edge_emu_buffer_base;
202
203     uint16_t *mctmp;            /* buffer holding the MC data multiplied by OBMC weights */
204     uint8_t *mcscratch;
205     int buffer_stride;
206
207     DECLARE_ALIGNED(16, uint8_t, obmc_weight)[3][MAX_BLOCKSIZE*MAX_BLOCKSIZE];
208
209     void (*put_pixels_tab[4])(uint8_t *dst, const uint8_t *src[5], int stride, int h);
210     void (*avg_pixels_tab[4])(uint8_t *dst, const uint8_t *src[5], int stride, int h);
211     void (*add_obmc)(uint16_t *dst, const uint8_t *src, int stride, const uint8_t *obmc_weight, int yblen);
212     dirac_weight_func weight_func;
213     dirac_biweight_func biweight_func;
214
215     DiracFrame *current_picture;
216     DiracFrame *ref_pics[2];
217
218     DiracFrame *ref_frames[MAX_REFERENCE_FRAMES+1];
219     DiracFrame *delay_frames[MAX_DELAY+1];
220     DiracFrame all_frames[MAX_FRAMES];
221 } DiracContext;
222
223 enum dirac_subband {
224     subband_ll = 0,
225     subband_hl = 1,
226     subband_lh = 2,
227     subband_hh = 3,
228     subband_nb,
229 };
230
231 /* magic number division by 3 from schroedinger */
232 static inline int divide3(int x)
233 {
234     return ((x+1)*21845 + 10922) >> 16;
235 }
236
237 static DiracFrame *remove_frame(DiracFrame *framelist[], int picnum)
238 {
239     DiracFrame *remove_pic = NULL;
240     int i, remove_idx = -1;
241
242     for (i = 0; framelist[i]; i++)
243         if (framelist[i]->avframe->display_picture_number == picnum) {
244             remove_pic = framelist[i];
245             remove_idx = i;
246         }
247
248     if (remove_pic)
249         for (i = remove_idx; framelist[i]; i++)
250             framelist[i] = framelist[i+1];
251
252     return remove_pic;
253 }
254
255 static int add_frame(DiracFrame *framelist[], int maxframes, DiracFrame *frame)
256 {
257     int i;
258     for (i = 0; i < maxframes; i++)
259         if (!framelist[i]) {
260             framelist[i] = frame;
261             return 0;
262         }
263     return -1;
264 }
265
266 static int alloc_sequence_buffers(DiracContext *s)
267 {
268     int sbwidth  = DIVRNDUP(s->seq.width,  4);
269     int sbheight = DIVRNDUP(s->seq.height, 4);
270     int i, w, h, top_padding;
271
272     /* todo: think more about this / use or set Plane here */
273     for (i = 0; i < 3; i++) {
274         int max_xblen = MAX_BLOCKSIZE >> (i ? s->chroma_x_shift : 0);
275         int max_yblen = MAX_BLOCKSIZE >> (i ? s->chroma_y_shift : 0);
276         w = s->seq.width  >> (i ? s->chroma_x_shift : 0);
277         h = s->seq.height >> (i ? s->chroma_y_shift : 0);
278
279         /* we allocate the max we support here since num decompositions can
280          * change from frame to frame. Stride is aligned to 16 for SIMD, and
281          * 1<<MAX_DWT_LEVELS top padding to avoid if(y>0) in arith decoding
282          * MAX_BLOCKSIZE padding for MC: blocks can spill up to half of that
283          * on each side */
284         top_padding = FFMAX(1<<MAX_DWT_LEVELS, max_yblen/2);
285         w = FFALIGN(CALC_PADDING(w, MAX_DWT_LEVELS), 8); /* FIXME: Should this be 16 for SSE??? */
286         h = top_padding + CALC_PADDING(h, MAX_DWT_LEVELS) + max_yblen/2;
287
288         s->plane[i].idwt.buf_base = av_mallocz_array((w+max_xblen), h * (2 << s->pshift));
289         s->plane[i].idwt.tmp      = av_malloc_array((w+16), 2 << s->pshift);
290         s->plane[i].idwt.buf      = s->plane[i].idwt.buf_base + (top_padding*w)*(2 << s->pshift);
291         if (!s->plane[i].idwt.buf_base || !s->plane[i].idwt.tmp)
292             return AVERROR(ENOMEM);
293     }
294
295     /* fixme: allocate using real stride here */
296     s->sbsplit  = av_malloc_array(sbwidth, sbheight);
297     s->blmotion = av_malloc_array(sbwidth, sbheight * 16 * sizeof(*s->blmotion));
298
299     if (!s->sbsplit || !s->blmotion)
300         return AVERROR(ENOMEM);
301     return 0;
302 }
303
304 static int alloc_buffers(DiracContext *s, int stride)
305 {
306     int w = s->seq.width;
307     int h = s->seq.height;
308
309     av_assert0(stride >= w);
310     stride += 64;
311
312     if (s->buffer_stride >= stride)
313         return 0;
314     s->buffer_stride = 0;
315
316     av_freep(&s->edge_emu_buffer_base);
317     memset(s->edge_emu_buffer, 0, sizeof(s->edge_emu_buffer));
318     av_freep(&s->mctmp);
319     av_freep(&s->mcscratch);
320
321     s->edge_emu_buffer_base = av_malloc_array(stride, MAX_BLOCKSIZE);
322
323     s->mctmp     = av_malloc_array((stride+MAX_BLOCKSIZE), (h+MAX_BLOCKSIZE) * sizeof(*s->mctmp));
324     s->mcscratch = av_malloc_array(stride, MAX_BLOCKSIZE);
325
326     if (!s->edge_emu_buffer_base || !s->mctmp || !s->mcscratch)
327         return AVERROR(ENOMEM);
328
329     s->buffer_stride = stride;
330     return 0;
331 }
332
333 static void free_sequence_buffers(DiracContext *s)
334 {
335     int i, j, k;
336
337     for (i = 0; i < MAX_FRAMES; i++) {
338         if (s->all_frames[i].avframe->data[0]) {
339             av_frame_unref(s->all_frames[i].avframe);
340             memset(s->all_frames[i].interpolated, 0, sizeof(s->all_frames[i].interpolated));
341         }
342
343         for (j = 0; j < 3; j++)
344             for (k = 1; k < 4; k++)
345                 av_freep(&s->all_frames[i].hpel_base[j][k]);
346     }
347
348     memset(s->ref_frames, 0, sizeof(s->ref_frames));
349     memset(s->delay_frames, 0, sizeof(s->delay_frames));
350
351     for (i = 0; i < 3; i++) {
352         av_freep(&s->plane[i].idwt.buf_base);
353         av_freep(&s->plane[i].idwt.tmp);
354     }
355
356     s->buffer_stride = 0;
357     av_freep(&s->sbsplit);
358     av_freep(&s->blmotion);
359     av_freep(&s->edge_emu_buffer_base);
360
361     av_freep(&s->mctmp);
362     av_freep(&s->mcscratch);
363 }
364
365 static av_cold int dirac_decode_init(AVCodecContext *avctx)
366 {
367     DiracContext *s = avctx->priv_data;
368     int i;
369
370     s->avctx = avctx;
371     s->frame_number = -1;
372
373     ff_diracdsp_init(&s->diracdsp);
374     ff_mpegvideoencdsp_init(&s->mpvencdsp, avctx);
375     ff_videodsp_init(&s->vdsp, 8);
376
377     for (i = 0; i < MAX_FRAMES; i++) {
378         s->all_frames[i].avframe = av_frame_alloc();
379         if (!s->all_frames[i].avframe) {
380             while (i > 0)
381                 av_frame_free(&s->all_frames[--i].avframe);
382             return AVERROR(ENOMEM);
383         }
384     }
385
386     return 0;
387 }
388
389 static void dirac_decode_flush(AVCodecContext *avctx)
390 {
391     DiracContext *s = avctx->priv_data;
392     free_sequence_buffers(s);
393     s->seen_sequence_header = 0;
394     s->frame_number = -1;
395 }
396
397 static av_cold int dirac_decode_end(AVCodecContext *avctx)
398 {
399     DiracContext *s = avctx->priv_data;
400     int i;
401
402     dirac_decode_flush(avctx);
403     for (i = 0; i < MAX_FRAMES; i++)
404         av_frame_free(&s->all_frames[i].avframe);
405
406     return 0;
407 }
408
409 #define SIGN_CTX(x) (CTX_SIGN_ZERO + ((x) > 0) - ((x) < 0))
410
411 static inline int coeff_unpack_golomb(GetBitContext *gb, int qfactor, int qoffset)
412 {
413     int sign, coeff;
414     uint32_t buf;
415
416     OPEN_READER(re, gb);
417     UPDATE_CACHE(re, gb);
418     buf = GET_CACHE(re, gb);
419
420     if (buf & 0x80000000) {
421         LAST_SKIP_BITS(re,gb,1);
422         CLOSE_READER(re, gb);
423         return 0;
424     }
425
426     if (buf & 0xAA800000) {
427         buf >>= 32 - 8;
428         SKIP_BITS(re, gb, ff_interleaved_golomb_vlc_len[buf]);
429
430         coeff = ff_interleaved_ue_golomb_vlc_code[buf];
431     } else {
432         unsigned ret = 1;
433
434         do {
435             buf >>= 32 - 8;
436             SKIP_BITS(re, gb,
437                            FFMIN(ff_interleaved_golomb_vlc_len[buf], 8));
438
439             if (ff_interleaved_golomb_vlc_len[buf] != 9) {
440                 ret <<= (ff_interleaved_golomb_vlc_len[buf] - 1) >> 1;
441                 ret  |= ff_interleaved_dirac_golomb_vlc_code[buf];
442                 break;
443             }
444             ret = (ret << 4) | ff_interleaved_dirac_golomb_vlc_code[buf];
445             UPDATE_CACHE(re, gb);
446             buf = GET_CACHE(re, gb);
447         } while (ret<0x8000000U && BITS_AVAILABLE(re, gb));
448
449         coeff = ret - 1;
450     }
451
452     coeff = (coeff * qfactor + qoffset) >> 2;
453     sign  = SHOW_SBITS(re, gb, 1);
454     LAST_SKIP_BITS(re, gb, 1);
455     coeff = (coeff ^ sign) - sign;
456
457     CLOSE_READER(re, gb);
458     return coeff;
459 }
460
461 #define UNPACK_ARITH(n, type) \
462     static inline void coeff_unpack_arith_##n(DiracArith *c, int qfactor, int qoffset, \
463                                               SubBand *b, type *buf, int x, int y) \
464     { \
465         int coeff, sign, sign_pred = 0, pred_ctx = CTX_ZPZN_F1; \
466         const int mstride = -(b->stride >> (1+b->pshift)); \
467         if (b->parent) { \
468             const type *pbuf = (type *)b->parent->ibuf; \
469             const int stride = b->parent->stride >> (1+b->parent->pshift); \
470             pred_ctx += !!pbuf[stride * (y>>1) + (x>>1)] << 1; \
471         } \
472         if (b->orientation == subband_hl) \
473             sign_pred = buf[mstride]; \
474         if (x) { \
475             pred_ctx += !(buf[-1] | buf[mstride] | buf[-1 + mstride]); \
476             if (b->orientation == subband_lh) \
477                 sign_pred = buf[-1]; \
478         } else { \
479             pred_ctx += !buf[mstride]; \
480         } \
481         coeff = dirac_get_arith_uint(c, pred_ctx, CTX_COEFF_DATA); \
482         if (coeff) { \
483             coeff = (coeff * qfactor + qoffset) >> 2; \
484             sign  = dirac_get_arith_bit(c, SIGN_CTX(sign_pred)); \
485             coeff = (coeff ^ -sign) + sign; \
486         } \
487         *buf = coeff; \
488     } \
489
490 UNPACK_ARITH(8, int16_t)
491 UNPACK_ARITH(10, int32_t)
492
493 /**
494  * Decode the coeffs in the rectangle defined by left, right, top, bottom
495  * [DIRAC_STD] 13.4.3.2 Codeblock unpacking loop. codeblock()
496  */
497 static inline void codeblock(DiracContext *s, SubBand *b,
498                              GetBitContext *gb, DiracArith *c,
499                              int left, int right, int top, int bottom,
500                              int blockcnt_one, int is_arith)
501 {
502     int x, y, zero_block;
503     int qoffset, qfactor;
504     uint8_t *buf;
505
506     /* check for any coded coefficients in this codeblock */
507     if (!blockcnt_one) {
508         if (is_arith)
509             zero_block = dirac_get_arith_bit(c, CTX_ZERO_BLOCK);
510         else
511             zero_block = get_bits1(gb);
512
513         if (zero_block)
514             return;
515     }
516
517     if (s->codeblock_mode && !(s->old_delta_quant && blockcnt_one)) {
518         int quant = b->quant;
519         if (is_arith)
520             quant += dirac_get_arith_int(c, CTX_DELTA_Q_F, CTX_DELTA_Q_DATA);
521         else
522             quant += dirac_get_se_golomb(gb);
523         if (quant < 0) {
524             av_log(s->avctx, AV_LOG_ERROR, "Invalid quant\n");
525             return;
526         }
527         b->quant = quant;
528     }
529
530     if (b->quant > 115) {
531         av_log(s->avctx, AV_LOG_ERROR, "Unsupported quant %d\n", b->quant);
532         b->quant = 0;
533         return;
534     }
535
536     qfactor = ff_dirac_qscale_tab[b->quant];
537     /* TODO: context pointer? */
538     if (!s->num_refs)
539         qoffset = ff_dirac_qoffset_intra_tab[b->quant] + 2;
540     else
541         qoffset = ff_dirac_qoffset_inter_tab[b->quant] + 2;
542
543     buf = b->ibuf + top * b->stride;
544     if (is_arith) {
545         for (y = top; y < bottom; y++) {
546             for (x = left; x < right; x++) {
547                 if (b->pshift) {
548                     coeff_unpack_arith_10(c, qfactor, qoffset, b, (int32_t*)(buf)+x, x, y);
549                 } else {
550                     coeff_unpack_arith_8(c, qfactor, qoffset, b, (int16_t*)(buf)+x, x, y);
551                 }
552             }
553             buf += b->stride;
554         }
555     } else {
556         for (y = top; y < bottom; y++) {
557             for (x = left; x < right; x++) {
558                 int val = coeff_unpack_golomb(gb, qfactor, qoffset);
559                 if (b->pshift) {
560                     AV_WN32(&buf[4*x], val);
561                 } else {
562                     AV_WN16(&buf[2*x], val);
563                 }
564             }
565             buf += b->stride;
566          }
567      }
568 }
569
570 /**
571  * Dirac Specification ->
572  * 13.3 intra_dc_prediction(band)
573  */
574 #define INTRA_DC_PRED(n, type) \
575     static inline void intra_dc_prediction_##n(SubBand *b) \
576     { \
577         type *buf = (type*)b->ibuf; \
578         int x, y; \
579         \
580         for (x = 1; x < b->width; x++) \
581             buf[x] += buf[x-1]; \
582         buf += (b->stride >> (1+b->pshift)); \
583         \
584         for (y = 1; y < b->height; y++) { \
585             buf[0] += buf[-(b->stride >> (1+b->pshift))]; \
586             \
587             for (x = 1; x < b->width; x++) { \
588                 int pred = buf[x - 1] + buf[x - (b->stride >> (1+b->pshift))] + buf[x - (b->stride >> (1+b->pshift))-1]; \
589                 buf[x]  += divide3(pred); \
590             } \
591             buf += (b->stride >> (1+b->pshift)); \
592         } \
593     } \
594
595 INTRA_DC_PRED(8, int16_t)
596 INTRA_DC_PRED(10, int32_t)
597
598 /**
599  * Dirac Specification ->
600  * 13.4.2 Non-skipped subbands.  subband_coeffs()
601  */
602 static av_always_inline void decode_subband_internal(DiracContext *s, SubBand *b, int is_arith)
603 {
604     int cb_x, cb_y, left, right, top, bottom;
605     DiracArith c;
606     GetBitContext gb;
607     int cb_width  = s->codeblock[b->level + (b->orientation != subband_ll)].width;
608     int cb_height = s->codeblock[b->level + (b->orientation != subband_ll)].height;
609     int blockcnt_one = (cb_width + cb_height) == 2;
610
611     if (!b->length)
612         return;
613
614     init_get_bits8(&gb, b->coeff_data, b->length);
615
616     if (is_arith)
617         ff_dirac_init_arith_decoder(&c, &gb, b->length);
618
619     top = 0;
620     for (cb_y = 0; cb_y < cb_height; cb_y++) {
621         bottom = (b->height * (cb_y+1LL)) / cb_height;
622         left = 0;
623         for (cb_x = 0; cb_x < cb_width; cb_x++) {
624             right = (b->width * (cb_x+1LL)) / cb_width;
625             codeblock(s, b, &gb, &c, left, right, top, bottom, blockcnt_one, is_arith);
626             left = right;
627         }
628         top = bottom;
629     }
630
631     if (b->orientation == subband_ll && s->num_refs == 0) {
632         if (s->pshift) {
633             intra_dc_prediction_10(b);
634         } else {
635             intra_dc_prediction_8(b);
636         }
637     }
638 }
639
640 static int decode_subband_arith(AVCodecContext *avctx, void *b)
641 {
642     DiracContext *s = avctx->priv_data;
643     decode_subband_internal(s, b, 1);
644     return 0;
645 }
646
647 static int decode_subband_golomb(AVCodecContext *avctx, void *arg)
648 {
649     DiracContext *s = avctx->priv_data;
650     SubBand **b     = arg;
651     decode_subband_internal(s, *b, 0);
652     return 0;
653 }
654
655 /**
656  * Dirac Specification ->
657  * [DIRAC_STD] 13.4.1 core_transform_data()
658  */
659 static void decode_component(DiracContext *s, int comp)
660 {
661     AVCodecContext *avctx = s->avctx;
662     SubBand *bands[3*MAX_DWT_LEVELS+1];
663     enum dirac_subband orientation;
664     int level, num_bands = 0;
665
666     /* Unpack all subbands at all levels. */
667     for (level = 0; level < s->wavelet_depth; level++) {
668         for (orientation = !!level; orientation < 4; orientation++) {
669             SubBand *b = &s->plane[comp].band[level][orientation];
670             bands[num_bands++] = b;
671
672             align_get_bits(&s->gb);
673             /* [DIRAC_STD] 13.4.2 subband() */
674             b->length = svq3_get_ue_golomb(&s->gb);
675             if (b->length) {
676                 b->quant = svq3_get_ue_golomb(&s->gb);
677                 align_get_bits(&s->gb);
678                 b->coeff_data = s->gb.buffer + get_bits_count(&s->gb)/8;
679                 b->length = FFMIN(b->length, FFMAX(get_bits_left(&s->gb)/8, 0));
680                 skip_bits_long(&s->gb, b->length*8);
681             }
682         }
683         /* arithmetic coding has inter-level dependencies, so we can only execute one level at a time */
684         if (s->is_arith)
685             avctx->execute(avctx, decode_subband_arith, &s->plane[comp].band[level][!!level],
686                            NULL, 4-!!level, sizeof(SubBand));
687     }
688     /* golomb coding has no inter-level dependencies, so we can execute all subbands in parallel */
689     if (!s->is_arith)
690         avctx->execute(avctx, decode_subband_golomb, bands, NULL, num_bands, sizeof(SubBand*));
691 }
692
693 #define PARSE_VALUES(type, x, gb, ebits, buf1, buf2) \
694     type *buf = (type *)buf1; \
695     buf[x] = coeff_unpack_golomb(gb, qfactor, qoffset); \
696     if (get_bits_count(gb) >= ebits) \
697         return; \
698     if (buf2) { \
699         buf = (type *)buf2; \
700         buf[x] = coeff_unpack_golomb(gb, qfactor, qoffset); \
701         if (get_bits_count(gb) >= ebits) \
702             return; \
703     } \
704
705 static void decode_subband(DiracContext *s, GetBitContext *gb, int quant,
706                            int slice_x, int slice_y, int bits_end,
707                            SubBand *b1, SubBand *b2)
708 {
709     int left   = b1->width  * slice_x    / s->num_x;
710     int right  = b1->width  *(slice_x+1) / s->num_x;
711     int top    = b1->height * slice_y    / s->num_y;
712     int bottom = b1->height *(slice_y+1) / s->num_y;
713
714     int qfactor, qoffset;
715
716     uint8_t *buf1 =      b1->ibuf + top * b1->stride;
717     uint8_t *buf2 = b2 ? b2->ibuf + top * b2->stride: NULL;
718     int x, y;
719
720     if (quant > 115) {
721         av_log(s->avctx, AV_LOG_ERROR, "Unsupported quant %d\n", quant);
722         return;
723     }
724     qfactor = ff_dirac_qscale_tab[quant & 0x7f];
725     qoffset = ff_dirac_qoffset_intra_tab[quant & 0x7f] + 2;
726     /* we have to constantly check for overread since the spec explicitly
727        requires this, with the meaning that all remaining coeffs are set to 0 */
728     if (get_bits_count(gb) >= bits_end)
729         return;
730
731     if (s->pshift) {
732         for (y = top; y < bottom; y++) {
733             for (x = left; x < right; x++) {
734                 PARSE_VALUES(int32_t, x, gb, bits_end, buf1, buf2);
735             }
736             buf1 += b1->stride;
737             if (buf2)
738                 buf2 += b2->stride;
739         }
740     }
741     else {
742         for (y = top; y < bottom; y++) {
743             for (x = left; x < right; x++) {
744                 PARSE_VALUES(int16_t, x, gb, bits_end, buf1, buf2);
745             }
746             buf1 += b1->stride;
747             if (buf2)
748                 buf2 += b2->stride;
749         }
750     }
751 }
752
753 /* Used by Low Delay and High Quality profiles */
754 typedef struct DiracSlice {
755     GetBitContext gb;
756     int slice_x;
757     int slice_y;
758     int bytes;
759 } DiracSlice;
760
761
762 /**
763  * Dirac Specification ->
764  * 13.5.2 Slices. slice(sx,sy)
765  */
766 static int decode_lowdelay_slice(AVCodecContext *avctx, void *arg)
767 {
768     DiracContext *s = avctx->priv_data;
769     DiracSlice *slice = arg;
770     GetBitContext *gb = &slice->gb;
771     enum dirac_subband orientation;
772     int level, quant, chroma_bits, chroma_end;
773
774     int quant_base  = get_bits(gb, 7); /*[DIRAC_STD] qindex */
775     int length_bits = av_log2(8 * slice->bytes)+1;
776     int luma_bits   = get_bits_long(gb, length_bits);
777     int luma_end    = get_bits_count(gb) + FFMIN(luma_bits, get_bits_left(gb));
778
779     /* [DIRAC_STD] 13.5.5.2 luma_slice_band */
780     for (level = 0; level < s->wavelet_depth; level++)
781         for (orientation = !!level; orientation < 4; orientation++) {
782             quant = FFMAX(quant_base - s->lowdelay.quant[level][orientation], 0);
783             decode_subband(s, gb, quant, slice->slice_x, slice->slice_y, luma_end,
784                            &s->plane[0].band[level][orientation], NULL);
785         }
786
787     /* consume any unused bits from luma */
788     skip_bits_long(gb, get_bits_count(gb) - luma_end);
789
790     chroma_bits = 8*slice->bytes - 7 - length_bits - luma_bits;
791     chroma_end  = get_bits_count(gb) + FFMIN(chroma_bits, get_bits_left(gb));
792     /* [DIRAC_STD] 13.5.5.3 chroma_slice_band */
793     for (level = 0; level < s->wavelet_depth; level++)
794         for (orientation = !!level; orientation < 4; orientation++) {
795             quant = FFMAX(quant_base - s->lowdelay.quant[level][orientation], 0);
796             decode_subband(s, gb, quant, slice->slice_x, slice->slice_y, chroma_end,
797                            &s->plane[1].band[level][orientation],
798                            &s->plane[2].band[level][orientation]);
799         }
800
801     return 0;
802 }
803
804 /**
805  * VC-2 Specification ->
806  * 13.5.3 hq_slice(sx,sy)
807  */
808 static int decode_hq_slice(AVCodecContext *avctx, void *arg)
809 {
810     int i, quant, level, orientation, quant_idx;
811     uint8_t quants[MAX_DWT_LEVELS][4];
812     DiracContext *s = avctx->priv_data;
813     DiracSlice *slice = arg;
814     GetBitContext *gb = &slice->gb;
815
816     skip_bits_long(gb, 8*s->highquality.prefix_bytes);
817     quant_idx = get_bits(gb, 8);
818
819     /* Slice quantization (slice_quantizers() in the specs) */
820     for (level = 0; level < s->wavelet_depth; level++) {
821         for (orientation = !!level; orientation < 4; orientation++) {
822             quant = FFMAX(quant_idx - s->lowdelay.quant[level][orientation], 0);
823             quants[level][orientation] = quant;
824         }
825     }
826
827     /* Luma + 2 Chroma planes */
828     for (i = 0; i < 3; i++) {
829         int64_t length = s->highquality.size_scaler * get_bits(gb, 8);
830         int64_t bits_left = 8 * length;
831         int64_t bits_end = get_bits_count(gb) + bits_left;
832
833         if (bits_end >= INT_MAX) {
834             av_log(s->avctx, AV_LOG_ERROR, "end too far away\n");
835             return AVERROR_INVALIDDATA;
836         }
837
838         for (level = 0; level < s->wavelet_depth; level++) {
839             for (orientation = !!level; orientation < 4; orientation++) {
840                 decode_subband(s, gb, quants[level][orientation], slice->slice_x, slice->slice_y, bits_end,
841                                &s->plane[i].band[level][orientation], NULL);
842             }
843         }
844         skip_bits_long(gb, bits_end - get_bits_count(gb));
845     }
846
847     return 0;
848 }
849
850 /**
851  * Dirac Specification ->
852  * 13.5.1 low_delay_transform_data()
853  */
854 static int decode_lowdelay(DiracContext *s)
855 {
856     AVCodecContext *avctx = s->avctx;
857     int slice_x, slice_y, bufsize;
858     int64_t bytes = 0;
859     const uint8_t *buf;
860     DiracSlice *slices;
861     int slice_num = 0;
862
863     slices = av_mallocz_array(s->num_x, s->num_y * sizeof(DiracSlice));
864     if (!slices)
865         return AVERROR(ENOMEM);
866
867     align_get_bits(&s->gb);
868     /*[DIRAC_STD] 13.5.2 Slices. slice(sx,sy) */
869     buf = s->gb.buffer + get_bits_count(&s->gb)/8;
870     bufsize = get_bits_left(&s->gb);
871
872     if (s->hq_picture) {
873         int i;
874
875         for (slice_y = 0; bufsize > 0 && slice_y < s->num_y; slice_y++) {
876             for (slice_x = 0; bufsize > 0 && slice_x < s->num_x; slice_x++) {
877                 bytes = s->highquality.prefix_bytes + 1;
878                 for (i = 0; i < 3; i++) {
879                     if (bytes <= bufsize/8)
880                         bytes += buf[bytes] * s->highquality.size_scaler + 1;
881                 }
882                 if (bytes >= INT_MAX) {
883                     av_log(s->avctx, AV_LOG_ERROR, "too many bytes\n");
884                     av_free(slices);
885                     return AVERROR_INVALIDDATA;
886                 }
887
888                 slices[slice_num].bytes   = bytes;
889                 slices[slice_num].slice_x = slice_x;
890                 slices[slice_num].slice_y = slice_y;
891                 init_get_bits(&slices[slice_num].gb, buf, bufsize);
892                 slice_num++;
893
894                 buf     += bytes;
895                 if (bufsize/8 >= bytes)
896                     bufsize -= bytes*8;
897                 else
898                     bufsize = 0;
899             }
900         }
901         avctx->execute(avctx, decode_hq_slice, slices, NULL, slice_num,
902                        sizeof(DiracSlice));
903     } else {
904         for (slice_y = 0; bufsize > 0 && slice_y < s->num_y; slice_y++) {
905             for (slice_x = 0; bufsize > 0 && slice_x < s->num_x; slice_x++) {
906                 bytes = (slice_num+1) * (int64_t)s->lowdelay.bytes.num / s->lowdelay.bytes.den
907                        - slice_num    * (int64_t)s->lowdelay.bytes.num / s->lowdelay.bytes.den;
908                 slices[slice_num].bytes   = bytes;
909                 slices[slice_num].slice_x = slice_x;
910                 slices[slice_num].slice_y = slice_y;
911                 init_get_bits(&slices[slice_num].gb, buf, bufsize);
912                 slice_num++;
913
914                 buf     += bytes;
915                 if (bufsize/8 >= bytes)
916                     bufsize -= bytes*8;
917                 else
918                     bufsize = 0;
919             }
920         }
921         avctx->execute(avctx, decode_lowdelay_slice, slices, NULL, slice_num,
922                        sizeof(DiracSlice)); /* [DIRAC_STD] 13.5.2 Slices */
923     }
924
925     if (s->dc_prediction) {
926         if (s->pshift) {
927             intra_dc_prediction_10(&s->plane[0].band[0][0]); /* [DIRAC_STD] 13.3 intra_dc_prediction() */
928             intra_dc_prediction_10(&s->plane[1].band[0][0]); /* [DIRAC_STD] 13.3 intra_dc_prediction() */
929             intra_dc_prediction_10(&s->plane[2].band[0][0]); /* [DIRAC_STD] 13.3 intra_dc_prediction() */
930         } else {
931             intra_dc_prediction_8(&s->plane[0].band[0][0]);
932             intra_dc_prediction_8(&s->plane[1].band[0][0]);
933             intra_dc_prediction_8(&s->plane[2].band[0][0]);
934         }
935     }
936     av_free(slices);
937     return 0;
938 }
939
940 static void init_planes(DiracContext *s)
941 {
942     int i, w, h, level, orientation;
943
944     for (i = 0; i < 3; i++) {
945         Plane *p = &s->plane[i];
946
947         p->width       = s->seq.width  >> (i ? s->chroma_x_shift : 0);
948         p->height      = s->seq.height >> (i ? s->chroma_y_shift : 0);
949         p->idwt.width  = w = CALC_PADDING(p->width , s->wavelet_depth);
950         p->idwt.height = h = CALC_PADDING(p->height, s->wavelet_depth);
951         p->idwt.stride = FFALIGN(p->idwt.width, 8) << (1 + s->pshift);
952
953         for (level = s->wavelet_depth-1; level >= 0; level--) {
954             w = w>>1;
955             h = h>>1;
956             for (orientation = !!level; orientation < 4; orientation++) {
957                 SubBand *b = &p->band[level][orientation];
958
959                 b->pshift = s->pshift;
960                 b->ibuf   = p->idwt.buf;
961                 b->level  = level;
962                 b->stride = p->idwt.stride << (s->wavelet_depth - level);
963                 b->width  = w;
964                 b->height = h;
965                 b->orientation = orientation;
966
967                 if (orientation & 1)
968                     b->ibuf += w << (1+b->pshift);
969                 if (orientation > 1)
970                     b->ibuf += (b->stride>>1);
971
972                 if (level)
973                     b->parent = &p->band[level-1][orientation];
974             }
975         }
976
977         if (i > 0) {
978             p->xblen = s->plane[0].xblen >> s->chroma_x_shift;
979             p->yblen = s->plane[0].yblen >> s->chroma_y_shift;
980             p->xbsep = s->plane[0].xbsep >> s->chroma_x_shift;
981             p->ybsep = s->plane[0].ybsep >> s->chroma_y_shift;
982         }
983
984         p->xoffset = (p->xblen - p->xbsep)/2;
985         p->yoffset = (p->yblen - p->ybsep)/2;
986     }
987 }
988
989 /**
990  * Unpack the motion compensation parameters
991  * Dirac Specification ->
992  * 11.2 Picture prediction data. picture_prediction()
993  */
994 static int dirac_unpack_prediction_parameters(DiracContext *s)
995 {
996     static const uint8_t default_blen[] = { 4, 12, 16, 24 };
997
998     GetBitContext *gb = &s->gb;
999     unsigned idx, ref;
1000
1001     align_get_bits(gb);
1002     /* [DIRAC_STD] 11.2.2 Block parameters. block_parameters() */
1003     /* Luma and Chroma are equal. 11.2.3 */
1004     idx = svq3_get_ue_golomb(gb); /* [DIRAC_STD] index */
1005
1006     if (idx > 4) {
1007         av_log(s->avctx, AV_LOG_ERROR, "Block prediction index too high\n");
1008         return AVERROR_INVALIDDATA;
1009     }
1010
1011     if (idx == 0) {
1012         s->plane[0].xblen = svq3_get_ue_golomb(gb);
1013         s->plane[0].yblen = svq3_get_ue_golomb(gb);
1014         s->plane[0].xbsep = svq3_get_ue_golomb(gb);
1015         s->plane[0].ybsep = svq3_get_ue_golomb(gb);
1016     } else {
1017         /*[DIRAC_STD] preset_block_params(index). Table 11.1 */
1018         s->plane[0].xblen = default_blen[idx-1];
1019         s->plane[0].yblen = default_blen[idx-1];
1020         s->plane[0].xbsep = 4 * idx;
1021         s->plane[0].ybsep = 4 * idx;
1022     }
1023     /*[DIRAC_STD] 11.2.4 motion_data_dimensions()
1024       Calculated in function dirac_unpack_block_motion_data */
1025
1026     if (s->plane[0].xblen % (1 << s->chroma_x_shift) != 0 ||
1027         s->plane[0].yblen % (1 << s->chroma_y_shift) != 0 ||
1028         !s->plane[0].xblen || !s->plane[0].yblen) {
1029         av_log(s->avctx, AV_LOG_ERROR,
1030                "invalid x/y block length (%d/%d) for x/y chroma shift (%d/%d)\n",
1031                s->plane[0].xblen, s->plane[0].yblen, s->chroma_x_shift, s->chroma_y_shift);
1032         return AVERROR_INVALIDDATA;
1033     }
1034     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) {
1035         av_log(s->avctx, AV_LOG_ERROR, "Block separation too small\n");
1036         return AVERROR_INVALIDDATA;
1037     }
1038     if (s->plane[0].xbsep > s->plane[0].xblen || s->plane[0].ybsep > s->plane[0].yblen) {
1039         av_log(s->avctx, AV_LOG_ERROR, "Block separation greater than size\n");
1040         return AVERROR_INVALIDDATA;
1041     }
1042     if (FFMAX(s->plane[0].xblen, s->plane[0].yblen) > MAX_BLOCKSIZE) {
1043         av_log(s->avctx, AV_LOG_ERROR, "Unsupported large block size\n");
1044         return AVERROR_PATCHWELCOME;
1045     }
1046
1047     /*[DIRAC_STD] 11.2.5 Motion vector precision. motion_vector_precision()
1048       Read motion vector precision */
1049     s->mv_precision = svq3_get_ue_golomb(gb);
1050     if (s->mv_precision > 3) {
1051         av_log(s->avctx, AV_LOG_ERROR, "MV precision finer than eighth-pel\n");
1052         return AVERROR_INVALIDDATA;
1053     }
1054
1055     /*[DIRAC_STD] 11.2.6 Global motion. global_motion()
1056       Read the global motion compensation parameters */
1057     s->globalmc_flag = get_bits1(gb);
1058     if (s->globalmc_flag) {
1059         memset(s->globalmc, 0, sizeof(s->globalmc));
1060         /* [DIRAC_STD] pan_tilt(gparams) */
1061         for (ref = 0; ref < s->num_refs; ref++) {
1062             if (get_bits1(gb)) {
1063                 s->globalmc[ref].pan_tilt[0] = dirac_get_se_golomb(gb);
1064                 s->globalmc[ref].pan_tilt[1] = dirac_get_se_golomb(gb);
1065             }
1066             /* [DIRAC_STD] zoom_rotate_shear(gparams)
1067                zoom/rotation/shear parameters */
1068             if (get_bits1(gb)) {
1069                 s->globalmc[ref].zrs_exp   = svq3_get_ue_golomb(gb);
1070                 s->globalmc[ref].zrs[0][0] = dirac_get_se_golomb(gb);
1071                 s->globalmc[ref].zrs[0][1] = dirac_get_se_golomb(gb);
1072                 s->globalmc[ref].zrs[1][0] = dirac_get_se_golomb(gb);
1073                 s->globalmc[ref].zrs[1][1] = dirac_get_se_golomb(gb);
1074             } else {
1075                 s->globalmc[ref].zrs[0][0] = 1;
1076                 s->globalmc[ref].zrs[1][1] = 1;
1077             }
1078             /* [DIRAC_STD] perspective(gparams) */
1079             if (get_bits1(gb)) {
1080                 s->globalmc[ref].perspective_exp = svq3_get_ue_golomb(gb);
1081                 s->globalmc[ref].perspective[0]  = dirac_get_se_golomb(gb);
1082                 s->globalmc[ref].perspective[1]  = dirac_get_se_golomb(gb);
1083             }
1084         }
1085     }
1086
1087     /*[DIRAC_STD] 11.2.7 Picture prediction mode. prediction_mode()
1088       Picture prediction mode, not currently used. */
1089     if (svq3_get_ue_golomb(gb)) {
1090         av_log(s->avctx, AV_LOG_ERROR, "Unknown picture prediction mode\n");
1091         return AVERROR_INVALIDDATA;
1092     }
1093
1094     /* [DIRAC_STD] 11.2.8 Reference picture weight. reference_picture_weights()
1095        just data read, weight calculation will be done later on. */
1096     s->weight_log2denom = 1;
1097     s->weight[0]        = 1;
1098     s->weight[1]        = 1;
1099
1100     if (get_bits1(gb)) {
1101         s->weight_log2denom = svq3_get_ue_golomb(gb);
1102         s->weight[0] = dirac_get_se_golomb(gb);
1103         if (s->num_refs == 2)
1104             s->weight[1] = dirac_get_se_golomb(gb);
1105     }
1106     return 0;
1107 }
1108
1109 /**
1110  * Dirac Specification ->
1111  * 11.3 Wavelet transform data. wavelet_transform()
1112  */
1113 static int dirac_unpack_idwt_params(DiracContext *s)
1114 {
1115     GetBitContext *gb = &s->gb;
1116     int i, level;
1117     unsigned tmp;
1118
1119 #define CHECKEDREAD(dst, cond, errmsg) \
1120     tmp = svq3_get_ue_golomb(gb); \
1121     if (cond) { \
1122         av_log(s->avctx, AV_LOG_ERROR, errmsg); \
1123         return AVERROR_INVALIDDATA; \
1124     }\
1125     dst = tmp;
1126
1127     align_get_bits(gb);
1128
1129     s->zero_res = s->num_refs ? get_bits1(gb) : 0;
1130     if (s->zero_res)
1131         return 0;
1132
1133     /*[DIRAC_STD] 11.3.1 Transform parameters. transform_parameters() */
1134     CHECKEDREAD(s->wavelet_idx, tmp > 6, "wavelet_idx is too big\n")
1135
1136     CHECKEDREAD(s->wavelet_depth, tmp > MAX_DWT_LEVELS || tmp < 1, "invalid number of DWT decompositions\n")
1137
1138     if (!s->low_delay) {
1139         /* Codeblock parameters (core syntax only) */
1140         if (get_bits1(gb)) {
1141             for (i = 0; i <= s->wavelet_depth; i++) {
1142                 CHECKEDREAD(s->codeblock[i].width , tmp < 1 || tmp > (s->avctx->width >>s->wavelet_depth-i), "codeblock width invalid\n")
1143                 CHECKEDREAD(s->codeblock[i].height, tmp < 1 || tmp > (s->avctx->height>>s->wavelet_depth-i), "codeblock height invalid\n")
1144             }
1145
1146             CHECKEDREAD(s->codeblock_mode, tmp > 1, "unknown codeblock mode\n")
1147         }
1148         else {
1149             for (i = 0; i <= s->wavelet_depth; i++)
1150                 s->codeblock[i].width = s->codeblock[i].height = 1;
1151         }
1152     }
1153     else {
1154         s->num_x        = svq3_get_ue_golomb(gb);
1155         s->num_y        = svq3_get_ue_golomb(gb);
1156         if (s->ld_picture) {
1157             s->lowdelay.bytes.num = svq3_get_ue_golomb(gb);
1158             s->lowdelay.bytes.den = svq3_get_ue_golomb(gb);
1159             if (s->lowdelay.bytes.den <= 0) {
1160                 av_log(s->avctx,AV_LOG_ERROR,"Invalid lowdelay.bytes.den\n");
1161                 return AVERROR_INVALIDDATA;
1162             }
1163         } else if (s->hq_picture) {
1164             s->highquality.prefix_bytes = svq3_get_ue_golomb(gb);
1165             s->highquality.size_scaler  = svq3_get_ue_golomb(gb);
1166             if (s->highquality.prefix_bytes >= INT_MAX / 8) {
1167                 av_log(s->avctx,AV_LOG_ERROR,"too many prefix bytes\n");
1168                 return AVERROR_INVALIDDATA;
1169             }
1170         }
1171
1172         /* [DIRAC_STD] 11.3.5 Quantisation matrices (low-delay syntax). quant_matrix() */
1173         if (get_bits1(gb)) {
1174             av_log(s->avctx,AV_LOG_DEBUG,"Low Delay: Has Custom Quantization Matrix!\n");
1175             /* custom quantization matrix */
1176             s->lowdelay.quant[0][0] = svq3_get_ue_golomb(gb);
1177             for (level = 0; level < s->wavelet_depth; level++) {
1178                 s->lowdelay.quant[level][1] = svq3_get_ue_golomb(gb);
1179                 s->lowdelay.quant[level][2] = svq3_get_ue_golomb(gb);
1180                 s->lowdelay.quant[level][3] = svq3_get_ue_golomb(gb);
1181             }
1182         } else {
1183             if (s->wavelet_depth > 4) {
1184                 av_log(s->avctx,AV_LOG_ERROR,"Mandatory custom low delay matrix missing for depth %d\n", s->wavelet_depth);
1185                 return AVERROR_INVALIDDATA;
1186             }
1187             /* default quantization matrix */
1188             for (level = 0; level < s->wavelet_depth; level++)
1189                 for (i = 0; i < 4; i++) {
1190                     s->lowdelay.quant[level][i] = ff_dirac_default_qmat[s->wavelet_idx][level][i];
1191                     /* haar with no shift differs for different depths */
1192                     if (s->wavelet_idx == 3)
1193                         s->lowdelay.quant[level][i] += 4*(s->wavelet_depth-1 - level);
1194                 }
1195         }
1196     }
1197     return 0;
1198 }
1199
1200 static inline int pred_sbsplit(uint8_t *sbsplit, int stride, int x, int y)
1201 {
1202     static const uint8_t avgsplit[7] = { 0, 0, 1, 1, 1, 2, 2 };
1203
1204     if (!(x|y))
1205         return 0;
1206     else if (!y)
1207         return sbsplit[-1];
1208     else if (!x)
1209         return sbsplit[-stride];
1210
1211     return avgsplit[sbsplit[-1] + sbsplit[-stride] + sbsplit[-stride-1]];
1212 }
1213
1214 static inline int pred_block_mode(DiracBlock *block, int stride, int x, int y, int refmask)
1215 {
1216     int pred;
1217
1218     if (!(x|y))
1219         return 0;
1220     else if (!y)
1221         return block[-1].ref & refmask;
1222     else if (!x)
1223         return block[-stride].ref & refmask;
1224
1225     /* return the majority */
1226     pred = (block[-1].ref & refmask) + (block[-stride].ref & refmask) + (block[-stride-1].ref & refmask);
1227     return (pred >> 1) & refmask;
1228 }
1229
1230 static inline void pred_block_dc(DiracBlock *block, int stride, int x, int y)
1231 {
1232     int i, n = 0;
1233
1234     memset(block->u.dc, 0, sizeof(block->u.dc));
1235
1236     if (x && !(block[-1].ref & 3)) {
1237         for (i = 0; i < 3; i++)
1238             block->u.dc[i] += block[-1].u.dc[i];
1239         n++;
1240     }
1241
1242     if (y && !(block[-stride].ref & 3)) {
1243         for (i = 0; i < 3; i++)
1244             block->u.dc[i] += block[-stride].u.dc[i];
1245         n++;
1246     }
1247
1248     if (x && y && !(block[-1-stride].ref & 3)) {
1249         for (i = 0; i < 3; i++)
1250             block->u.dc[i] += block[-1-stride].u.dc[i];
1251         n++;
1252     }
1253
1254     if (n == 2) {
1255         for (i = 0; i < 3; i++)
1256             block->u.dc[i] = (block->u.dc[i]+1)>>1;
1257     } else if (n == 3) {
1258         for (i = 0; i < 3; i++)
1259             block->u.dc[i] = divide3(block->u.dc[i]);
1260     }
1261 }
1262
1263 static inline void pred_mv(DiracBlock *block, int stride, int x, int y, int ref)
1264 {
1265     int16_t *pred[3];
1266     int refmask = ref+1;
1267     int mask = refmask | DIRAC_REF_MASK_GLOBAL; /*  exclude gmc blocks */
1268     int n = 0;
1269
1270     if (x && (block[-1].ref & mask) == refmask)
1271         pred[n++] = block[-1].u.mv[ref];
1272
1273     if (y && (block[-stride].ref & mask) == refmask)
1274         pred[n++] = block[-stride].u.mv[ref];
1275
1276     if (x && y && (block[-stride-1].ref & mask) == refmask)
1277         pred[n++] = block[-stride-1].u.mv[ref];
1278
1279     switch (n) {
1280     case 0:
1281         block->u.mv[ref][0] = 0;
1282         block->u.mv[ref][1] = 0;
1283         break;
1284     case 1:
1285         block->u.mv[ref][0] = pred[0][0];
1286         block->u.mv[ref][1] = pred[0][1];
1287         break;
1288     case 2:
1289         block->u.mv[ref][0] = (pred[0][0] + pred[1][0] + 1) >> 1;
1290         block->u.mv[ref][1] = (pred[0][1] + pred[1][1] + 1) >> 1;
1291         break;
1292     case 3:
1293         block->u.mv[ref][0] = mid_pred(pred[0][0], pred[1][0], pred[2][0]);
1294         block->u.mv[ref][1] = mid_pred(pred[0][1], pred[1][1], pred[2][1]);
1295         break;
1296     }
1297 }
1298
1299 static void global_mv(DiracContext *s, DiracBlock *block, int x, int y, int ref)
1300 {
1301     int ez      = s->globalmc[ref].zrs_exp;
1302     int ep      = s->globalmc[ref].perspective_exp;
1303     int (*A)[2] = s->globalmc[ref].zrs;
1304     int *b      = s->globalmc[ref].pan_tilt;
1305     int *c      = s->globalmc[ref].perspective;
1306
1307     int m       = (1<<ep) - (c[0]*x + c[1]*y);
1308     int mx      = m * ((A[0][0] * x + A[0][1]*y) + (1<<ez) * b[0]);
1309     int my      = m * ((A[1][0] * x + A[1][1]*y) + (1<<ez) * b[1]);
1310
1311     block->u.mv[ref][0] = (mx + (1<<(ez+ep))) >> (ez+ep);
1312     block->u.mv[ref][1] = (my + (1<<(ez+ep))) >> (ez+ep);
1313 }
1314
1315 static void decode_block_params(DiracContext *s, DiracArith arith[8], DiracBlock *block,
1316                                 int stride, int x, int y)
1317 {
1318     int i;
1319
1320     block->ref  = pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_REF1);
1321     block->ref ^= dirac_get_arith_bit(arith, CTX_PMODE_REF1);
1322
1323     if (s->num_refs == 2) {
1324         block->ref |= pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_REF2);
1325         block->ref ^= dirac_get_arith_bit(arith, CTX_PMODE_REF2) << 1;
1326     }
1327
1328     if (!block->ref) {
1329         pred_block_dc(block, stride, x, y);
1330         for (i = 0; i < 3; i++)
1331             block->u.dc[i] += dirac_get_arith_int(arith+1+i, CTX_DC_F1, CTX_DC_DATA);
1332         return;
1333     }
1334
1335     if (s->globalmc_flag) {
1336         block->ref |= pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_GLOBAL);
1337         block->ref ^= dirac_get_arith_bit(arith, CTX_GLOBAL_BLOCK) << 2;
1338     }
1339
1340     for (i = 0; i < s->num_refs; i++)
1341         if (block->ref & (i+1)) {
1342             if (block->ref & DIRAC_REF_MASK_GLOBAL) {
1343                 global_mv(s, block, x, y, i);
1344             } else {
1345                 pred_mv(block, stride, x, y, i);
1346                 block->u.mv[i][0] += dirac_get_arith_int(arith + 4 + 2 * i, CTX_MV_F1, CTX_MV_DATA);
1347                 block->u.mv[i][1] += dirac_get_arith_int(arith + 5 + 2 * i, CTX_MV_F1, CTX_MV_DATA);
1348             }
1349         }
1350 }
1351
1352 /**
1353  * Copies the current block to the other blocks covered by the current superblock split mode
1354  */
1355 static void propagate_block_data(DiracBlock *block, int stride, int size)
1356 {
1357     int x, y;
1358     DiracBlock *dst = block;
1359
1360     for (x = 1; x < size; x++)
1361         dst[x] = *block;
1362
1363     for (y = 1; y < size; y++) {
1364         dst += stride;
1365         for (x = 0; x < size; x++)
1366             dst[x] = *block;
1367     }
1368 }
1369
1370 /**
1371  * Dirac Specification ->
1372  * 12. Block motion data syntax
1373  */
1374 static int dirac_unpack_block_motion_data(DiracContext *s)
1375 {
1376     GetBitContext *gb = &s->gb;
1377     uint8_t *sbsplit = s->sbsplit;
1378     int i, x, y, q, p;
1379     DiracArith arith[8];
1380
1381     align_get_bits(gb);
1382
1383     /* [DIRAC_STD] 11.2.4 and 12.2.1 Number of blocks and superblocks */
1384     s->sbwidth  = DIVRNDUP(s->seq.width,  4*s->plane[0].xbsep);
1385     s->sbheight = DIVRNDUP(s->seq.height, 4*s->plane[0].ybsep);
1386     s->blwidth  = 4 * s->sbwidth;
1387     s->blheight = 4 * s->sbheight;
1388
1389     /* [DIRAC_STD] 12.3.1 Superblock splitting modes. superblock_split_modes()
1390        decode superblock split modes */
1391     ff_dirac_init_arith_decoder(arith, gb, svq3_get_ue_golomb(gb));     /* svq3_get_ue_golomb(gb) is the length */
1392     for (y = 0; y < s->sbheight; y++) {
1393         for (x = 0; x < s->sbwidth; x++) {
1394             unsigned int split  = dirac_get_arith_uint(arith, CTX_SB_F1, CTX_SB_DATA);
1395             if (split > 2)
1396                 return AVERROR_INVALIDDATA;
1397             sbsplit[x] = (split + pred_sbsplit(sbsplit+x, s->sbwidth, x, y)) % 3;
1398         }
1399         sbsplit += s->sbwidth;
1400     }
1401
1402     /* setup arith decoding */
1403     ff_dirac_init_arith_decoder(arith, gb, svq3_get_ue_golomb(gb));
1404     for (i = 0; i < s->num_refs; i++) {
1405         ff_dirac_init_arith_decoder(arith + 4 + 2 * i, gb, svq3_get_ue_golomb(gb));
1406         ff_dirac_init_arith_decoder(arith + 5 + 2 * i, gb, svq3_get_ue_golomb(gb));
1407     }
1408     for (i = 0; i < 3; i++)
1409         ff_dirac_init_arith_decoder(arith+1+i, gb, svq3_get_ue_golomb(gb));
1410
1411     for (y = 0; y < s->sbheight; y++)
1412         for (x = 0; x < s->sbwidth; x++) {
1413             int blkcnt = 1 << s->sbsplit[y * s->sbwidth + x];
1414             int step   = 4 >> s->sbsplit[y * s->sbwidth + x];
1415
1416             for (q = 0; q < blkcnt; q++)
1417                 for (p = 0; p < blkcnt; p++) {
1418                     int bx = 4 * x + p*step;
1419                     int by = 4 * y + q*step;
1420                     DiracBlock *block = &s->blmotion[by*s->blwidth + bx];
1421                     decode_block_params(s, arith, block, s->blwidth, bx, by);
1422                     propagate_block_data(block, s->blwidth, step);
1423                 }
1424         }
1425
1426     return 0;
1427 }
1428
1429 static int weight(int i, int blen, int offset)
1430 {
1431 #define ROLLOFF(i) offset == 1 ? ((i) ? 5 : 3) :        \
1432     (1 + (6*(i) + offset - 1) / (2*offset - 1))
1433
1434     if (i < 2*offset)
1435         return ROLLOFF(i);
1436     else if (i > blen-1 - 2*offset)
1437         return ROLLOFF(blen-1 - i);
1438     return 8;
1439 }
1440
1441 static void init_obmc_weight_row(Plane *p, uint8_t *obmc_weight, int stride,
1442                                  int left, int right, int wy)
1443 {
1444     int x;
1445     for (x = 0; left && x < p->xblen >> 1; x++)
1446         obmc_weight[x] = wy*8;
1447     for (; x < p->xblen >> right; x++)
1448         obmc_weight[x] = wy*weight(x, p->xblen, p->xoffset);
1449     for (; x < p->xblen; x++)
1450         obmc_weight[x] = wy*8;
1451     for (; x < stride; x++)
1452         obmc_weight[x] = 0;
1453 }
1454
1455 static void init_obmc_weight(Plane *p, uint8_t *obmc_weight, int stride,
1456                              int left, int right, int top, int bottom)
1457 {
1458     int y;
1459     for (y = 0; top && y < p->yblen >> 1; y++) {
1460         init_obmc_weight_row(p, obmc_weight, stride, left, right, 8);
1461         obmc_weight += stride;
1462     }
1463     for (; y < p->yblen >> bottom; y++) {
1464         int wy = weight(y, p->yblen, p->yoffset);
1465         init_obmc_weight_row(p, obmc_weight, stride, left, right, wy);
1466         obmc_weight += stride;
1467     }
1468     for (; y < p->yblen; y++) {
1469         init_obmc_weight_row(p, obmc_weight, stride, left, right, 8);
1470         obmc_weight += stride;
1471     }
1472 }
1473
1474 static void init_obmc_weights(DiracContext *s, Plane *p, int by)
1475 {
1476     int top = !by;
1477     int bottom = by == s->blheight-1;
1478
1479     /* don't bother re-initing for rows 2 to blheight-2, the weights don't change */
1480     if (top || bottom || by == 1) {
1481         init_obmc_weight(p, s->obmc_weight[0], MAX_BLOCKSIZE, 1, 0, top, bottom);
1482         init_obmc_weight(p, s->obmc_weight[1], MAX_BLOCKSIZE, 0, 0, top, bottom);
1483         init_obmc_weight(p, s->obmc_weight[2], MAX_BLOCKSIZE, 0, 1, top, bottom);
1484     }
1485 }
1486
1487 static const uint8_t epel_weights[4][4][4] = {
1488     {{ 16,  0,  0,  0 },
1489      { 12,  4,  0,  0 },
1490      {  8,  8,  0,  0 },
1491      {  4, 12,  0,  0 }},
1492     {{ 12,  0,  4,  0 },
1493      {  9,  3,  3,  1 },
1494      {  6,  6,  2,  2 },
1495      {  3,  9,  1,  3 }},
1496     {{  8,  0,  8,  0 },
1497      {  6,  2,  6,  2 },
1498      {  4,  4,  4,  4 },
1499      {  2,  6,  2,  6 }},
1500     {{  4,  0, 12,  0 },
1501      {  3,  1,  9,  3 },
1502      {  2,  2,  6,  6 },
1503      {  1,  3,  3,  9 }}
1504 };
1505
1506 /**
1507  * For block x,y, determine which of the hpel planes to do bilinear
1508  * interpolation from and set src[] to the location in each hpel plane
1509  * to MC from.
1510  *
1511  * @return the index of the put_dirac_pixels_tab function to use
1512  *  0 for 1 plane (fpel,hpel), 1 for 2 planes (qpel), 2 for 4 planes (qpel), and 3 for epel
1513  */
1514 static int mc_subpel(DiracContext *s, DiracBlock *block, const uint8_t *src[5],
1515                      int x, int y, int ref, int plane)
1516 {
1517     Plane *p = &s->plane[plane];
1518     uint8_t **ref_hpel = s->ref_pics[ref]->hpel[plane];
1519     int motion_x = block->u.mv[ref][0];
1520     int motion_y = block->u.mv[ref][1];
1521     int mx, my, i, epel, nplanes = 0;
1522
1523     if (plane) {
1524         motion_x >>= s->chroma_x_shift;
1525         motion_y >>= s->chroma_y_shift;
1526     }
1527
1528     mx         = motion_x & ~(-1U << s->mv_precision);
1529     my         = motion_y & ~(-1U << s->mv_precision);
1530     motion_x >>= s->mv_precision;
1531     motion_y >>= s->mv_precision;
1532     /* normalize subpel coordinates to epel */
1533     /* TODO: template this function? */
1534     mx      <<= 3 - s->mv_precision;
1535     my      <<= 3 - s->mv_precision;
1536
1537     x += motion_x;
1538     y += motion_y;
1539     epel = (mx|my)&1;
1540
1541     /* hpel position */
1542     if (!((mx|my)&3)) {
1543         nplanes = 1;
1544         src[0] = ref_hpel[(my>>1)+(mx>>2)] + y*p->stride + x;
1545     } else {
1546         /* qpel or epel */
1547         nplanes = 4;
1548         for (i = 0; i < 4; i++)
1549             src[i] = ref_hpel[i] + y*p->stride + x;
1550
1551         /* if we're interpolating in the right/bottom halves, adjust the planes as needed
1552            we increment x/y because the edge changes for half of the pixels */
1553         if (mx > 4) {
1554             src[0] += 1;
1555             src[2] += 1;
1556             x++;
1557         }
1558         if (my > 4) {
1559             src[0] += p->stride;
1560             src[1] += p->stride;
1561             y++;
1562         }
1563
1564         /* hpel planes are:
1565            [0]: F  [1]: H
1566            [2]: V  [3]: C */
1567         if (!epel) {
1568             /* check if we really only need 2 planes since either mx or my is
1569                a hpel position. (epel weights of 0 handle this there) */
1570             if (!(mx&3)) {
1571                 /* mx == 0: average [0] and [2]
1572                    mx == 4: average [1] and [3] */
1573                 src[!mx] = src[2 + !!mx];
1574                 nplanes = 2;
1575             } else if (!(my&3)) {
1576                 src[0] = src[(my>>1)  ];
1577                 src[1] = src[(my>>1)+1];
1578                 nplanes = 2;
1579             }
1580         } else {
1581             /* adjust the ordering if needed so the weights work */
1582             if (mx > 4) {
1583                 FFSWAP(const uint8_t *, src[0], src[1]);
1584                 FFSWAP(const uint8_t *, src[2], src[3]);
1585             }
1586             if (my > 4) {
1587                 FFSWAP(const uint8_t *, src[0], src[2]);
1588                 FFSWAP(const uint8_t *, src[1], src[3]);
1589             }
1590             src[4] = epel_weights[my&3][mx&3];
1591         }
1592     }
1593
1594     /* fixme: v/h _edge_pos */
1595     if (x + p->xblen > p->width +EDGE_WIDTH/2 ||
1596         y + p->yblen > p->height+EDGE_WIDTH/2 ||
1597         x < 0 || y < 0) {
1598         for (i = 0; i < nplanes; i++) {
1599             s->vdsp.emulated_edge_mc(s->edge_emu_buffer[i], src[i],
1600                                      p->stride, p->stride,
1601                                      p->xblen, p->yblen, x, y,
1602                                      p->width+EDGE_WIDTH/2, p->height+EDGE_WIDTH/2);
1603             src[i] = s->edge_emu_buffer[i];
1604         }
1605     }
1606     return (nplanes>>1) + epel;
1607 }
1608
1609 static void add_dc(uint16_t *dst, int dc, int stride,
1610                    uint8_t *obmc_weight, int xblen, int yblen)
1611 {
1612     int x, y;
1613     dc += 128;
1614
1615     for (y = 0; y < yblen; y++) {
1616         for (x = 0; x < xblen; x += 2) {
1617             dst[x  ] += dc * obmc_weight[x  ];
1618             dst[x+1] += dc * obmc_weight[x+1];
1619         }
1620         dst          += stride;
1621         obmc_weight  += MAX_BLOCKSIZE;
1622     }
1623 }
1624
1625 static void block_mc(DiracContext *s, DiracBlock *block,
1626                      uint16_t *mctmp, uint8_t *obmc_weight,
1627                      int plane, int dstx, int dsty)
1628 {
1629     Plane *p = &s->plane[plane];
1630     const uint8_t *src[5];
1631     int idx;
1632
1633     switch (block->ref&3) {
1634     case 0: /* DC */
1635         add_dc(mctmp, block->u.dc[plane], p->stride, obmc_weight, p->xblen, p->yblen);
1636         return;
1637     case 1:
1638     case 2:
1639         idx = mc_subpel(s, block, src, dstx, dsty, (block->ref&3)-1, plane);
1640         s->put_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen);
1641         if (s->weight_func)
1642             s->weight_func(s->mcscratch, p->stride, s->weight_log2denom,
1643                            s->weight[0] + s->weight[1], p->yblen);
1644         break;
1645     case 3:
1646         idx = mc_subpel(s, block, src, dstx, dsty, 0, plane);
1647         s->put_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen);
1648         idx = mc_subpel(s, block, src, dstx, dsty, 1, plane);
1649         if (s->biweight_func) {
1650             /* fixme: +32 is a quick hack */
1651             s->put_pixels_tab[idx](s->mcscratch + 32, src, p->stride, p->yblen);
1652             s->biweight_func(s->mcscratch, s->mcscratch+32, p->stride, s->weight_log2denom,
1653                              s->weight[0], s->weight[1], p->yblen);
1654         } else
1655             s->avg_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen);
1656         break;
1657     }
1658     s->add_obmc(mctmp, s->mcscratch, p->stride, obmc_weight, p->yblen);
1659 }
1660
1661 static void mc_row(DiracContext *s, DiracBlock *block, uint16_t *mctmp, int plane, int dsty)
1662 {
1663     Plane *p = &s->plane[plane];
1664     int x, dstx = p->xbsep - p->xoffset;
1665
1666     block_mc(s, block, mctmp, s->obmc_weight[0], plane, -p->xoffset, dsty);
1667     mctmp += p->xbsep;
1668
1669     for (x = 1; x < s->blwidth-1; x++) {
1670         block_mc(s, block+x, mctmp, s->obmc_weight[1], plane, dstx, dsty);
1671         dstx  += p->xbsep;
1672         mctmp += p->xbsep;
1673     }
1674     block_mc(s, block+x, mctmp, s->obmc_weight[2], plane, dstx, dsty);
1675 }
1676
1677 static void select_dsp_funcs(DiracContext *s, int width, int height, int xblen, int yblen)
1678 {
1679     int idx = 0;
1680     if (xblen > 8)
1681         idx = 1;
1682     if (xblen > 16)
1683         idx = 2;
1684
1685     memcpy(s->put_pixels_tab, s->diracdsp.put_dirac_pixels_tab[idx], sizeof(s->put_pixels_tab));
1686     memcpy(s->avg_pixels_tab, s->diracdsp.avg_dirac_pixels_tab[idx], sizeof(s->avg_pixels_tab));
1687     s->add_obmc = s->diracdsp.add_dirac_obmc[idx];
1688     if (s->weight_log2denom > 1 || s->weight[0] != 1 || s->weight[1] != 1) {
1689         s->weight_func   = s->diracdsp.weight_dirac_pixels_tab[idx];
1690         s->biweight_func = s->diracdsp.biweight_dirac_pixels_tab[idx];
1691     } else {
1692         s->weight_func   = NULL;
1693         s->biweight_func = NULL;
1694     }
1695 }
1696
1697 static int interpolate_refplane(DiracContext *s, DiracFrame *ref, int plane, int width, int height)
1698 {
1699     /* chroma allocates an edge of 8 when subsampled
1700        which for 4:2:2 means an h edge of 16 and v edge of 8
1701        just use 8 for everything for the moment */
1702     int i, edge = EDGE_WIDTH/2;
1703
1704     ref->hpel[plane][0] = ref->avframe->data[plane];
1705     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 */
1706
1707     /* no need for hpel if we only have fpel vectors */
1708     if (!s->mv_precision)
1709         return 0;
1710
1711     for (i = 1; i < 4; i++) {
1712         if (!ref->hpel_base[plane][i])
1713             ref->hpel_base[plane][i] = av_malloc((height+2*edge) * ref->avframe->linesize[plane] + 32);
1714         if (!ref->hpel_base[plane][i]) {
1715             return AVERROR(ENOMEM);
1716         }
1717         /* we need to be 16-byte aligned even for chroma */
1718         ref->hpel[plane][i] = ref->hpel_base[plane][i] + edge*ref->avframe->linesize[plane] + 16;
1719     }
1720
1721     if (!ref->interpolated[plane]) {
1722         s->diracdsp.dirac_hpel_filter(ref->hpel[plane][1], ref->hpel[plane][2],
1723                                       ref->hpel[plane][3], ref->hpel[plane][0],
1724                                       ref->avframe->linesize[plane], width, height);
1725         s->mpvencdsp.draw_edges(ref->hpel[plane][1], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);
1726         s->mpvencdsp.draw_edges(ref->hpel[plane][2], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);
1727         s->mpvencdsp.draw_edges(ref->hpel[plane][3], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);
1728     }
1729     ref->interpolated[plane] = 1;
1730
1731     return 0;
1732 }
1733
1734 /**
1735  * Dirac Specification ->
1736  * 13.0 Transform data syntax. transform_data()
1737  */
1738 static int dirac_decode_frame_internal(DiracContext *s)
1739 {
1740     DWTContext d;
1741     int y, i, comp, dsty;
1742     int ret;
1743
1744     if (s->low_delay) {
1745         /* [DIRAC_STD] 13.5.1 low_delay_transform_data() */
1746         for (comp = 0; comp < 3; comp++) {
1747             Plane *p = &s->plane[comp];
1748             memset(p->idwt.buf, 0, p->idwt.stride * p->idwt.height);
1749         }
1750         if (!s->zero_res) {
1751             if ((ret = decode_lowdelay(s)) < 0)
1752                 return ret;
1753         }
1754     }
1755
1756     for (comp = 0; comp < 3; comp++) {
1757         Plane *p       = &s->plane[comp];
1758         uint8_t *frame = s->current_picture->avframe->data[comp];
1759
1760         /* FIXME: small resolutions */
1761         for (i = 0; i < 4; i++)
1762             s->edge_emu_buffer[i] = s->edge_emu_buffer_base + i*FFALIGN(p->width, 16);
1763
1764         if (!s->zero_res && !s->low_delay)
1765         {
1766             memset(p->idwt.buf, 0, p->idwt.stride * p->idwt.height);
1767             decode_component(s, comp); /* [DIRAC_STD] 13.4.1 core_transform_data() */
1768         }
1769         ret = ff_spatial_idwt_init(&d, &p->idwt, s->wavelet_idx+2,
1770                                    s->wavelet_depth, s->bit_depth);
1771         if (ret < 0)
1772             return ret;
1773
1774         if (!s->num_refs) { /* intra */
1775             for (y = 0; y < p->height; y += 16) {
1776                 int idx = (s->bit_depth - 8) >> 1;
1777                 ff_spatial_idwt_slice2(&d, y+16); /* decode */
1778                 s->diracdsp.put_signed_rect_clamped[idx](frame + y*p->stride,
1779                                                          p->stride,
1780                                                          p->idwt.buf + y*p->idwt.stride,
1781                                                          p->idwt.stride, p->width, 16);
1782             }
1783         } else { /* inter */
1784             int rowheight = p->ybsep*p->stride;
1785
1786             select_dsp_funcs(s, p->width, p->height, p->xblen, p->yblen);
1787
1788             for (i = 0; i < s->num_refs; i++) {
1789                 int ret = interpolate_refplane(s, s->ref_pics[i], comp, p->width, p->height);
1790                 if (ret < 0)
1791                     return ret;
1792             }
1793
1794             memset(s->mctmp, 0, 4*p->yoffset*p->stride);
1795
1796             dsty = -p->yoffset;
1797             for (y = 0; y < s->blheight; y++) {
1798                 int h     = 0,
1799                     start = FFMAX(dsty, 0);
1800                 uint16_t *mctmp    = s->mctmp + y*rowheight;
1801                 DiracBlock *blocks = s->blmotion + y*s->blwidth;
1802
1803                 init_obmc_weights(s, p, y);
1804
1805                 if (y == s->blheight-1 || start+p->ybsep > p->height)
1806                     h = p->height - start;
1807                 else
1808                     h = p->ybsep - (start - dsty);
1809                 if (h < 0)
1810                     break;
1811
1812                 memset(mctmp+2*p->yoffset*p->stride, 0, 2*rowheight);
1813                 mc_row(s, blocks, mctmp, comp, dsty);
1814
1815                 mctmp += (start - dsty)*p->stride + p->xoffset;
1816                 ff_spatial_idwt_slice2(&d, start + h); /* decode */
1817                 /* NOTE: add_rect_clamped hasn't been templated hence the shifts.
1818                  * idwt.stride is passed as pixels, not in bytes as in the rest of the decoder */
1819                 s->diracdsp.add_rect_clamped(frame + start*p->stride, mctmp, p->stride,
1820                                              (int16_t*)(p->idwt.buf) + start*(p->idwt.stride >> 1), (p->idwt.stride >> 1), p->width, h);
1821
1822                 dsty += p->ybsep;
1823             }
1824         }
1825     }
1826
1827
1828     return 0;
1829 }
1830
1831 static int get_buffer_with_edge(AVCodecContext *avctx, AVFrame *f, int flags)
1832 {
1833     int ret, i;
1834     int chroma_x_shift, chroma_y_shift;
1835     avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_x_shift, &chroma_y_shift);
1836
1837     f->width  = avctx->width  + 2 * EDGE_WIDTH;
1838     f->height = avctx->height + 2 * EDGE_WIDTH + 2;
1839     ret = ff_get_buffer(avctx, f, flags);
1840     if (ret < 0)
1841         return ret;
1842
1843     for (i = 0; f->data[i]; i++) {
1844         int offset = (EDGE_WIDTH >> (i && i<3 ? chroma_y_shift : 0)) *
1845                      f->linesize[i] + 32;
1846         f->data[i] += offset;
1847     }
1848     f->width  = avctx->width;
1849     f->height = avctx->height;
1850
1851     return 0;
1852 }
1853
1854 /**
1855  * Dirac Specification ->
1856  * 11.1.1 Picture Header. picture_header()
1857  */
1858 static int dirac_decode_picture_header(DiracContext *s)
1859 {
1860     unsigned retire, picnum;
1861     int i, j, ret;
1862     int64_t refdist, refnum;
1863     GetBitContext *gb = &s->gb;
1864
1865     /* [DIRAC_STD] 11.1.1 Picture Header. picture_header() PICTURE_NUM */
1866     picnum = s->current_picture->avframe->display_picture_number = get_bits_long(gb, 32);
1867
1868
1869     av_log(s->avctx,AV_LOG_DEBUG,"PICTURE_NUM: %d\n",picnum);
1870
1871     /* if this is the first keyframe after a sequence header, start our
1872        reordering from here */
1873     if (s->frame_number < 0)
1874         s->frame_number = picnum;
1875
1876     s->ref_pics[0] = s->ref_pics[1] = NULL;
1877     for (i = 0; i < s->num_refs; i++) {
1878         refnum = (picnum + dirac_get_se_golomb(gb)) & 0xFFFFFFFF;
1879         refdist = INT64_MAX;
1880
1881         /* find the closest reference to the one we want */
1882         /* Jordi: this is needed if the referenced picture hasn't yet arrived */
1883         for (j = 0; j < MAX_REFERENCE_FRAMES && refdist; j++)
1884             if (s->ref_frames[j]
1885                 && FFABS(s->ref_frames[j]->avframe->display_picture_number - refnum) < refdist) {
1886                 s->ref_pics[i] = s->ref_frames[j];
1887                 refdist = FFABS(s->ref_frames[j]->avframe->display_picture_number - refnum);
1888             }
1889
1890         if (!s->ref_pics[i] || refdist)
1891             av_log(s->avctx, AV_LOG_DEBUG, "Reference not found\n");
1892
1893         /* if there were no references at all, allocate one */
1894         if (!s->ref_pics[i])
1895             for (j = 0; j < MAX_FRAMES; j++)
1896                 if (!s->all_frames[j].avframe->data[0]) {
1897                     s->ref_pics[i] = &s->all_frames[j];
1898                     get_buffer_with_edge(s->avctx, s->ref_pics[i]->avframe, AV_GET_BUFFER_FLAG_REF);
1899                     break;
1900                 }
1901
1902         if (!s->ref_pics[i]) {
1903             av_log(s->avctx, AV_LOG_ERROR, "Reference could not be allocated\n");
1904             return AVERROR_INVALIDDATA;
1905         }
1906
1907     }
1908
1909     /* retire the reference frames that are not used anymore */
1910     if (s->current_picture->reference) {
1911         retire = (picnum + dirac_get_se_golomb(gb)) & 0xFFFFFFFF;
1912         if (retire != picnum) {
1913             DiracFrame *retire_pic = remove_frame(s->ref_frames, retire);
1914
1915             if (retire_pic)
1916                 retire_pic->reference &= DELAYED_PIC_REF;
1917             else
1918                 av_log(s->avctx, AV_LOG_DEBUG, "Frame to retire not found\n");
1919         }
1920
1921         /* if reference array is full, remove the oldest as per the spec */
1922         while (add_frame(s->ref_frames, MAX_REFERENCE_FRAMES, s->current_picture)) {
1923             av_log(s->avctx, AV_LOG_ERROR, "Reference frame overflow\n");
1924             remove_frame(s->ref_frames, s->ref_frames[0]->avframe->display_picture_number)->reference &= DELAYED_PIC_REF;
1925         }
1926     }
1927
1928     if (s->num_refs) {
1929         ret = dirac_unpack_prediction_parameters(s);  /* [DIRAC_STD] 11.2 Picture Prediction Data. picture_prediction() */
1930         if (ret < 0)
1931             return ret;
1932         ret = dirac_unpack_block_motion_data(s);      /* [DIRAC_STD] 12. Block motion data syntax                       */
1933         if (ret < 0)
1934             return ret;
1935     }
1936     ret = dirac_unpack_idwt_params(s);                /* [DIRAC_STD] 11.3 Wavelet transform data                        */
1937     if (ret < 0)
1938         return ret;
1939
1940     init_planes(s);
1941     return 0;
1942 }
1943
1944 static int get_delayed_pic(DiracContext *s, AVFrame *picture, int *got_frame)
1945 {
1946     DiracFrame *out = s->delay_frames[0];
1947     int i, out_idx  = 0;
1948     int ret;
1949
1950     /* find frame with lowest picture number */
1951     for (i = 1; s->delay_frames[i]; i++)
1952         if (s->delay_frames[i]->avframe->display_picture_number < out->avframe->display_picture_number) {
1953             out     = s->delay_frames[i];
1954             out_idx = i;
1955         }
1956
1957     for (i = out_idx; s->delay_frames[i]; i++)
1958         s->delay_frames[i] = s->delay_frames[i+1];
1959
1960     if (out) {
1961         out->reference ^= DELAYED_PIC_REF;
1962         *got_frame = 1;
1963         if((ret = av_frame_ref(picture, out->avframe)) < 0)
1964             return ret;
1965     }
1966
1967     return 0;
1968 }
1969
1970 /**
1971  * Dirac Specification ->
1972  * 9.6 Parse Info Header Syntax. parse_info()
1973  * 4 byte start code + byte parse code + 4 byte size + 4 byte previous size
1974  */
1975 #define DATA_UNIT_HEADER_SIZE 13
1976
1977 /* [DIRAC_STD] dirac_decode_data_unit makes reference to the while defined in 9.3
1978    inside the function parse_sequence() */
1979 static int dirac_decode_data_unit(AVCodecContext *avctx, const uint8_t *buf, int size)
1980 {
1981     DiracContext *s   = avctx->priv_data;
1982     DiracFrame *pic   = NULL;
1983     AVDiracSeqHeader *dsh;
1984     int ret, i;
1985     uint8_t parse_code;
1986     unsigned tmp;
1987
1988     if (size < DATA_UNIT_HEADER_SIZE)
1989         return AVERROR_INVALIDDATA;
1990
1991     parse_code = buf[4];
1992
1993     init_get_bits(&s->gb, &buf[13], 8*(size - DATA_UNIT_HEADER_SIZE));
1994
1995     if (parse_code == DIRAC_PCODE_SEQ_HEADER) {
1996         if (s->seen_sequence_header)
1997             return 0;
1998
1999         /* [DIRAC_STD] 10. Sequence header */
2000         ret = av_dirac_parse_sequence_header(&dsh, buf + DATA_UNIT_HEADER_SIZE, size - DATA_UNIT_HEADER_SIZE, avctx);
2001         if (ret < 0) {
2002             av_log(avctx, AV_LOG_ERROR, "error parsing sequence header");
2003             return ret;
2004         }
2005
2006         ret = ff_set_dimensions(avctx, dsh->width, dsh->height);
2007         if (ret < 0) {
2008             av_freep(&dsh);
2009             return ret;
2010         }
2011
2012         ff_set_sar(avctx, dsh->sample_aspect_ratio);
2013         avctx->pix_fmt         = dsh->pix_fmt;
2014         avctx->color_range     = dsh->color_range;
2015         avctx->color_trc       = dsh->color_trc;
2016         avctx->color_primaries = dsh->color_primaries;
2017         avctx->colorspace      = dsh->colorspace;
2018         avctx->profile         = dsh->profile;
2019         avctx->level           = dsh->level;
2020         avctx->framerate       = dsh->framerate;
2021         s->bit_depth           = dsh->bit_depth;
2022         s->version.major       = dsh->version.major;
2023         s->version.minor       = dsh->version.minor;
2024         s->seq                 = *dsh;
2025         av_freep(&dsh);
2026
2027         s->pshift = s->bit_depth > 8;
2028
2029         avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
2030
2031         ret = alloc_sequence_buffers(s);
2032         if (ret < 0)
2033             return ret;
2034
2035         s->seen_sequence_header = 1;
2036     } else if (parse_code == DIRAC_PCODE_END_SEQ) { /* [DIRAC_STD] End of Sequence */
2037         free_sequence_buffers(s);
2038         s->seen_sequence_header = 0;
2039     } else if (parse_code == DIRAC_PCODE_AUX) {
2040         if (buf[13] == 1) {     /* encoder implementation/version */
2041             int ver[3];
2042             /* versions older than 1.0.8 don't store quant delta for
2043                subbands with only one codeblock */
2044             if (sscanf(buf+14, "Schroedinger %d.%d.%d", ver, ver+1, ver+2) == 3)
2045                 if (ver[0] == 1 && ver[1] == 0 && ver[2] <= 7)
2046                     s->old_delta_quant = 1;
2047         }
2048     } else if (parse_code & 0x8) {  /* picture data unit */
2049         if (!s->seen_sequence_header) {
2050             av_log(avctx, AV_LOG_DEBUG, "Dropping frame without sequence header\n");
2051             return AVERROR_INVALIDDATA;
2052         }
2053
2054         /* find an unused frame */
2055         for (i = 0; i < MAX_FRAMES; i++)
2056             if (s->all_frames[i].avframe->data[0] == NULL)
2057                 pic = &s->all_frames[i];
2058         if (!pic) {
2059             av_log(avctx, AV_LOG_ERROR, "framelist full\n");
2060             return AVERROR_INVALIDDATA;
2061         }
2062
2063         av_frame_unref(pic->avframe);
2064
2065         /* [DIRAC_STD] Defined in 9.6.1 ... */
2066         tmp            =  parse_code & 0x03;                   /* [DIRAC_STD] num_refs()      */
2067         if (tmp > 2) {
2068             av_log(avctx, AV_LOG_ERROR, "num_refs of 3\n");
2069             return AVERROR_INVALIDDATA;
2070         }
2071         s->num_refs      = tmp;
2072         s->is_arith      = (parse_code & 0x48) == 0x08;          /* [DIRAC_STD] using_ac()            */
2073         s->low_delay     = (parse_code & 0x88) == 0x88;          /* [DIRAC_STD] is_low_delay()        */
2074         s->core_syntax   = (parse_code & 0x88) == 0x08;          /* [DIRAC_STD] is_core_syntax()      */
2075         s->ld_picture    = (parse_code & 0xF8) == 0xC8;          /* [DIRAC_STD] is_ld_picture()       */
2076         s->hq_picture    = (parse_code & 0xF8) == 0xE8;          /* [DIRAC_STD] is_hq_picture()       */
2077         s->dc_prediction = (parse_code & 0x28) == 0x08;          /* [DIRAC_STD] using_dc_prediction() */
2078         pic->reference   = (parse_code & 0x0C) == 0x0C;          /* [DIRAC_STD] is_reference()        */
2079         pic->avframe->key_frame = s->num_refs == 0;              /* [DIRAC_STD] is_intra()            */
2080         pic->avframe->pict_type = s->num_refs + 1;               /* Definition of AVPictureType in avutil.h */
2081
2082         /* VC-2 Low Delay has a different parse code than the Dirac Low Delay */
2083         if (s->version.minor == 2 && parse_code == 0x88)
2084             s->ld_picture = 1;
2085
2086         if (s->low_delay && !(s->ld_picture || s->hq_picture) ) {
2087             av_log(avctx, AV_LOG_ERROR, "Invalid low delay flag\n");
2088             return AVERROR_INVALIDDATA;
2089         }
2090
2091         if ((ret = get_buffer_with_edge(avctx, pic->avframe, (parse_code & 0x0C) == 0x0C ? AV_GET_BUFFER_FLAG_REF : 0)) < 0)
2092             return ret;
2093         s->current_picture = pic;
2094         s->plane[0].stride = pic->avframe->linesize[0];
2095         s->plane[1].stride = pic->avframe->linesize[1];
2096         s->plane[2].stride = pic->avframe->linesize[2];
2097
2098         if (alloc_buffers(s, FFMAX3(FFABS(s->plane[0].stride), FFABS(s->plane[1].stride), FFABS(s->plane[2].stride))) < 0)
2099             return AVERROR(ENOMEM);
2100
2101         /* [DIRAC_STD] 11.1 Picture parse. picture_parse() */
2102         ret = dirac_decode_picture_header(s);
2103         if (ret < 0)
2104             return ret;
2105
2106         /* [DIRAC_STD] 13.0 Transform data syntax. transform_data() */
2107         ret = dirac_decode_frame_internal(s);
2108         if (ret < 0)
2109             return ret;
2110     }
2111     return 0;
2112 }
2113
2114 static int dirac_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt)
2115 {
2116     DiracContext *s     = avctx->priv_data;
2117     AVFrame *picture    = data;
2118     uint8_t *buf        = pkt->data;
2119     int buf_size        = pkt->size;
2120     int i, buf_idx      = 0;
2121     int ret;
2122     unsigned data_unit_size;
2123
2124     /* release unused frames */
2125     for (i = 0; i < MAX_FRAMES; i++)
2126         if (s->all_frames[i].avframe->data[0] && !s->all_frames[i].reference) {
2127             av_frame_unref(s->all_frames[i].avframe);
2128             memset(s->all_frames[i].interpolated, 0, sizeof(s->all_frames[i].interpolated));
2129         }
2130
2131     s->current_picture = NULL;
2132     *got_frame = 0;
2133
2134     /* end of stream, so flush delayed pics */
2135     if (buf_size == 0)
2136         return get_delayed_pic(s, (AVFrame *)data, got_frame);
2137
2138     for (;;) {
2139         /*[DIRAC_STD] Here starts the code from parse_info() defined in 9.6
2140           [DIRAC_STD] PARSE_INFO_PREFIX = "BBCD" as defined in ISO/IEC 646
2141           BBCD start code search */
2142         for (; buf_idx + DATA_UNIT_HEADER_SIZE < buf_size; buf_idx++) {
2143             if (buf[buf_idx  ] == 'B' && buf[buf_idx+1] == 'B' &&
2144                 buf[buf_idx+2] == 'C' && buf[buf_idx+3] == 'D')
2145                 break;
2146         }
2147         /* BBCD found or end of data */
2148         if (buf_idx + DATA_UNIT_HEADER_SIZE >= buf_size)
2149             break;
2150
2151         data_unit_size = AV_RB32(buf+buf_idx+5);
2152         if (data_unit_size > buf_size - buf_idx || !data_unit_size) {
2153             if(data_unit_size > buf_size - buf_idx)
2154             av_log(s->avctx, AV_LOG_ERROR,
2155                    "Data unit with size %d is larger than input buffer, discarding\n",
2156                    data_unit_size);
2157             buf_idx += 4;
2158             continue;
2159         }
2160         /* [DIRAC_STD] dirac_decode_data_unit makes reference to the while defined in 9.3 inside the function parse_sequence() */
2161         ret = dirac_decode_data_unit(avctx, buf+buf_idx, data_unit_size);
2162         if (ret < 0)
2163         {
2164             av_log(s->avctx, AV_LOG_ERROR,"Error in dirac_decode_data_unit\n");
2165             return ret;
2166         }
2167         buf_idx += data_unit_size;
2168     }
2169
2170     if (!s->current_picture)
2171         return buf_size;
2172
2173     if (s->current_picture->avframe->display_picture_number > s->frame_number) {
2174         DiracFrame *delayed_frame = remove_frame(s->delay_frames, s->frame_number);
2175
2176         s->current_picture->reference |= DELAYED_PIC_REF;
2177
2178         if (add_frame(s->delay_frames, MAX_DELAY, s->current_picture)) {
2179             int min_num = s->delay_frames[0]->avframe->display_picture_number;
2180             /* Too many delayed frames, so we display the frame with the lowest pts */
2181             av_log(avctx, AV_LOG_ERROR, "Delay frame overflow\n");
2182
2183             for (i = 1; s->delay_frames[i]; i++)
2184                 if (s->delay_frames[i]->avframe->display_picture_number < min_num)
2185                     min_num = s->delay_frames[i]->avframe->display_picture_number;
2186
2187             delayed_frame = remove_frame(s->delay_frames, min_num);
2188             add_frame(s->delay_frames, MAX_DELAY, s->current_picture);
2189         }
2190
2191         if (delayed_frame) {
2192             delayed_frame->reference ^= DELAYED_PIC_REF;
2193             if((ret=av_frame_ref(data, delayed_frame->avframe)) < 0)
2194                 return ret;
2195             *got_frame = 1;
2196         }
2197     } else if (s->current_picture->avframe->display_picture_number == s->frame_number) {
2198         /* The right frame at the right time :-) */
2199         if((ret=av_frame_ref(data, s->current_picture->avframe)) < 0)
2200             return ret;
2201         *got_frame = 1;
2202     }
2203
2204     if (*got_frame)
2205         s->frame_number = picture->display_picture_number + 1;
2206
2207     return buf_idx;
2208 }
2209
2210 AVCodec ff_dirac_decoder = {
2211     .name           = "dirac",
2212     .long_name      = NULL_IF_CONFIG_SMALL("BBC Dirac VC-2"),
2213     .type           = AVMEDIA_TYPE_VIDEO,
2214     .id             = AV_CODEC_ID_DIRAC,
2215     .priv_data_size = sizeof(DiracContext),
2216     .init           = dirac_decode_init,
2217     .close          = dirac_decode_end,
2218     .decode         = dirac_decode_frame,
2219     .capabilities   = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS | AV_CODEC_CAP_DR1,
2220     .flush          = dirac_decode_flush,
2221 };