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