OSDN Git Service

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