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