2 * Copyright (C) 2007 Marco Gerards <marco@gnu.org>
3 * Copyright (C) 2009 David Conrad
4 * Copyright (C) 2011 Jordi Ortiz
6 * This file is part of FFmpeg.
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.
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.
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
26 * @author Marco Gerards <marco@gnu.org>, David Conrad, Jordi Ortiz <nenjordi@gmail.com>
29 #include "libavutil/pixdesc.h"
30 #include "libavutil/thread.h"
33 #include "bytestream.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"
48 * The spec limits this to 3 for frame coding, but in practice can be as high as 6
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 */
57 * DiracBlock->ref flags, if set then the block does MC from the given ref
59 #define DIRAC_REF_MASK_REF1 1
60 #define DIRAC_REF_MASK_REF2 2
61 #define DIRAC_REF_MASK_GLOBAL 4
64 * Value of Picture.reference when Picture is not a reference picture, but
65 * is held for delayed output.
67 #define DELAYED_PIC_REF 4
69 #define CALC_PADDING(size, depth) \
70 (((size + (1 << depth) - 1) >> depth) << depth)
72 #define DIVRNDUP(a, b) (((a) + (b) - 1) / (b))
76 int interpolated[3]; /* 1 if hpel[] is valid */
78 uint8_t *hpel_base[3][4];
86 } u; /* anonymous unions aren't in C99 :( */
90 typedef struct SubBand {
93 int stride; /* in bytes */
99 struct SubBand *parent;
103 const uint8_t *coeff_data;
106 typedef struct Plane {
116 /* block separation (block n+1 starts after this many pixels in block n) */
119 /* amount of overspill on each edge (half of the overlap between blocks) */
123 SubBand band[MAX_DWT_LEVELS][4];
126 /* Used by Low Delay and High Quality profiles */
127 typedef struct DiracSlice {
134 typedef struct DiracContext {
135 AVCodecContext *avctx;
136 MpegvideoEncDSPContext mpvencdsp;
137 VideoDSPContext vdsp;
138 DiracDSPContext diracdsp;
139 DiracGolombLUT *reader_ctx;
140 DiracVersionInfo version;
142 AVDiracSeqHeader seq;
143 int seen_sequence_header;
144 int64_t frame_number; /* number of the next frame to display */
149 int bit_depth; /* bit depth */
150 int pshift; /* pixel shift = bit_depth > 8 */
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 */
162 /* wavelet decoding */
163 unsigned wavelet_depth; /* depth of the IDWT */
164 unsigned wavelet_idx;
167 * schroedinger older than 1.0.8 doesn't store
168 * quant delta if only one codebook exists in a band
170 unsigned old_delta_quant;
171 unsigned codeblock_mode;
173 unsigned num_x; /* number of horizontal slices */
174 unsigned num_y; /* number of vertical slices */
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 */
180 DiracSlice *slice_params_buf;
181 int slice_params_num_buf;
186 } codeblock[MAX_DWT_LEVELS+1];
189 AVRational bytes; /* average bytes per slice */
190 uint8_t quant[MAX_DWT_LEVELS][4]; /* [DIRAC_STD] E.1 */
194 unsigned prefix_bytes;
195 uint64_t size_scaler;
199 int pan_tilt[2]; /* pan/tilt vector */
200 int zrs[2][2]; /* zoom/rotate/shear matrix */
201 int perspective[2]; /* perspective vector */
203 unsigned perspective_exp;
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 */
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) */
217 DiracBlock *blmotion;
219 uint8_t *edge_emu_buffer[4];
220 uint8_t *edge_emu_buffer_base;
222 uint16_t *mctmp; /* buffer holding the MC data multiplied by OBMC weights */
226 DECLARE_ALIGNED(16, uint8_t, obmc_weight)[3][MAX_BLOCKSIZE*MAX_BLOCKSIZE];
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;
234 DiracFrame *current_picture;
235 DiracFrame *ref_pics[2];
237 DiracFrame *ref_frames[MAX_REFERENCE_FRAMES+1];
238 DiracFrame *delay_frames[MAX_DELAY+1];
239 DiracFrame all_frames[MAX_FRAMES];
250 /* magic number division by 3 from schroedinger */
251 static inline int divide3(int x)
253 return (int)((x+1U)*21845 + 10922) >> 16;
256 static DiracFrame *remove_frame(DiracFrame *framelist[], int picnum)
258 DiracFrame *remove_pic = NULL;
259 int i, remove_idx = -1;
261 for (i = 0; framelist[i]; i++)
262 if (framelist[i]->avframe->display_picture_number == picnum) {
263 remove_pic = framelist[i];
268 for (i = remove_idx; framelist[i]; i++)
269 framelist[i] = framelist[i+1];
274 static int add_frame(DiracFrame *framelist[], int maxframes, DiracFrame *frame)
277 for (i = 0; i < maxframes; i++)
279 framelist[i] = frame;
285 static int alloc_sequence_buffers(DiracContext *s)
287 int sbwidth = DIVRNDUP(s->seq.width, 4);
288 int sbheight = DIVRNDUP(s->seq.height, 4);
289 int i, w, h, top_padding;
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);
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
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;
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);
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));
318 if (!s->sbsplit || !s->blmotion)
319 return AVERROR(ENOMEM);
323 static int alloc_buffers(DiracContext *s, int stride)
325 int w = s->seq.width;
326 int h = s->seq.height;
328 av_assert0(stride >= w);
331 if (s->buffer_stride >= stride)
333 s->buffer_stride = 0;
335 av_freep(&s->edge_emu_buffer_base);
336 memset(s->edge_emu_buffer, 0, sizeof(s->edge_emu_buffer));
338 av_freep(&s->mcscratch);
340 s->edge_emu_buffer_base = av_malloc_array(stride, MAX_BLOCKSIZE);
342 s->mctmp = av_malloc_array((stride+MAX_BLOCKSIZE), (h+MAX_BLOCKSIZE) * sizeof(*s->mctmp));
343 s->mcscratch = av_malloc_array(stride, MAX_BLOCKSIZE);
345 if (!s->edge_emu_buffer_base || !s->mctmp || !s->mcscratch)
346 return AVERROR(ENOMEM);
348 s->buffer_stride = stride;
352 static void free_sequence_buffers(DiracContext *s)
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));
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]);
367 memset(s->ref_frames, 0, sizeof(s->ref_frames));
368 memset(s->delay_frames, 0, sizeof(s->delay_frames));
370 for (i = 0; i < 3; i++) {
371 av_freep(&s->plane[i].idwt.buf_base);
372 av_freep(&s->plane[i].idwt.tmp);
375 s->buffer_stride = 0;
376 av_freep(&s->sbsplit);
377 av_freep(&s->blmotion);
378 av_freep(&s->edge_emu_buffer_base);
381 av_freep(&s->mcscratch);
384 static AVOnce dirac_arith_init = AV_ONCE_INIT;
386 static av_cold int dirac_decode_init(AVCodecContext *avctx)
388 DiracContext *s = avctx->priv_data;
392 s->frame_number = -1;
394 s->thread_buf = NULL;
395 s->threads_num_buf = -1;
396 s->thread_buf_size = -1;
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);
403 for (i = 0; i < MAX_FRAMES; i++) {
404 s->all_frames[i].avframe = av_frame_alloc();
405 if (!s->all_frames[i].avframe) {
407 av_frame_free(&s->all_frames[--i].avframe);
408 return AVERROR(ENOMEM);
411 ret = ff_thread_once(&dirac_arith_init, ff_dirac_init_arith_tables);
413 return AVERROR_UNKNOWN;
418 static void dirac_decode_flush(AVCodecContext *avctx)
420 DiracContext *s = avctx->priv_data;
421 free_sequence_buffers(s);
422 s->seen_sequence_header = 0;
423 s->frame_number = -1;
426 static av_cold int dirac_decode_end(AVCodecContext *avctx)
428 DiracContext *s = avctx->priv_data;
431 ff_dirac_golomb_reader_end(&s->reader_ctx);
433 dirac_decode_flush(avctx);
434 for (i = 0; i < MAX_FRAMES; i++)
435 av_frame_free(&s->all_frames[i].avframe);
437 av_freep(&s->thread_buf);
438 av_freep(&s->slice_params_buf);
443 static inline int coeff_unpack_golomb(GetBitContext *gb, int qfactor, int qoffset)
445 int coeff = dirac_get_se_golomb(gb);
446 const unsigned sign = FFSIGN(coeff);
448 coeff = sign*((sign * coeff * qfactor + qoffset) >> 2);
452 #define SIGN_CTX(x) (CTX_SIGN_ZERO + ((x) > 0) - ((x) < 0))
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) \
458 int sign, sign_pred = 0, pred_ctx = CTX_ZPZN_F1; \
460 const int mstride = -(b->stride >> (1+b->pshift)); \
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; \
466 if (b->orientation == subband_hl) \
467 sign_pred = buf[mstride]; \
469 pred_ctx += !(buf[-1] | buf[mstride] | buf[-1 + mstride]); \
470 if (b->orientation == subband_lh) \
471 sign_pred = buf[-1]; \
473 pred_ctx += !buf[mstride]; \
475 coeff = dirac_get_arith_uint(c, pred_ctx, CTX_COEFF_DATA); \
477 coeff = (coeff * qfactor + qoffset) >> 2; \
478 sign = dirac_get_arith_bit(c, SIGN_CTX(sign_pred)); \
479 coeff = (coeff ^ -sign) + sign; \
484 UNPACK_ARITH(8, int16_t)
485 UNPACK_ARITH(10, int32_t)
488 * Decode the coeffs in the rectangle defined by left, right, top, bottom
489 * [DIRAC_STD] 13.4.3.2 Codeblock unpacking loop. codeblock()
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)
496 int x, y, zero_block;
497 int qoffset, qfactor;
500 /* check for any coded coefficients in this codeblock */
503 zero_block = dirac_get_arith_bit(c, CTX_ZERO_BLOCK);
505 zero_block = get_bits1(gb);
511 if (s->codeblock_mode && !(s->old_delta_quant && blockcnt_one)) {
514 quant = dirac_get_arith_int(c, CTX_DELTA_Q_F, CTX_DELTA_Q_DATA);
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;
524 if (b->quant > (DIRAC_MAX_QUANT_INDEX - 1)) {
525 av_log(s->avctx, AV_LOG_ERROR, "Unsupported quant %d\n", b->quant);
527 return AVERROR_INVALIDDATA;
530 qfactor = ff_dirac_qscale_tab[b->quant];
531 /* TODO: context pointer? */
533 qoffset = ff_dirac_qoffset_intra_tab[b->quant] + 2;
535 qoffset = ff_dirac_qoffset_inter_tab[b->quant] + 2;
537 buf = b->ibuf + top * b->stride;
539 for (y = top; y < bottom; y++) {
542 for (x = left; x < right; x++) {
544 coeff_unpack_arith_10(c, qfactor, qoffset, b, (int32_t*)(buf)+x, x, y);
546 coeff_unpack_arith_8(c, qfactor, qoffset, b, (int16_t*)(buf)+x, x, y);
552 for (y = top; y < bottom; y++) {
553 if (get_bits_left(gb) < 1)
554 return AVERROR_INVALIDDATA;
555 for (x = left; x < right; x++) {
556 int val = coeff_unpack_golomb(gb, qfactor, qoffset);
558 AV_WN32(&buf[4*x], val);
560 AV_WN16(&buf[2*x], val);
570 * Dirac Specification ->
571 * 13.3 intra_dc_prediction(band)
573 #define INTRA_DC_PRED(n, type) \
574 static inline void intra_dc_prediction_##n(SubBand *b) \
576 type *buf = (type*)b->ibuf; \
579 for (x = 1; x < b->width; x++) \
580 buf[x] += buf[x-1]; \
581 buf += (b->stride >> (1+b->pshift)); \
583 for (y = 1; y < b->height; y++) { \
584 buf[0] += buf[-(b->stride >> (1+b->pshift))]; \
586 for (x = 1; x < b->width; x++) { \
587 int pred = buf[x - 1] + buf[x - (b->stride >> (1+b->pshift))] + buf[x - (b->stride >> (1+b->pshift))-1]; \
588 buf[x] += divide3(pred); \
590 buf += (b->stride >> (1+b->pshift)); \
594 INTRA_DC_PRED(8, int16_t)
595 INTRA_DC_PRED(10, uint32_t)
598 * Dirac Specification ->
599 * 13.4.2 Non-skipped subbands. subband_coeffs()
601 static av_always_inline int decode_subband_internal(DiracContext *s, SubBand *b, int is_arith)
603 int cb_x, cb_y, left, right, top, bottom;
606 int cb_width = s->codeblock[b->level + (b->orientation != subband_ll)].width;
607 int cb_height = s->codeblock[b->level + (b->orientation != subband_ll)].height;
608 int blockcnt_one = (cb_width + cb_height) == 2;
614 init_get_bits8(&gb, b->coeff_data, b->length);
617 ff_dirac_init_arith_decoder(&c, &gb, b->length);
620 for (cb_y = 0; cb_y < cb_height; cb_y++) {
621 bottom = (b->height * (cb_y+1LL)) / cb_height;
623 for (cb_x = 0; cb_x < cb_width; cb_x++) {
624 right = (b->width * (cb_x+1LL)) / cb_width;
625 ret = codeblock(s, b, &gb, &c, left, right, top, bottom, blockcnt_one, is_arith);
633 if (b->orientation == subband_ll && s->num_refs == 0) {
635 intra_dc_prediction_10(b);
637 intra_dc_prediction_8(b);
643 static int decode_subband_arith(AVCodecContext *avctx, void *b)
645 DiracContext *s = avctx->priv_data;
646 return decode_subband_internal(s, b, 1);
649 static int decode_subband_golomb(AVCodecContext *avctx, void *arg)
651 DiracContext *s = avctx->priv_data;
653 return decode_subband_internal(s, *b, 0);
657 * Dirac Specification ->
658 * [DIRAC_STD] 13.4.1 core_transform_data()
660 static int decode_component(DiracContext *s, int comp)
662 AVCodecContext *avctx = s->avctx;
663 SubBand *bands[3*MAX_DWT_LEVELS+1];
664 enum dirac_subband orientation;
665 int level, num_bands = 0;
666 int ret[3*MAX_DWT_LEVELS+1];
668 int damaged_count = 0;
670 /* Unpack all subbands at all levels. */
671 for (level = 0; level < s->wavelet_depth; level++) {
672 for (orientation = !!level; orientation < 4; orientation++) {
673 SubBand *b = &s->plane[comp].band[level][orientation];
674 bands[num_bands++] = b;
676 align_get_bits(&s->gb);
677 /* [DIRAC_STD] 13.4.2 subband() */
678 b->length = get_interleaved_ue_golomb(&s->gb);
680 b->quant = get_interleaved_ue_golomb(&s->gb);
681 if (b->quant > (DIRAC_MAX_QUANT_INDEX - 1)) {
682 av_log(s->avctx, AV_LOG_ERROR, "Unsupported quant %d\n", b->quant);
684 return AVERROR_INVALIDDATA;
686 align_get_bits(&s->gb);
687 b->coeff_data = s->gb.buffer + get_bits_count(&s->gb)/8;
688 if (b->length > FFMAX(get_bits_left(&s->gb)/8, 0)) {
689 b->length = FFMAX(get_bits_left(&s->gb)/8, 0);
692 skip_bits_long(&s->gb, b->length*8);
695 /* arithmetic coding has inter-level dependencies, so we can only execute one level at a time */
697 avctx->execute(avctx, decode_subband_arith, &s->plane[comp].band[level][!!level],
698 ret + 3*level + !!level, 4-!!level, sizeof(SubBand));
700 /* golomb coding has no inter-level dependencies, so we can execute all subbands in parallel */
702 avctx->execute(avctx, decode_subband_golomb, bands, ret, num_bands, sizeof(SubBand*));
704 for (i = 0; i < s->wavelet_depth * 3 + 1; i++) {
708 if (damaged_count > (s->wavelet_depth * 3 + 1) /2)
709 return AVERROR_INVALIDDATA;
714 #define PARSE_VALUES(type, x, gb, ebits, buf1, buf2) \
715 type *buf = (type *)buf1; \
716 buf[x] = coeff_unpack_golomb(gb, qfactor, qoffset); \
717 if (get_bits_count(gb) >= ebits) \
720 buf = (type *)buf2; \
721 buf[x] = coeff_unpack_golomb(gb, qfactor, qoffset); \
722 if (get_bits_count(gb) >= ebits) \
726 static void decode_subband(DiracContext *s, GetBitContext *gb, int quant,
727 int slice_x, int slice_y, int bits_end,
728 SubBand *b1, SubBand *b2)
730 int left = b1->width * slice_x / s->num_x;
731 int right = b1->width *(slice_x+1) / s->num_x;
732 int top = b1->height * slice_y / s->num_y;
733 int bottom = b1->height *(slice_y+1) / s->num_y;
735 int qfactor, qoffset;
737 uint8_t *buf1 = b1->ibuf + top * b1->stride;
738 uint8_t *buf2 = b2 ? b2->ibuf + top * b2->stride: NULL;
741 if (quant > (DIRAC_MAX_QUANT_INDEX - 1)) {
742 av_log(s->avctx, AV_LOG_ERROR, "Unsupported quant %d\n", quant);
745 qfactor = ff_dirac_qscale_tab[quant];
746 qoffset = ff_dirac_qoffset_intra_tab[quant] + 2;
747 /* we have to constantly check for overread since the spec explicitly
748 requires this, with the meaning that all remaining coeffs are set to 0 */
749 if (get_bits_count(gb) >= bits_end)
753 for (y = top; y < bottom; y++) {
754 for (x = left; x < right; x++) {
755 PARSE_VALUES(int32_t, x, gb, bits_end, buf1, buf2);
763 for (y = top; y < bottom; y++) {
764 for (x = left; x < right; x++) {
765 PARSE_VALUES(int16_t, x, gb, bits_end, buf1, buf2);
775 * Dirac Specification ->
776 * 13.5.2 Slices. slice(sx,sy)
778 static int decode_lowdelay_slice(AVCodecContext *avctx, void *arg)
780 DiracContext *s = avctx->priv_data;
781 DiracSlice *slice = arg;
782 GetBitContext *gb = &slice->gb;
783 enum dirac_subband orientation;
784 int level, quant, chroma_bits, chroma_end;
786 int quant_base = get_bits(gb, 7); /*[DIRAC_STD] qindex */
787 int length_bits = av_log2(8 * slice->bytes)+1;
788 int luma_bits = get_bits_long(gb, length_bits);
789 int luma_end = get_bits_count(gb) + FFMIN(luma_bits, get_bits_left(gb));
791 /* [DIRAC_STD] 13.5.5.2 luma_slice_band */
792 for (level = 0; level < s->wavelet_depth; level++)
793 for (orientation = !!level; orientation < 4; orientation++) {
794 quant = FFMAX(quant_base - s->lowdelay.quant[level][orientation], 0);
795 decode_subband(s, gb, quant, slice->slice_x, slice->slice_y, luma_end,
796 &s->plane[0].band[level][orientation], NULL);
799 /* consume any unused bits from luma */
800 skip_bits_long(gb, get_bits_count(gb) - luma_end);
802 chroma_bits = 8*slice->bytes - 7 - length_bits - luma_bits;
803 chroma_end = get_bits_count(gb) + FFMIN(chroma_bits, get_bits_left(gb));
804 /* [DIRAC_STD] 13.5.5.3 chroma_slice_band */
805 for (level = 0; level < s->wavelet_depth; level++)
806 for (orientation = !!level; orientation < 4; orientation++) {
807 quant = FFMAX(quant_base - s->lowdelay.quant[level][orientation], 0);
808 decode_subband(s, gb, quant, slice->slice_x, slice->slice_y, chroma_end,
809 &s->plane[1].band[level][orientation],
810 &s->plane[2].band[level][orientation]);
816 typedef struct SliceCoeffs {
824 static int subband_coeffs(DiracContext *s, int x, int y, int p,
825 SliceCoeffs c[MAX_DWT_LEVELS])
828 for (level = 0; level < s->wavelet_depth; level++) {
829 SliceCoeffs *o = &c[level];
830 SubBand *b = &s->plane[p].band[level][3]; /* orientation doens't matter */
831 o->top = b->height * y / s->num_y;
832 o->left = b->width * x / s->num_x;
833 o->tot_h = ((b->width * (x + 1)) / s->num_x) - o->left;
834 o->tot_v = ((b->height * (y + 1)) / s->num_y) - o->top;
835 o->tot = o->tot_h*o->tot_v;
836 coef += o->tot * (4 - !!level);
842 * VC-2 Specification ->
843 * 13.5.3 hq_slice(sx,sy)
845 static int decode_hq_slice(DiracContext *s, DiracSlice *slice, uint8_t *tmp_buf)
847 int i, level, orientation, quant_idx;
848 int qfactor[MAX_DWT_LEVELS][4], qoffset[MAX_DWT_LEVELS][4];
849 GetBitContext *gb = &slice->gb;
850 SliceCoeffs coeffs_num[MAX_DWT_LEVELS];
852 skip_bits_long(gb, 8*s->highquality.prefix_bytes);
853 quant_idx = get_bits(gb, 8);
855 if (quant_idx > DIRAC_MAX_QUANT_INDEX - 1) {
856 av_log(s->avctx, AV_LOG_ERROR, "Invalid quantization index - %i\n", quant_idx);
857 return AVERROR_INVALIDDATA;
860 /* Slice quantization (slice_quantizers() in the specs) */
861 for (level = 0; level < s->wavelet_depth; level++) {
862 for (orientation = !!level; orientation < 4; orientation++) {
863 const int quant = FFMAX(quant_idx - s->lowdelay.quant[level][orientation], 0);
864 qfactor[level][orientation] = ff_dirac_qscale_tab[quant];
865 qoffset[level][orientation] = ff_dirac_qoffset_intra_tab[quant] + 2;
869 /* Luma + 2 Chroma planes */
870 for (i = 0; i < 3; i++) {
871 int coef_num, coef_par, off = 0;
872 int64_t length = s->highquality.size_scaler*get_bits(gb, 8);
873 int64_t bits_end = get_bits_count(gb) + 8*length;
874 const uint8_t *addr = align_get_bits(gb);
876 if (length*8 > get_bits_left(gb)) {
877 av_log(s->avctx, AV_LOG_ERROR, "end too far away\n");
878 return AVERROR_INVALIDDATA;
881 coef_num = subband_coeffs(s, slice->slice_x, slice->slice_y, i, coeffs_num);
884 coef_par = ff_dirac_golomb_read_32bit(s->reader_ctx, addr,
885 length, tmp_buf, coef_num);
887 coef_par = ff_dirac_golomb_read_16bit(s->reader_ctx, addr,
888 length, tmp_buf, coef_num);
890 if (coef_num > coef_par) {
891 const int start_b = coef_par * (1 << (s->pshift + 1));
892 const int end_b = coef_num * (1 << (s->pshift + 1));
893 memset(&tmp_buf[start_b], 0, end_b - start_b);
896 for (level = 0; level < s->wavelet_depth; level++) {
897 const SliceCoeffs *c = &coeffs_num[level];
898 for (orientation = !!level; orientation < 4; orientation++) {
899 const SubBand *b1 = &s->plane[i].band[level][orientation];
900 uint8_t *buf = b1->ibuf + c->top * b1->stride + (c->left << (s->pshift + 1));
902 /* Change to c->tot_h <= 4 for AVX2 dequantization */
903 const int qfunc = s->pshift + 2*(c->tot_h <= 2);
904 s->diracdsp.dequant_subband[qfunc](&tmp_buf[off], buf, b1->stride,
905 qfactor[level][orientation],
906 qoffset[level][orientation],
909 off += c->tot << (s->pshift + 1);
913 skip_bits_long(gb, bits_end - get_bits_count(gb));
919 static int decode_hq_slice_row(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
922 DiracContext *s = avctx->priv_data;
923 DiracSlice *slices = ((DiracSlice *)arg) + s->num_x*jobnr;
924 uint8_t *thread_buf = &s->thread_buf[s->thread_buf_size*threadnr];
925 for (i = 0; i < s->num_x; i++)
926 decode_hq_slice(s, &slices[i], thread_buf);
931 * Dirac Specification ->
932 * 13.5.1 low_delay_transform_data()
934 static int decode_lowdelay(DiracContext *s)
936 AVCodecContext *avctx = s->avctx;
937 int slice_x, slice_y, bufsize;
938 int64_t coef_buf_size, bytes = 0;
941 SliceCoeffs tmp[MAX_DWT_LEVELS];
944 if (s->slice_params_num_buf != (s->num_x * s->num_y)) {
945 s->slice_params_buf = av_realloc_f(s->slice_params_buf, s->num_x * s->num_y, sizeof(DiracSlice));
946 if (!s->slice_params_buf) {
947 av_log(s->avctx, AV_LOG_ERROR, "slice params buffer allocation failure\n");
948 s->slice_params_num_buf = 0;
949 return AVERROR(ENOMEM);
951 s->slice_params_num_buf = s->num_x * s->num_y;
953 slices = s->slice_params_buf;
955 /* 8 becacuse that's how much the golomb reader could overread junk data
956 * from another plane/slice at most, and 512 because SIMD */
957 coef_buf_size = subband_coeffs(s, s->num_x - 1, s->num_y - 1, 0, tmp) + 8;
958 coef_buf_size = (coef_buf_size << (1 + s->pshift)) + 512;
960 if (s->threads_num_buf != avctx->thread_count ||
961 s->thread_buf_size != coef_buf_size) {
962 s->threads_num_buf = avctx->thread_count;
963 s->thread_buf_size = coef_buf_size;
964 s->thread_buf = av_realloc_f(s->thread_buf, avctx->thread_count, s->thread_buf_size);
965 if (!s->thread_buf) {
966 av_log(s->avctx, AV_LOG_ERROR, "thread buffer allocation failure\n");
967 return AVERROR(ENOMEM);
971 align_get_bits(&s->gb);
972 /*[DIRAC_STD] 13.5.2 Slices. slice(sx,sy) */
973 buf = s->gb.buffer + get_bits_count(&s->gb)/8;
974 bufsize = get_bits_left(&s->gb);
979 for (slice_y = 0; bufsize > 0 && slice_y < s->num_y; slice_y++) {
980 for (slice_x = 0; bufsize > 0 && slice_x < s->num_x; slice_x++) {
981 bytes = s->highquality.prefix_bytes + 1;
982 for (i = 0; i < 3; i++) {
983 if (bytes <= bufsize/8)
984 bytes += buf[bytes] * s->highquality.size_scaler + 1;
986 if (bytes >= INT_MAX || bytes*8 > bufsize) {
987 av_log(s->avctx, AV_LOG_ERROR, "too many bytes\n");
988 return AVERROR_INVALIDDATA;
991 slices[slice_num].bytes = bytes;
992 slices[slice_num].slice_x = slice_x;
993 slices[slice_num].slice_y = slice_y;
994 init_get_bits(&slices[slice_num].gb, buf, bufsize);
998 if (bufsize/8 >= bytes)
1005 if (s->num_x*s->num_y != slice_num) {
1006 av_log(s->avctx, AV_LOG_ERROR, "too few slices\n");
1007 return AVERROR_INVALIDDATA;
1010 avctx->execute2(avctx, decode_hq_slice_row, slices, NULL, s->num_y);
1012 for (slice_y = 0; bufsize > 0 && slice_y < s->num_y; slice_y++) {
1013 for (slice_x = 0; bufsize > 0 && slice_x < s->num_x; slice_x++) {
1014 bytes = (slice_num+1) * (int64_t)s->lowdelay.bytes.num / s->lowdelay.bytes.den
1015 - slice_num * (int64_t)s->lowdelay.bytes.num / s->lowdelay.bytes.den;
1016 if (bytes >= INT_MAX || bytes*8 > bufsize) {
1017 av_log(s->avctx, AV_LOG_ERROR, "too many bytes\n");
1018 return AVERROR_INVALIDDATA;
1020 slices[slice_num].bytes = bytes;
1021 slices[slice_num].slice_x = slice_x;
1022 slices[slice_num].slice_y = slice_y;
1023 init_get_bits(&slices[slice_num].gb, buf, bufsize);
1027 if (bufsize/8 >= bytes)
1033 avctx->execute(avctx, decode_lowdelay_slice, slices, NULL, slice_num,
1034 sizeof(DiracSlice)); /* [DIRAC_STD] 13.5.2 Slices */
1037 if (s->dc_prediction) {
1039 intra_dc_prediction_10(&s->plane[0].band[0][0]); /* [DIRAC_STD] 13.3 intra_dc_prediction() */
1040 intra_dc_prediction_10(&s->plane[1].band[0][0]); /* [DIRAC_STD] 13.3 intra_dc_prediction() */
1041 intra_dc_prediction_10(&s->plane[2].band[0][0]); /* [DIRAC_STD] 13.3 intra_dc_prediction() */
1043 intra_dc_prediction_8(&s->plane[0].band[0][0]);
1044 intra_dc_prediction_8(&s->plane[1].band[0][0]);
1045 intra_dc_prediction_8(&s->plane[2].band[0][0]);
1052 static void init_planes(DiracContext *s)
1054 int i, w, h, level, orientation;
1056 for (i = 0; i < 3; i++) {
1057 Plane *p = &s->plane[i];
1059 p->width = s->seq.width >> (i ? s->chroma_x_shift : 0);
1060 p->height = s->seq.height >> (i ? s->chroma_y_shift : 0);
1061 p->idwt.width = w = CALC_PADDING(p->width , s->wavelet_depth);
1062 p->idwt.height = h = CALC_PADDING(p->height, s->wavelet_depth);
1063 p->idwt.stride = FFALIGN(p->idwt.width, 8) << (1 + s->pshift);
1065 for (level = s->wavelet_depth-1; level >= 0; level--) {
1068 for (orientation = !!level; orientation < 4; orientation++) {
1069 SubBand *b = &p->band[level][orientation];
1071 b->pshift = s->pshift;
1072 b->ibuf = p->idwt.buf;
1074 b->stride = p->idwt.stride << (s->wavelet_depth - level);
1077 b->orientation = orientation;
1079 if (orientation & 1)
1080 b->ibuf += w << (1+b->pshift);
1081 if (orientation > 1)
1082 b->ibuf += (b->stride>>1);
1085 b->parent = &p->band[level-1][orientation];
1090 p->xblen = s->plane[0].xblen >> s->chroma_x_shift;
1091 p->yblen = s->plane[0].yblen >> s->chroma_y_shift;
1092 p->xbsep = s->plane[0].xbsep >> s->chroma_x_shift;
1093 p->ybsep = s->plane[0].ybsep >> s->chroma_y_shift;
1096 p->xoffset = (p->xblen - p->xbsep)/2;
1097 p->yoffset = (p->yblen - p->ybsep)/2;
1102 * Unpack the motion compensation parameters
1103 * Dirac Specification ->
1104 * 11.2 Picture prediction data. picture_prediction()
1106 static int dirac_unpack_prediction_parameters(DiracContext *s)
1108 static const uint8_t default_blen[] = { 4, 12, 16, 24 };
1110 GetBitContext *gb = &s->gb;
1114 /* [DIRAC_STD] 11.2.2 Block parameters. block_parameters() */
1115 /* Luma and Chroma are equal. 11.2.3 */
1116 idx = get_interleaved_ue_golomb(gb); /* [DIRAC_STD] index */
1119 av_log(s->avctx, AV_LOG_ERROR, "Block prediction index too high\n");
1120 return AVERROR_INVALIDDATA;
1124 s->plane[0].xblen = get_interleaved_ue_golomb(gb);
1125 s->plane[0].yblen = get_interleaved_ue_golomb(gb);
1126 s->plane[0].xbsep = get_interleaved_ue_golomb(gb);
1127 s->plane[0].ybsep = get_interleaved_ue_golomb(gb);
1129 /*[DIRAC_STD] preset_block_params(index). Table 11.1 */
1130 s->plane[0].xblen = default_blen[idx-1];
1131 s->plane[0].yblen = default_blen[idx-1];
1132 s->plane[0].xbsep = 4 * idx;
1133 s->plane[0].ybsep = 4 * idx;
1135 /*[DIRAC_STD] 11.2.4 motion_data_dimensions()
1136 Calculated in function dirac_unpack_block_motion_data */
1138 if (s->plane[0].xblen % (1 << s->chroma_x_shift) != 0 ||
1139 s->plane[0].yblen % (1 << s->chroma_y_shift) != 0 ||
1140 !s->plane[0].xblen || !s->plane[0].yblen) {
1141 av_log(s->avctx, AV_LOG_ERROR,
1142 "invalid x/y block length (%d/%d) for x/y chroma shift (%d/%d)\n",
1143 s->plane[0].xblen, s->plane[0].yblen, s->chroma_x_shift, s->chroma_y_shift);
1144 return AVERROR_INVALIDDATA;
1146 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) {
1147 av_log(s->avctx, AV_LOG_ERROR, "Block separation too small\n");
1148 return AVERROR_INVALIDDATA;
1150 if (s->plane[0].xbsep > s->plane[0].xblen || s->plane[0].ybsep > s->plane[0].yblen) {
1151 av_log(s->avctx, AV_LOG_ERROR, "Block separation greater than size\n");
1152 return AVERROR_INVALIDDATA;
1154 if (FFMAX(s->plane[0].xblen, s->plane[0].yblen) > MAX_BLOCKSIZE) {
1155 av_log(s->avctx, AV_LOG_ERROR, "Unsupported large block size\n");
1156 return AVERROR_PATCHWELCOME;
1159 /*[DIRAC_STD] 11.2.5 Motion vector precision. motion_vector_precision()
1160 Read motion vector precision */
1161 s->mv_precision = get_interleaved_ue_golomb(gb);
1162 if (s->mv_precision > 3) {
1163 av_log(s->avctx, AV_LOG_ERROR, "MV precision finer than eighth-pel\n");
1164 return AVERROR_INVALIDDATA;
1167 /*[DIRAC_STD] 11.2.6 Global motion. global_motion()
1168 Read the global motion compensation parameters */
1169 s->globalmc_flag = get_bits1(gb);
1170 if (s->globalmc_flag) {
1171 memset(s->globalmc, 0, sizeof(s->globalmc));
1172 /* [DIRAC_STD] pan_tilt(gparams) */
1173 for (ref = 0; ref < s->num_refs; ref++) {
1174 if (get_bits1(gb)) {
1175 s->globalmc[ref].pan_tilt[0] = dirac_get_se_golomb(gb);
1176 s->globalmc[ref].pan_tilt[1] = dirac_get_se_golomb(gb);
1178 /* [DIRAC_STD] zoom_rotate_shear(gparams)
1179 zoom/rotation/shear parameters */
1180 if (get_bits1(gb)) {
1181 s->globalmc[ref].zrs_exp = get_interleaved_ue_golomb(gb);
1182 s->globalmc[ref].zrs[0][0] = dirac_get_se_golomb(gb);
1183 s->globalmc[ref].zrs[0][1] = dirac_get_se_golomb(gb);
1184 s->globalmc[ref].zrs[1][0] = dirac_get_se_golomb(gb);
1185 s->globalmc[ref].zrs[1][1] = dirac_get_se_golomb(gb);
1187 s->globalmc[ref].zrs[0][0] = 1;
1188 s->globalmc[ref].zrs[1][1] = 1;
1190 /* [DIRAC_STD] perspective(gparams) */
1191 if (get_bits1(gb)) {
1192 s->globalmc[ref].perspective_exp = get_interleaved_ue_golomb(gb);
1193 s->globalmc[ref].perspective[0] = dirac_get_se_golomb(gb);
1194 s->globalmc[ref].perspective[1] = dirac_get_se_golomb(gb);
1196 if (s->globalmc[ref].perspective_exp + (uint64_t)s->globalmc[ref].zrs_exp > 30) {
1197 return AVERROR_INVALIDDATA;
1203 /*[DIRAC_STD] 11.2.7 Picture prediction mode. prediction_mode()
1204 Picture prediction mode, not currently used. */
1205 if (get_interleaved_ue_golomb(gb)) {
1206 av_log(s->avctx, AV_LOG_ERROR, "Unknown picture prediction mode\n");
1207 return AVERROR_INVALIDDATA;
1210 /* [DIRAC_STD] 11.2.8 Reference picture weight. reference_picture_weights()
1211 just data read, weight calculation will be done later on. */
1212 s->weight_log2denom = 1;
1216 if (get_bits1(gb)) {
1217 s->weight_log2denom = get_interleaved_ue_golomb(gb);
1218 if (s->weight_log2denom < 1 || s->weight_log2denom > 8) {
1219 av_log(s->avctx, AV_LOG_ERROR, "weight_log2denom unsupported or invalid\n");
1220 s->weight_log2denom = 1;
1221 return AVERROR_INVALIDDATA;
1223 s->weight[0] = dirac_get_se_golomb(gb);
1224 if (s->num_refs == 2)
1225 s->weight[1] = dirac_get_se_golomb(gb);
1231 * Dirac Specification ->
1232 * 11.3 Wavelet transform data. wavelet_transform()
1234 static int dirac_unpack_idwt_params(DiracContext *s)
1236 GetBitContext *gb = &s->gb;
1240 #define CHECKEDREAD(dst, cond, errmsg) \
1241 tmp = get_interleaved_ue_golomb(gb); \
1243 av_log(s->avctx, AV_LOG_ERROR, errmsg); \
1244 return AVERROR_INVALIDDATA; \
1250 s->zero_res = s->num_refs ? get_bits1(gb) : 0;
1254 /*[DIRAC_STD] 11.3.1 Transform parameters. transform_parameters() */
1255 CHECKEDREAD(s->wavelet_idx, tmp > 6, "wavelet_idx is too big\n")
1257 CHECKEDREAD(s->wavelet_depth, tmp > MAX_DWT_LEVELS || tmp < 1, "invalid number of DWT decompositions\n")
1259 if (!s->low_delay) {
1260 /* Codeblock parameters (core syntax only) */
1261 if (get_bits1(gb)) {
1262 for (i = 0; i <= s->wavelet_depth; i++) {
1263 CHECKEDREAD(s->codeblock[i].width , tmp < 1 || tmp > (s->avctx->width >>s->wavelet_depth-i), "codeblock width invalid\n")
1264 CHECKEDREAD(s->codeblock[i].height, tmp < 1 || tmp > (s->avctx->height>>s->wavelet_depth-i), "codeblock height invalid\n")
1267 CHECKEDREAD(s->codeblock_mode, tmp > 1, "unknown codeblock mode\n")
1270 for (i = 0; i <= s->wavelet_depth; i++)
1271 s->codeblock[i].width = s->codeblock[i].height = 1;
1275 s->num_x = get_interleaved_ue_golomb(gb);
1276 s->num_y = get_interleaved_ue_golomb(gb);
1277 if (s->num_x * s->num_y == 0 || s->num_x * (uint64_t)s->num_y > INT_MAX ||
1278 s->num_x * (uint64_t)s->avctx->width > INT_MAX ||
1279 s->num_y * (uint64_t)s->avctx->height > INT_MAX
1281 av_log(s->avctx,AV_LOG_ERROR,"Invalid numx/y\n");
1282 s->num_x = s->num_y = 0;
1283 return AVERROR_INVALIDDATA;
1285 if (s->ld_picture) {
1286 s->lowdelay.bytes.num = get_interleaved_ue_golomb(gb);
1287 s->lowdelay.bytes.den = get_interleaved_ue_golomb(gb);
1288 if (s->lowdelay.bytes.den <= 0) {
1289 av_log(s->avctx,AV_LOG_ERROR,"Invalid lowdelay.bytes.den\n");
1290 return AVERROR_INVALIDDATA;
1292 } else if (s->hq_picture) {
1293 s->highquality.prefix_bytes = get_interleaved_ue_golomb(gb);
1294 s->highquality.size_scaler = get_interleaved_ue_golomb(gb);
1295 if (s->highquality.prefix_bytes >= INT_MAX / 8) {
1296 av_log(s->avctx,AV_LOG_ERROR,"too many prefix bytes\n");
1297 return AVERROR_INVALIDDATA;
1301 /* [DIRAC_STD] 11.3.5 Quantisation matrices (low-delay syntax). quant_matrix() */
1302 if (get_bits1(gb)) {
1303 av_log(s->avctx,AV_LOG_DEBUG,"Low Delay: Has Custom Quantization Matrix!\n");
1304 /* custom quantization matrix */
1305 for (level = 0; level < s->wavelet_depth; level++) {
1306 for (i = !!level; i < 4; i++) {
1307 s->lowdelay.quant[level][i] = get_interleaved_ue_golomb(gb);
1311 if (s->wavelet_depth > 4) {
1312 av_log(s->avctx,AV_LOG_ERROR,"Mandatory custom low delay matrix missing for depth %d\n", s->wavelet_depth);
1313 return AVERROR_INVALIDDATA;
1315 /* default quantization matrix */
1316 for (level = 0; level < s->wavelet_depth; level++)
1317 for (i = 0; i < 4; i++) {
1318 s->lowdelay.quant[level][i] = ff_dirac_default_qmat[s->wavelet_idx][level][i];
1319 /* haar with no shift differs for different depths */
1320 if (s->wavelet_idx == 3)
1321 s->lowdelay.quant[level][i] += 4*(s->wavelet_depth-1 - level);
1328 static inline int pred_sbsplit(uint8_t *sbsplit, int stride, int x, int y)
1330 static const uint8_t avgsplit[7] = { 0, 0, 1, 1, 1, 2, 2 };
1337 return sbsplit[-stride];
1339 return avgsplit[sbsplit[-1] + sbsplit[-stride] + sbsplit[-stride-1]];
1342 static inline int pred_block_mode(DiracBlock *block, int stride, int x, int y, int refmask)
1349 return block[-1].ref & refmask;
1351 return block[-stride].ref & refmask;
1353 /* return the majority */
1354 pred = (block[-1].ref & refmask) + (block[-stride].ref & refmask) + (block[-stride-1].ref & refmask);
1355 return (pred >> 1) & refmask;
1358 static inline void pred_block_dc(DiracBlock *block, int stride, int x, int y)
1362 memset(block->u.dc, 0, sizeof(block->u.dc));
1364 if (x && !(block[-1].ref & 3)) {
1365 for (i = 0; i < 3; i++)
1366 block->u.dc[i] += block[-1].u.dc[i];
1370 if (y && !(block[-stride].ref & 3)) {
1371 for (i = 0; i < 3; i++)
1372 block->u.dc[i] += block[-stride].u.dc[i];
1376 if (x && y && !(block[-1-stride].ref & 3)) {
1377 for (i = 0; i < 3; i++)
1378 block->u.dc[i] += block[-1-stride].u.dc[i];
1383 for (i = 0; i < 3; i++)
1384 block->u.dc[i] = (block->u.dc[i]+1)>>1;
1385 } else if (n == 3) {
1386 for (i = 0; i < 3; i++)
1387 block->u.dc[i] = divide3(block->u.dc[i]);
1391 static inline void pred_mv(DiracBlock *block, int stride, int x, int y, int ref)
1394 int refmask = ref+1;
1395 int mask = refmask | DIRAC_REF_MASK_GLOBAL; /* exclude gmc blocks */
1398 if (x && (block[-1].ref & mask) == refmask)
1399 pred[n++] = block[-1].u.mv[ref];
1401 if (y && (block[-stride].ref & mask) == refmask)
1402 pred[n++] = block[-stride].u.mv[ref];
1404 if (x && y && (block[-stride-1].ref & mask) == refmask)
1405 pred[n++] = block[-stride-1].u.mv[ref];
1409 block->u.mv[ref][0] = 0;
1410 block->u.mv[ref][1] = 0;
1413 block->u.mv[ref][0] = pred[0][0];
1414 block->u.mv[ref][1] = pred[0][1];
1417 block->u.mv[ref][0] = (pred[0][0] + pred[1][0] + 1) >> 1;
1418 block->u.mv[ref][1] = (pred[0][1] + pred[1][1] + 1) >> 1;
1421 block->u.mv[ref][0] = mid_pred(pred[0][0], pred[1][0], pred[2][0]);
1422 block->u.mv[ref][1] = mid_pred(pred[0][1], pred[1][1], pred[2][1]);
1427 static void global_mv(DiracContext *s, DiracBlock *block, int x, int y, int ref)
1429 int ez = s->globalmc[ref].zrs_exp;
1430 int ep = s->globalmc[ref].perspective_exp;
1431 int (*A)[2] = s->globalmc[ref].zrs;
1432 int *b = s->globalmc[ref].pan_tilt;
1433 int *c = s->globalmc[ref].perspective;
1435 int64_t m = (1<<ep) - (c[0]*(int64_t)x + c[1]*(int64_t)y);
1436 int64_t mx = m * (int64_t)((A[0][0] * (int64_t)x + A[0][1]*(int64_t)y) + (1<<ez) * b[0]);
1437 int64_t my = m * (int64_t)((A[1][0] * (int64_t)x + A[1][1]*(int64_t)y) + (1<<ez) * b[1]);
1439 block->u.mv[ref][0] = (mx + (1<<(ez+ep))) >> (ez+ep);
1440 block->u.mv[ref][1] = (my + (1<<(ez+ep))) >> (ez+ep);
1443 static void decode_block_params(DiracContext *s, DiracArith arith[8], DiracBlock *block,
1444 int stride, int x, int y)
1448 block->ref = pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_REF1);
1449 block->ref ^= dirac_get_arith_bit(arith, CTX_PMODE_REF1);
1451 if (s->num_refs == 2) {
1452 block->ref |= pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_REF2);
1453 block->ref ^= dirac_get_arith_bit(arith, CTX_PMODE_REF2) << 1;
1457 pred_block_dc(block, stride, x, y);
1458 for (i = 0; i < 3; i++)
1459 block->u.dc[i] += (unsigned)dirac_get_arith_int(arith+1+i, CTX_DC_F1, CTX_DC_DATA);
1463 if (s->globalmc_flag) {
1464 block->ref |= pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_GLOBAL);
1465 block->ref ^= dirac_get_arith_bit(arith, CTX_GLOBAL_BLOCK) << 2;
1468 for (i = 0; i < s->num_refs; i++)
1469 if (block->ref & (i+1)) {
1470 if (block->ref & DIRAC_REF_MASK_GLOBAL) {
1471 global_mv(s, block, x, y, i);
1473 pred_mv(block, stride, x, y, i);
1474 block->u.mv[i][0] += (unsigned)dirac_get_arith_int(arith + 4 + 2 * i, CTX_MV_F1, CTX_MV_DATA);
1475 block->u.mv[i][1] += (unsigned)dirac_get_arith_int(arith + 5 + 2 * i, CTX_MV_F1, CTX_MV_DATA);
1481 * Copies the current block to the other blocks covered by the current superblock split mode
1483 static void propagate_block_data(DiracBlock *block, int stride, int size)
1486 DiracBlock *dst = block;
1488 for (x = 1; x < size; x++)
1491 for (y = 1; y < size; y++) {
1493 for (x = 0; x < size; x++)
1499 * Dirac Specification ->
1500 * 12. Block motion data syntax
1502 static int dirac_unpack_block_motion_data(DiracContext *s)
1504 GetBitContext *gb = &s->gb;
1505 uint8_t *sbsplit = s->sbsplit;
1507 DiracArith arith[8];
1511 /* [DIRAC_STD] 11.2.4 and 12.2.1 Number of blocks and superblocks */
1512 s->sbwidth = DIVRNDUP(s->seq.width, 4*s->plane[0].xbsep);
1513 s->sbheight = DIVRNDUP(s->seq.height, 4*s->plane[0].ybsep);
1514 s->blwidth = 4 * s->sbwidth;
1515 s->blheight = 4 * s->sbheight;
1517 /* [DIRAC_STD] 12.3.1 Superblock splitting modes. superblock_split_modes()
1518 decode superblock split modes */
1519 ff_dirac_init_arith_decoder(arith, gb, get_interleaved_ue_golomb(gb)); /* get_interleaved_ue_golomb(gb) is the length */
1520 for (y = 0; y < s->sbheight; y++) {
1521 for (x = 0; x < s->sbwidth; x++) {
1522 unsigned int split = dirac_get_arith_uint(arith, CTX_SB_F1, CTX_SB_DATA);
1524 return AVERROR_INVALIDDATA;
1525 sbsplit[x] = (split + pred_sbsplit(sbsplit+x, s->sbwidth, x, y)) % 3;
1527 sbsplit += s->sbwidth;
1530 /* setup arith decoding */
1531 ff_dirac_init_arith_decoder(arith, gb, get_interleaved_ue_golomb(gb));
1532 for (i = 0; i < s->num_refs; i++) {
1533 ff_dirac_init_arith_decoder(arith + 4 + 2 * i, gb, get_interleaved_ue_golomb(gb));
1534 ff_dirac_init_arith_decoder(arith + 5 + 2 * i, gb, get_interleaved_ue_golomb(gb));
1536 for (i = 0; i < 3; i++)
1537 ff_dirac_init_arith_decoder(arith+1+i, gb, get_interleaved_ue_golomb(gb));
1539 for (y = 0; y < s->sbheight; y++)
1540 for (x = 0; x < s->sbwidth; x++) {
1541 int blkcnt = 1 << s->sbsplit[y * s->sbwidth + x];
1542 int step = 4 >> s->sbsplit[y * s->sbwidth + x];
1544 for (q = 0; q < blkcnt; q++)
1545 for (p = 0; p < blkcnt; p++) {
1546 int bx = 4 * x + p*step;
1547 int by = 4 * y + q*step;
1548 DiracBlock *block = &s->blmotion[by*s->blwidth + bx];
1549 decode_block_params(s, arith, block, s->blwidth, bx, by);
1550 propagate_block_data(block, s->blwidth, step);
1557 static int weight(int i, int blen, int offset)
1559 #define ROLLOFF(i) offset == 1 ? ((i) ? 5 : 3) : \
1560 (1 + (6*(i) + offset - 1) / (2*offset - 1))
1564 else if (i > blen-1 - 2*offset)
1565 return ROLLOFF(blen-1 - i);
1569 static void init_obmc_weight_row(Plane *p, uint8_t *obmc_weight, int stride,
1570 int left, int right, int wy)
1573 for (x = 0; left && x < p->xblen >> 1; x++)
1574 obmc_weight[x] = wy*8;
1575 for (; x < p->xblen >> right; x++)
1576 obmc_weight[x] = wy*weight(x, p->xblen, p->xoffset);
1577 for (; x < p->xblen; x++)
1578 obmc_weight[x] = wy*8;
1579 for (; x < stride; x++)
1583 static void init_obmc_weight(Plane *p, uint8_t *obmc_weight, int stride,
1584 int left, int right, int top, int bottom)
1587 for (y = 0; top && y < p->yblen >> 1; y++) {
1588 init_obmc_weight_row(p, obmc_weight, stride, left, right, 8);
1589 obmc_weight += stride;
1591 for (; y < p->yblen >> bottom; y++) {
1592 int wy = weight(y, p->yblen, p->yoffset);
1593 init_obmc_weight_row(p, obmc_weight, stride, left, right, wy);
1594 obmc_weight += stride;
1596 for (; y < p->yblen; y++) {
1597 init_obmc_weight_row(p, obmc_weight, stride, left, right, 8);
1598 obmc_weight += stride;
1602 static void init_obmc_weights(DiracContext *s, Plane *p, int by)
1605 int bottom = by == s->blheight-1;
1607 /* don't bother re-initing for rows 2 to blheight-2, the weights don't change */
1608 if (top || bottom || by == 1) {
1609 init_obmc_weight(p, s->obmc_weight[0], MAX_BLOCKSIZE, 1, 0, top, bottom);
1610 init_obmc_weight(p, s->obmc_weight[1], MAX_BLOCKSIZE, 0, 0, top, bottom);
1611 init_obmc_weight(p, s->obmc_weight[2], MAX_BLOCKSIZE, 0, 1, top, bottom);
1615 static const uint8_t epel_weights[4][4][4] = {
1635 * For block x,y, determine which of the hpel planes to do bilinear
1636 * interpolation from and set src[] to the location in each hpel plane
1639 * @return the index of the put_dirac_pixels_tab function to use
1640 * 0 for 1 plane (fpel,hpel), 1 for 2 planes (qpel), 2 for 4 planes (qpel), and 3 for epel
1642 static int mc_subpel(DiracContext *s, DiracBlock *block, const uint8_t *src[5],
1643 int x, int y, int ref, int plane)
1645 Plane *p = &s->plane[plane];
1646 uint8_t **ref_hpel = s->ref_pics[ref]->hpel[plane];
1647 int motion_x = block->u.mv[ref][0];
1648 int motion_y = block->u.mv[ref][1];
1649 int mx, my, i, epel, nplanes = 0;
1652 motion_x >>= s->chroma_x_shift;
1653 motion_y >>= s->chroma_y_shift;
1656 mx = motion_x & ~(-1U << s->mv_precision);
1657 my = motion_y & ~(-1U << s->mv_precision);
1658 motion_x >>= s->mv_precision;
1659 motion_y >>= s->mv_precision;
1660 /* normalize subpel coordinates to epel */
1661 /* TODO: template this function? */
1662 mx <<= 3 - s->mv_precision;
1663 my <<= 3 - s->mv_precision;
1672 src[0] = ref_hpel[(my>>1)+(mx>>2)] + y*p->stride + x;
1676 for (i = 0; i < 4; i++)
1677 src[i] = ref_hpel[i] + y*p->stride + x;
1679 /* if we're interpolating in the right/bottom halves, adjust the planes as needed
1680 we increment x/y because the edge changes for half of the pixels */
1687 src[0] += p->stride;
1688 src[1] += p->stride;
1696 /* check if we really only need 2 planes since either mx or my is
1697 a hpel position. (epel weights of 0 handle this there) */
1699 /* mx == 0: average [0] and [2]
1700 mx == 4: average [1] and [3] */
1701 src[!mx] = src[2 + !!mx];
1703 } else if (!(my&3)) {
1704 src[0] = src[(my>>1) ];
1705 src[1] = src[(my>>1)+1];
1709 /* adjust the ordering if needed so the weights work */
1711 FFSWAP(const uint8_t *, src[0], src[1]);
1712 FFSWAP(const uint8_t *, src[2], src[3]);
1715 FFSWAP(const uint8_t *, src[0], src[2]);
1716 FFSWAP(const uint8_t *, src[1], src[3]);
1718 src[4] = epel_weights[my&3][mx&3];
1722 /* fixme: v/h _edge_pos */
1723 if (x + p->xblen > p->width +EDGE_WIDTH/2 ||
1724 y + p->yblen > p->height+EDGE_WIDTH/2 ||
1726 for (i = 0; i < nplanes; i++) {
1727 s->vdsp.emulated_edge_mc(s->edge_emu_buffer[i], src[i],
1728 p->stride, p->stride,
1729 p->xblen, p->yblen, x, y,
1730 p->width+EDGE_WIDTH/2, p->height+EDGE_WIDTH/2);
1731 src[i] = s->edge_emu_buffer[i];
1734 return (nplanes>>1) + epel;
1737 static void add_dc(uint16_t *dst, int dc, int stride,
1738 uint8_t *obmc_weight, int xblen, int yblen)
1743 for (y = 0; y < yblen; y++) {
1744 for (x = 0; x < xblen; x += 2) {
1745 dst[x ] += dc * obmc_weight[x ];
1746 dst[x+1] += dc * obmc_weight[x+1];
1749 obmc_weight += MAX_BLOCKSIZE;
1753 static void block_mc(DiracContext *s, DiracBlock *block,
1754 uint16_t *mctmp, uint8_t *obmc_weight,
1755 int plane, int dstx, int dsty)
1757 Plane *p = &s->plane[plane];
1758 const uint8_t *src[5];
1761 switch (block->ref&3) {
1763 add_dc(mctmp, block->u.dc[plane], p->stride, obmc_weight, p->xblen, p->yblen);
1767 idx = mc_subpel(s, block, src, dstx, dsty, (block->ref&3)-1, plane);
1768 s->put_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen);
1770 s->weight_func(s->mcscratch, p->stride, s->weight_log2denom,
1771 s->weight[0] + s->weight[1], p->yblen);
1774 idx = mc_subpel(s, block, src, dstx, dsty, 0, plane);
1775 s->put_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen);
1776 idx = mc_subpel(s, block, src, dstx, dsty, 1, plane);
1777 if (s->biweight_func) {
1778 /* fixme: +32 is a quick hack */
1779 s->put_pixels_tab[idx](s->mcscratch + 32, src, p->stride, p->yblen);
1780 s->biweight_func(s->mcscratch, s->mcscratch+32, p->stride, s->weight_log2denom,
1781 s->weight[0], s->weight[1], p->yblen);
1783 s->avg_pixels_tab[idx](s->mcscratch, src, p->stride, p->yblen);
1786 s->add_obmc(mctmp, s->mcscratch, p->stride, obmc_weight, p->yblen);
1789 static void mc_row(DiracContext *s, DiracBlock *block, uint16_t *mctmp, int plane, int dsty)
1791 Plane *p = &s->plane[plane];
1792 int x, dstx = p->xbsep - p->xoffset;
1794 block_mc(s, block, mctmp, s->obmc_weight[0], plane, -p->xoffset, dsty);
1797 for (x = 1; x < s->blwidth-1; x++) {
1798 block_mc(s, block+x, mctmp, s->obmc_weight[1], plane, dstx, dsty);
1802 block_mc(s, block+x, mctmp, s->obmc_weight[2], plane, dstx, dsty);
1805 static void select_dsp_funcs(DiracContext *s, int width, int height, int xblen, int yblen)
1813 memcpy(s->put_pixels_tab, s->diracdsp.put_dirac_pixels_tab[idx], sizeof(s->put_pixels_tab));
1814 memcpy(s->avg_pixels_tab, s->diracdsp.avg_dirac_pixels_tab[idx], sizeof(s->avg_pixels_tab));
1815 s->add_obmc = s->diracdsp.add_dirac_obmc[idx];
1816 if (s->weight_log2denom > 1 || s->weight[0] != 1 || s->weight[1] != 1) {
1817 s->weight_func = s->diracdsp.weight_dirac_pixels_tab[idx];
1818 s->biweight_func = s->diracdsp.biweight_dirac_pixels_tab[idx];
1820 s->weight_func = NULL;
1821 s->biweight_func = NULL;
1825 static int interpolate_refplane(DiracContext *s, DiracFrame *ref, int plane, int width, int height)
1827 /* chroma allocates an edge of 8 when subsampled
1828 which for 4:2:2 means an h edge of 16 and v edge of 8
1829 just use 8 for everything for the moment */
1830 int i, edge = EDGE_WIDTH/2;
1832 ref->hpel[plane][0] = ref->avframe->data[plane];
1833 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 */
1835 /* no need for hpel if we only have fpel vectors */
1836 if (!s->mv_precision)
1839 for (i = 1; i < 4; i++) {
1840 if (!ref->hpel_base[plane][i])
1841 ref->hpel_base[plane][i] = av_malloc((height+2*edge) * ref->avframe->linesize[plane] + 32);
1842 if (!ref->hpel_base[plane][i]) {
1843 return AVERROR(ENOMEM);
1845 /* we need to be 16-byte aligned even for chroma */
1846 ref->hpel[plane][i] = ref->hpel_base[plane][i] + edge*ref->avframe->linesize[plane] + 16;
1849 if (!ref->interpolated[plane]) {
1850 s->diracdsp.dirac_hpel_filter(ref->hpel[plane][1], ref->hpel[plane][2],
1851 ref->hpel[plane][3], ref->hpel[plane][0],
1852 ref->avframe->linesize[plane], width, height);
1853 s->mpvencdsp.draw_edges(ref->hpel[plane][1], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);
1854 s->mpvencdsp.draw_edges(ref->hpel[plane][2], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);
1855 s->mpvencdsp.draw_edges(ref->hpel[plane][3], ref->avframe->linesize[plane], width, height, edge, edge, EDGE_TOP | EDGE_BOTTOM);
1857 ref->interpolated[plane] = 1;
1863 * Dirac Specification ->
1864 * 13.0 Transform data syntax. transform_data()
1866 static int dirac_decode_frame_internal(DiracContext *s)
1869 int y, i, comp, dsty;
1873 /* [DIRAC_STD] 13.5.1 low_delay_transform_data() */
1874 if (!s->hq_picture) {
1875 for (comp = 0; comp < 3; comp++) {
1876 Plane *p = &s->plane[comp];
1877 memset(p->idwt.buf, 0, p->idwt.stride * p->idwt.height);
1881 if ((ret = decode_lowdelay(s)) < 0)
1886 for (comp = 0; comp < 3; comp++) {
1887 Plane *p = &s->plane[comp];
1888 uint8_t *frame = s->current_picture->avframe->data[comp];
1890 /* FIXME: small resolutions */
1891 for (i = 0; i < 4; i++)
1892 s->edge_emu_buffer[i] = s->edge_emu_buffer_base + i*FFALIGN(p->width, 16);
1894 if (!s->zero_res && !s->low_delay)
1896 memset(p->idwt.buf, 0, p->idwt.stride * p->idwt.height);
1897 ret = decode_component(s, comp); /* [DIRAC_STD] 13.4.1 core_transform_data() */
1901 ret = ff_spatial_idwt_init(&d, &p->idwt, s->wavelet_idx+2,
1902 s->wavelet_depth, s->bit_depth);
1906 if (!s->num_refs) { /* intra */
1907 for (y = 0; y < p->height; y += 16) {
1908 int idx = (s->bit_depth - 8) >> 1;
1909 ff_spatial_idwt_slice2(&d, y+16); /* decode */
1910 s->diracdsp.put_signed_rect_clamped[idx](frame + y*p->stride,
1912 p->idwt.buf + y*p->idwt.stride,
1913 p->idwt.stride, p->width, 16);
1915 } else { /* inter */
1916 int rowheight = p->ybsep*p->stride;
1918 select_dsp_funcs(s, p->width, p->height, p->xblen, p->yblen);
1920 for (i = 0; i < s->num_refs; i++) {
1921 int ret = interpolate_refplane(s, s->ref_pics[i], comp, p->width, p->height);
1926 memset(s->mctmp, 0, 4*p->yoffset*p->stride);
1929 for (y = 0; y < s->blheight; y++) {
1931 start = FFMAX(dsty, 0);
1932 uint16_t *mctmp = s->mctmp + y*rowheight;
1933 DiracBlock *blocks = s->blmotion + y*s->blwidth;
1935 init_obmc_weights(s, p, y);
1937 if (y == s->blheight-1 || start+p->ybsep > p->height)
1938 h = p->height - start;
1940 h = p->ybsep - (start - dsty);
1944 memset(mctmp+2*p->yoffset*p->stride, 0, 2*rowheight);
1945 mc_row(s, blocks, mctmp, comp, dsty);
1947 mctmp += (start - dsty)*p->stride + p->xoffset;
1948 ff_spatial_idwt_slice2(&d, start + h); /* decode */
1949 /* NOTE: add_rect_clamped hasn't been templated hence the shifts.
1950 * idwt.stride is passed as pixels, not in bytes as in the rest of the decoder */
1951 s->diracdsp.add_rect_clamped(frame + start*p->stride, mctmp, p->stride,
1952 (int16_t*)(p->idwt.buf) + start*(p->idwt.stride >> 1), (p->idwt.stride >> 1), p->width, h);
1963 static int get_buffer_with_edge(AVCodecContext *avctx, AVFrame *f, int flags)
1966 int chroma_x_shift, chroma_y_shift;
1967 ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &chroma_x_shift,
1972 f->width = avctx->width + 2 * EDGE_WIDTH;
1973 f->height = avctx->height + 2 * EDGE_WIDTH + 2;
1974 ret = ff_get_buffer(avctx, f, flags);
1978 for (i = 0; f->data[i]; i++) {
1979 int offset = (EDGE_WIDTH >> (i && i<3 ? chroma_y_shift : 0)) *
1980 f->linesize[i] + 32;
1981 f->data[i] += offset;
1983 f->width = avctx->width;
1984 f->height = avctx->height;
1990 * Dirac Specification ->
1991 * 11.1.1 Picture Header. picture_header()
1993 static int dirac_decode_picture_header(DiracContext *s)
1995 unsigned retire, picnum;
1997 int64_t refdist, refnum;
1998 GetBitContext *gb = &s->gb;
2000 /* [DIRAC_STD] 11.1.1 Picture Header. picture_header() PICTURE_NUM */
2001 picnum = s->current_picture->avframe->display_picture_number = get_bits_long(gb, 32);
2004 av_log(s->avctx,AV_LOG_DEBUG,"PICTURE_NUM: %d\n",picnum);
2006 /* if this is the first keyframe after a sequence header, start our
2007 reordering from here */
2008 if (s->frame_number < 0)
2009 s->frame_number = picnum;
2011 s->ref_pics[0] = s->ref_pics[1] = NULL;
2012 for (i = 0; i < s->num_refs; i++) {
2013 refnum = (picnum + dirac_get_se_golomb(gb)) & 0xFFFFFFFF;
2014 refdist = INT64_MAX;
2016 /* find the closest reference to the one we want */
2017 /* Jordi: this is needed if the referenced picture hasn't yet arrived */
2018 for (j = 0; j < MAX_REFERENCE_FRAMES && refdist; j++)
2019 if (s->ref_frames[j]
2020 && FFABS(s->ref_frames[j]->avframe->display_picture_number - refnum) < refdist) {
2021 s->ref_pics[i] = s->ref_frames[j];
2022 refdist = FFABS(s->ref_frames[j]->avframe->display_picture_number - refnum);
2025 if (!s->ref_pics[i] || refdist)
2026 av_log(s->avctx, AV_LOG_DEBUG, "Reference not found\n");
2028 /* if there were no references at all, allocate one */
2029 if (!s->ref_pics[i])
2030 for (j = 0; j < MAX_FRAMES; j++)
2031 if (!s->all_frames[j].avframe->data[0]) {
2032 s->ref_pics[i] = &s->all_frames[j];
2033 ret = get_buffer_with_edge(s->avctx, s->ref_pics[i]->avframe, AV_GET_BUFFER_FLAG_REF);
2039 if (!s->ref_pics[i]) {
2040 av_log(s->avctx, AV_LOG_ERROR, "Reference could not be allocated\n");
2041 return AVERROR_INVALIDDATA;
2046 /* retire the reference frames that are not used anymore */
2047 if (s->current_picture->reference) {
2048 retire = (picnum + dirac_get_se_golomb(gb)) & 0xFFFFFFFF;
2049 if (retire != picnum) {
2050 DiracFrame *retire_pic = remove_frame(s->ref_frames, retire);
2053 retire_pic->reference &= DELAYED_PIC_REF;
2055 av_log(s->avctx, AV_LOG_DEBUG, "Frame to retire not found\n");
2058 /* if reference array is full, remove the oldest as per the spec */
2059 while (add_frame(s->ref_frames, MAX_REFERENCE_FRAMES, s->current_picture)) {
2060 av_log(s->avctx, AV_LOG_ERROR, "Reference frame overflow\n");
2061 remove_frame(s->ref_frames, s->ref_frames[0]->avframe->display_picture_number)->reference &= DELAYED_PIC_REF;
2066 ret = dirac_unpack_prediction_parameters(s); /* [DIRAC_STD] 11.2 Picture Prediction Data. picture_prediction() */
2069 ret = dirac_unpack_block_motion_data(s); /* [DIRAC_STD] 12. Block motion data syntax */
2073 ret = dirac_unpack_idwt_params(s); /* [DIRAC_STD] 11.3 Wavelet transform data */
2081 static int get_delayed_pic(DiracContext *s, AVFrame *picture, int *got_frame)
2083 DiracFrame *out = s->delay_frames[0];
2087 /* find frame with lowest picture number */
2088 for (i = 1; s->delay_frames[i]; i++)
2089 if (s->delay_frames[i]->avframe->display_picture_number < out->avframe->display_picture_number) {
2090 out = s->delay_frames[i];
2094 for (i = out_idx; s->delay_frames[i]; i++)
2095 s->delay_frames[i] = s->delay_frames[i+1];
2098 out->reference ^= DELAYED_PIC_REF;
2099 if((ret = av_frame_ref(picture, out->avframe)) < 0)
2108 * Dirac Specification ->
2109 * 9.6 Parse Info Header Syntax. parse_info()
2110 * 4 byte start code + byte parse code + 4 byte size + 4 byte previous size
2112 #define DATA_UNIT_HEADER_SIZE 13
2114 /* [DIRAC_STD] dirac_decode_data_unit makes reference to the while defined in 9.3
2115 inside the function parse_sequence() */
2116 static int dirac_decode_data_unit(AVCodecContext *avctx, const uint8_t *buf, int size)
2118 DiracContext *s = avctx->priv_data;
2119 DiracFrame *pic = NULL;
2120 AVDiracSeqHeader *dsh;
2125 if (size < DATA_UNIT_HEADER_SIZE)
2126 return AVERROR_INVALIDDATA;
2128 parse_code = buf[4];
2130 init_get_bits(&s->gb, &buf[13], 8*(size - DATA_UNIT_HEADER_SIZE));
2132 if (parse_code == DIRAC_PCODE_SEQ_HEADER) {
2133 if (s->seen_sequence_header)
2136 /* [DIRAC_STD] 10. Sequence header */
2137 ret = av_dirac_parse_sequence_header(&dsh, buf + DATA_UNIT_HEADER_SIZE, size - DATA_UNIT_HEADER_SIZE, avctx);
2139 av_log(avctx, AV_LOG_ERROR, "error parsing sequence header");
2143 if (CALC_PADDING((int64_t)dsh->width, MAX_DWT_LEVELS) * CALC_PADDING((int64_t)dsh->height, MAX_DWT_LEVELS) * 5LL > avctx->max_pixels)
2144 ret = AVERROR(ERANGE);
2146 ret = ff_set_dimensions(avctx, dsh->width, dsh->height);
2152 ff_set_sar(avctx, dsh->sample_aspect_ratio);
2153 avctx->pix_fmt = dsh->pix_fmt;
2154 avctx->color_range = dsh->color_range;
2155 avctx->color_trc = dsh->color_trc;
2156 avctx->color_primaries = dsh->color_primaries;
2157 avctx->colorspace = dsh->colorspace;
2158 avctx->profile = dsh->profile;
2159 avctx->level = dsh->level;
2160 avctx->framerate = dsh->framerate;
2161 s->bit_depth = dsh->bit_depth;
2162 s->version.major = dsh->version.major;
2163 s->version.minor = dsh->version.minor;
2167 s->pshift = s->bit_depth > 8;
2169 ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt,
2171 &s->chroma_y_shift);
2175 ret = alloc_sequence_buffers(s);
2179 s->seen_sequence_header = 1;
2180 } else if (parse_code == DIRAC_PCODE_END_SEQ) { /* [DIRAC_STD] End of Sequence */
2181 free_sequence_buffers(s);
2182 s->seen_sequence_header = 0;
2183 } else if (parse_code == DIRAC_PCODE_AUX) {
2184 if (buf[13] == 1) { /* encoder implementation/version */
2186 /* versions older than 1.0.8 don't store quant delta for
2187 subbands with only one codeblock */
2188 if (sscanf(buf+14, "Schroedinger %d.%d.%d", ver, ver+1, ver+2) == 3)
2189 if (ver[0] == 1 && ver[1] == 0 && ver[2] <= 7)
2190 s->old_delta_quant = 1;
2192 } else if (parse_code & 0x8) { /* picture data unit */
2193 if (!s->seen_sequence_header) {
2194 av_log(avctx, AV_LOG_DEBUG, "Dropping frame without sequence header\n");
2195 return AVERROR_INVALIDDATA;
2198 /* find an unused frame */
2199 for (i = 0; i < MAX_FRAMES; i++)
2200 if (s->all_frames[i].avframe->data[0] == NULL)
2201 pic = &s->all_frames[i];
2203 av_log(avctx, AV_LOG_ERROR, "framelist full\n");
2204 return AVERROR_INVALIDDATA;
2207 av_frame_unref(pic->avframe);
2209 /* [DIRAC_STD] Defined in 9.6.1 ... */
2210 tmp = parse_code & 0x03; /* [DIRAC_STD] num_refs() */
2212 av_log(avctx, AV_LOG_ERROR, "num_refs of 3\n");
2213 return AVERROR_INVALIDDATA;
2216 s->is_arith = (parse_code & 0x48) == 0x08; /* [DIRAC_STD] using_ac() */
2217 s->low_delay = (parse_code & 0x88) == 0x88; /* [DIRAC_STD] is_low_delay() */
2218 s->core_syntax = (parse_code & 0x88) == 0x08; /* [DIRAC_STD] is_core_syntax() */
2219 s->ld_picture = (parse_code & 0xF8) == 0xC8; /* [DIRAC_STD] is_ld_picture() */
2220 s->hq_picture = (parse_code & 0xF8) == 0xE8; /* [DIRAC_STD] is_hq_picture() */
2221 s->dc_prediction = (parse_code & 0x28) == 0x08; /* [DIRAC_STD] using_dc_prediction() */
2222 pic->reference = (parse_code & 0x0C) == 0x0C; /* [DIRAC_STD] is_reference() */
2223 pic->avframe->key_frame = s->num_refs == 0; /* [DIRAC_STD] is_intra() */
2224 pic->avframe->pict_type = s->num_refs + 1; /* Definition of AVPictureType in avutil.h */
2226 /* VC-2 Low Delay has a different parse code than the Dirac Low Delay */
2227 if (s->version.minor == 2 && parse_code == 0x88)
2230 if (s->low_delay && !(s->ld_picture || s->hq_picture) ) {
2231 av_log(avctx, AV_LOG_ERROR, "Invalid low delay flag\n");
2232 return AVERROR_INVALIDDATA;
2235 if ((ret = get_buffer_with_edge(avctx, pic->avframe, (parse_code & 0x0C) == 0x0C ? AV_GET_BUFFER_FLAG_REF : 0)) < 0)
2237 s->current_picture = pic;
2238 s->plane[0].stride = pic->avframe->linesize[0];
2239 s->plane[1].stride = pic->avframe->linesize[1];
2240 s->plane[2].stride = pic->avframe->linesize[2];
2242 if (alloc_buffers(s, FFMAX3(FFABS(s->plane[0].stride), FFABS(s->plane[1].stride), FFABS(s->plane[2].stride))) < 0)
2243 return AVERROR(ENOMEM);
2245 /* [DIRAC_STD] 11.1 Picture parse. picture_parse() */
2246 ret = dirac_decode_picture_header(s);
2250 /* [DIRAC_STD] 13.0 Transform data syntax. transform_data() */
2251 ret = dirac_decode_frame_internal(s);
2258 static int dirac_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt)
2260 DiracContext *s = avctx->priv_data;
2261 AVFrame *picture = data;
2262 uint8_t *buf = pkt->data;
2263 int buf_size = pkt->size;
2266 unsigned data_unit_size;
2268 /* release unused frames */
2269 for (i = 0; i < MAX_FRAMES; i++)
2270 if (s->all_frames[i].avframe->data[0] && !s->all_frames[i].reference) {
2271 av_frame_unref(s->all_frames[i].avframe);
2272 memset(s->all_frames[i].interpolated, 0, sizeof(s->all_frames[i].interpolated));
2275 s->current_picture = NULL;
2278 /* end of stream, so flush delayed pics */
2280 return get_delayed_pic(s, (AVFrame *)data, got_frame);
2283 /*[DIRAC_STD] Here starts the code from parse_info() defined in 9.6
2284 [DIRAC_STD] PARSE_INFO_PREFIX = "BBCD" as defined in ISO/IEC 646
2285 BBCD start code search */
2286 for (; buf_idx + DATA_UNIT_HEADER_SIZE < buf_size; buf_idx++) {
2287 if (buf[buf_idx ] == 'B' && buf[buf_idx+1] == 'B' &&
2288 buf[buf_idx+2] == 'C' && buf[buf_idx+3] == 'D')
2291 /* BBCD found or end of data */
2292 if (buf_idx + DATA_UNIT_HEADER_SIZE >= buf_size)
2295 data_unit_size = AV_RB32(buf+buf_idx+5);
2296 if (data_unit_size > buf_size - buf_idx || !data_unit_size) {
2297 if(data_unit_size > buf_size - buf_idx)
2298 av_log(s->avctx, AV_LOG_ERROR,
2299 "Data unit with size %d is larger than input buffer, discarding\n",
2304 /* [DIRAC_STD] dirac_decode_data_unit makes reference to the while defined in 9.3 inside the function parse_sequence() */
2305 ret = dirac_decode_data_unit(avctx, buf+buf_idx, data_unit_size);
2308 av_log(s->avctx, AV_LOG_ERROR,"Error in dirac_decode_data_unit\n");
2311 buf_idx += data_unit_size;
2314 if (!s->current_picture)
2317 if (s->current_picture->avframe->display_picture_number > s->frame_number) {
2318 DiracFrame *delayed_frame = remove_frame(s->delay_frames, s->frame_number);
2320 s->current_picture->reference |= DELAYED_PIC_REF;
2322 if (add_frame(s->delay_frames, MAX_DELAY, s->current_picture)) {
2323 int min_num = s->delay_frames[0]->avframe->display_picture_number;
2324 /* Too many delayed frames, so we display the frame with the lowest pts */
2325 av_log(avctx, AV_LOG_ERROR, "Delay frame overflow\n");
2327 for (i = 1; s->delay_frames[i]; i++)
2328 if (s->delay_frames[i]->avframe->display_picture_number < min_num)
2329 min_num = s->delay_frames[i]->avframe->display_picture_number;
2331 delayed_frame = remove_frame(s->delay_frames, min_num);
2332 add_frame(s->delay_frames, MAX_DELAY, s->current_picture);
2335 if (delayed_frame) {
2336 delayed_frame->reference ^= DELAYED_PIC_REF;
2337 if((ret=av_frame_ref(data, delayed_frame->avframe)) < 0)
2341 } else if (s->current_picture->avframe->display_picture_number == s->frame_number) {
2342 /* The right frame at the right time :-) */
2343 if((ret=av_frame_ref(data, s->current_picture->avframe)) < 0)
2349 s->frame_number = picture->display_picture_number + 1LL;
2354 AVCodec ff_dirac_decoder = {
2356 .long_name = NULL_IF_CONFIG_SMALL("BBC Dirac VC-2"),
2357 .type = AVMEDIA_TYPE_VIDEO,
2358 .id = AV_CODEC_ID_DIRAC,
2359 .priv_data_size = sizeof(DiracContext),
2360 .init = dirac_decode_init,
2361 .close = dirac_decode_end,
2362 .decode = dirac_decode_frame,
2363 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS | AV_CODEC_CAP_DR1,
2364 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
2365 .flush = dirac_decode_flush,