]> git.sesse.net Git - ffmpeg/blob - libavcodec/indeo4.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / indeo4.c
1 /*
2  * Indeo Video Interactive v4 compatible decoder
3  * Copyright (c) 2009-2011 Maxim Poliakovski
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * Indeo Video Interactive version 4 decoder
25  *
26  * Indeo 4 data is usually transported within .avi or .mov files.
27  * Known FOURCCs: 'IV41'
28  */
29
30 #define BITSTREAM_READER_LE
31 #include "avcodec.h"
32 #include "get_bits.h"
33 #include "dsputil.h"
34 #include "ivi_dsp.h"
35 #include "ivi_common.h"
36 #include "indeo4data.h"
37
38 #define IVI4_STREAM_ANALYSER    0
39 #define IVI4_DEBUG_CHECKSUM     0
40
41 /**
42  *  Indeo 4 frame types.
43  */
44 enum {
45     FRAMETYPE_INTRA       = 0,
46     FRAMETYPE_BIDIR1      = 1,  ///< bidirectional frame
47     FRAMETYPE_INTER       = 2,  ///< non-droppable P-frame
48     FRAMETYPE_BIDIR       = 3,  ///< bidirectional frame
49     FRAMETYPE_INTER_NOREF = 4,  ///< droppable P-frame
50     FRAMETYPE_NULL_FIRST  = 5,  ///< empty frame with no data
51     FRAMETYPE_NULL_LAST   = 6   ///< empty frame with no data
52 };
53
54 #define IVI4_PIC_SIZE_ESC   7
55
56
57 typedef struct {
58     GetBitContext   gb;
59     AVFrame         frame;
60     RVMapDesc       rvmap_tabs[9];   ///< local corrected copy of the static rvmap tables
61
62     uint32_t        frame_num;
63     int             frame_type;
64     int             prev_frame_type; ///< frame type of the previous frame
65     uint32_t        data_size;       ///< size of the frame data in bytes from picture header
66     int             is_scalable;
67     int             transp_status;   ///< transparency mode status: 1 - enabled
68
69     IVIPicConfig    pic_conf;
70     IVIPlaneDesc    planes[3];       ///< color planes
71
72     int             buf_switch;      ///< used to switch between three buffers
73     int             dst_buf;         ///< buffer index for the currently decoded frame
74     int             ref_buf;         ///< inter frame reference buffer index
75
76     IVIHuffTab      mb_vlc;          ///< current macroblock table descriptor
77     IVIHuffTab      blk_vlc;         ///< current block table descriptor
78
79     uint16_t        checksum;        ///< frame checksum
80
81     uint8_t         rvmap_sel;
82     uint8_t         in_imf;
83     uint8_t         in_q;            ///< flag for explicitly stored quantiser delta
84     uint8_t         pic_glob_quant;
85     uint8_t         unknown1;
86
87 #if IVI4_STREAM_ANALYSER
88     uint8_t         has_b_frames;
89     uint8_t         has_transp;
90     uint8_t         uses_tiling;
91     uint8_t         uses_haar;
92     uint8_t         uses_fullpel;
93 #endif
94 } IVI4DecContext;
95
96
97 static const struct {
98     InvTransformPtr *inv_trans;
99     DCTransformPtr  *dc_trans;
100     int             is_2d_trans;
101 } transforms[18] = {
102     { ff_ivi_inverse_haar_8x8,  ff_ivi_dc_haar_2d,       1 },
103     { NULL, NULL, 0 }, /* inverse Haar 8x1 */
104     { NULL, NULL, 0 }, /* inverse Haar 1x8 */
105     { ff_ivi_put_pixels_8x8,    ff_ivi_put_dc_pixel_8x8, 1 },
106     { ff_ivi_inverse_slant_8x8, ff_ivi_dc_slant_2d,      1 },
107     { ff_ivi_row_slant8,        ff_ivi_dc_row_slant,     1 },
108     { ff_ivi_col_slant8,        ff_ivi_dc_col_slant,     1 },
109     { NULL, NULL, 0 }, /* inverse DCT 8x8 */
110     { NULL, NULL, 0 }, /* inverse DCT 8x1 */
111     { NULL, NULL, 0 }, /* inverse DCT 1x8 */
112     { NULL, NULL, 0 }, /* inverse Haar 4x4 */
113     { ff_ivi_inverse_slant_4x4, ff_ivi_dc_slant_2d,      1 },
114     { NULL, NULL, 0 }, /* no transform 4x4 */
115     { NULL, NULL, 0 }, /* inverse Haar 1x4 */
116     { NULL, NULL, 0 }, /* inverse Haar 4x1 */
117     { NULL, NULL, 0 }, /* inverse slant 1x4 */
118     { NULL, NULL, 0 }, /* inverse slant 4x1 */
119     { NULL, NULL, 0 }, /* inverse DCT 4x4 */
120 };
121
122 /**
123  *  Decode subdivision of a plane.
124  *  This is a simplified version that checks for two supported subdivisions:
125  *  - 1 wavelet band  per plane, size factor 1:1, code pattern: 3
126  *  - 4 wavelet bands per plane, size factor 1:4, code pattern: 2,3,3,3,3
127  *  Anything else is either unsupported or corrupt.
128  *
129  *  @param[in,out] gb    the GetBit context
130  *  @return        number of wavelet bands or 0 on error
131  */
132 static int decode_plane_subdivision(GetBitContext *gb)
133 {
134     int i;
135
136     switch (get_bits(gb, 2)) {
137     case 3:
138         return 1;
139     case 2:
140         for (i = 0; i < 4; i++)
141             if (get_bits(gb, 2) != 3)
142                 return 0;
143         return 4;
144     default:
145         return 0;
146     }
147 }
148
149 static inline int scale_tile_size(int def_size, int size_factor)
150 {
151     return size_factor == 15 ? def_size : (size_factor + 1) << 5;
152 }
153
154 /**
155  *  Decode Indeo 4 picture header.
156  *
157  *  @param[in,out] ctx       pointer to the decoder context
158  *  @param[in]     avctx     pointer to the AVCodecContext
159  *  @return        result code: 0 = OK, negative number = error
160  */
161 static int decode_pic_hdr(IVI4DecContext *ctx, AVCodecContext *avctx)
162 {
163     int             pic_size_indx, i, p;
164     IVIPicConfig    pic_conf;
165
166     if (get_bits(&ctx->gb, 18) != 0x3FFF8) {
167         av_log(avctx, AV_LOG_ERROR, "Invalid picture start code!\n");
168         return AVERROR_INVALIDDATA;
169     }
170
171     ctx->prev_frame_type = ctx->frame_type;
172     ctx->frame_type      = get_bits(&ctx->gb, 3);
173     if (ctx->frame_type == 7) {
174         av_log(avctx, AV_LOG_ERROR, "Invalid frame type: %d\n", ctx->frame_type);
175         return AVERROR_INVALIDDATA;
176     }
177
178 #if IVI4_STREAM_ANALYSER
179     if (   ctx->frame_type == FRAMETYPE_BIDIR1
180         || ctx->frame_type == FRAMETYPE_BIDIR)
181         ctx->has_b_frames = 1;
182 #endif
183
184     ctx->transp_status = get_bits1(&ctx->gb);
185 #if IVI4_STREAM_ANALYSER
186     if (ctx->transp_status) {
187         ctx->has_transp = 1;
188     }
189 #endif
190
191     /* unknown bit: Mac decoder ignores this bit, XANIM returns error */
192     if (get_bits1(&ctx->gb)) {
193         av_log(avctx, AV_LOG_ERROR, "Sync bit is set!\n");
194         return AVERROR_INVALIDDATA;
195     }
196
197     ctx->data_size = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 24) : 0;
198
199     /* null frames don't contain anything else so we just return */
200     if (ctx->frame_type >= FRAMETYPE_NULL_FIRST) {
201         av_dlog(avctx, "Null frame encountered!\n");
202         return 0;
203     }
204
205     /* Check key lock status. If enabled - ignore lock word.         */
206     /* Usually we have to prompt the user for the password, but      */
207     /* we don't do that because Indeo 4 videos can be decoded anyway */
208     if (get_bits1(&ctx->gb)) {
209         skip_bits_long(&ctx->gb, 32);
210         av_dlog(avctx, "Password-protected clip!\n");
211     }
212
213     pic_size_indx = get_bits(&ctx->gb, 3);
214     if (pic_size_indx == IVI4_PIC_SIZE_ESC) {
215         pic_conf.pic_height = get_bits(&ctx->gb, 16);
216         pic_conf.pic_width  = get_bits(&ctx->gb, 16);
217     } else {
218         pic_conf.pic_height = ivi4_common_pic_sizes[pic_size_indx * 2 + 1];
219         pic_conf.pic_width  = ivi4_common_pic_sizes[pic_size_indx * 2    ];
220     }
221
222     /* Decode tile dimensions. */
223     if (get_bits1(&ctx->gb)) {
224         pic_conf.tile_height = scale_tile_size(pic_conf.pic_height, get_bits(&ctx->gb, 4));
225         pic_conf.tile_width  = scale_tile_size(pic_conf.pic_width,  get_bits(&ctx->gb, 4));
226 #if IVI4_STREAM_ANALYSER
227         ctx->uses_tiling = 1;
228 #endif
229     } else {
230         pic_conf.tile_height = pic_conf.pic_height;
231         pic_conf.tile_width  = pic_conf.pic_width;
232     }
233
234     /* Decode chroma subsampling. We support only 4:4 aka YVU9. */
235     if (get_bits(&ctx->gb, 2)) {
236         av_log(avctx, AV_LOG_ERROR, "Only YVU9 picture format is supported!\n");
237         return AVERROR_INVALIDDATA;
238     }
239     pic_conf.chroma_height = (pic_conf.pic_height + 3) >> 2;
240     pic_conf.chroma_width  = (pic_conf.pic_width  + 3) >> 2;
241
242     /* decode subdivision of the planes */
243     pic_conf.luma_bands = decode_plane_subdivision(&ctx->gb);
244     if (pic_conf.luma_bands)
245         pic_conf.chroma_bands = decode_plane_subdivision(&ctx->gb);
246     ctx->is_scalable = pic_conf.luma_bands != 1 || pic_conf.chroma_bands != 1;
247     if (ctx->is_scalable && (pic_conf.luma_bands != 4 || pic_conf.chroma_bands != 1)) {
248         av_log(avctx, AV_LOG_ERROR, "Scalability: unsupported subdivision! Luma bands: %d, chroma bands: %d\n",
249                pic_conf.luma_bands, pic_conf.chroma_bands);
250         return AVERROR_INVALIDDATA;
251     }
252
253     /* check if picture layout was changed and reallocate buffers */
254     if (ivi_pic_config_cmp(&pic_conf, &ctx->pic_conf)) {
255         if (ff_ivi_init_planes(ctx->planes, &pic_conf)) {
256             av_log(avctx, AV_LOG_ERROR, "Couldn't reallocate color planes!\n");
257             return AVERROR(ENOMEM);
258         }
259
260         ctx->pic_conf = pic_conf;
261
262         /* set default macroblock/block dimensions */
263         for (p = 0; p <= 2; p++) {
264             for (i = 0; i < (!p ? pic_conf.luma_bands : pic_conf.chroma_bands); i++) {
265                 ctx->planes[p].bands[i].mb_size  = !p ? (!ctx->is_scalable ? 16 : 8) : 4;
266                 ctx->planes[p].bands[i].blk_size = !p ? 8 : 4;
267             }
268         }
269
270         if (ff_ivi_init_tiles(ctx->planes, ctx->pic_conf.tile_width,
271                               ctx->pic_conf.tile_height)) {
272             av_log(avctx, AV_LOG_ERROR,
273                    "Couldn't reallocate internal structures!\n");
274             return AVERROR(ENOMEM);
275         }
276     }
277
278     ctx->frame_num = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 20) : 0;
279
280     /* skip decTimeEst field if present */
281     if (get_bits1(&ctx->gb))
282         skip_bits(&ctx->gb, 8);
283
284     /* decode macroblock and block huffman codebooks */
285     if (ff_ivi_dec_huff_desc(&ctx->gb, get_bits1(&ctx->gb), IVI_MB_HUFF,  &ctx->mb_vlc,  avctx) ||
286         ff_ivi_dec_huff_desc(&ctx->gb, get_bits1(&ctx->gb), IVI_BLK_HUFF, &ctx->blk_vlc, avctx))
287         return AVERROR_INVALIDDATA;
288
289     ctx->rvmap_sel = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 3) : 8;
290
291     ctx->in_imf = get_bits1(&ctx->gb);
292     ctx->in_q   = get_bits1(&ctx->gb);
293
294     ctx->pic_glob_quant = get_bits(&ctx->gb, 5);
295
296     /* TODO: ignore this parameter if unused */
297     ctx->unknown1 = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 3) : 0;
298
299     ctx->checksum = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 16) : 0;
300
301     /* skip picture header extension if any */
302     while (get_bits1(&ctx->gb)) {
303         av_dlog(avctx, "Pic hdr extension encountered!\n");
304         skip_bits(&ctx->gb, 8);
305     }
306
307     if (get_bits1(&ctx->gb)) {
308         av_log(avctx, AV_LOG_ERROR, "Bad blocks bits encountered!\n");
309     }
310
311     align_get_bits(&ctx->gb);
312
313     return 0;
314 }
315
316
317 /**
318  *  Decode Indeo 4 band header.
319  *
320  *  @param[in,out] ctx       pointer to the decoder context
321  *  @param[in,out] band      pointer to the band descriptor
322  *  @param[in]     avctx     pointer to the AVCodecContext
323  *  @return        result code: 0 = OK, negative number = error
324  */
325 static int decode_band_hdr(IVI4DecContext *ctx, IVIBandDesc *band,
326                            AVCodecContext *avctx)
327 {
328     int plane, band_num, indx, transform_id, scan_indx;
329     int i;
330     int quant_mat;
331
332     plane    = get_bits(&ctx->gb, 2);
333     band_num = get_bits(&ctx->gb, 4);
334     if (band->plane != plane || band->band_num != band_num) {
335         av_log(avctx, AV_LOG_ERROR, "Invalid band header sequence!\n");
336         return AVERROR_INVALIDDATA;
337     }
338
339     band->is_empty = get_bits1(&ctx->gb);
340     if (!band->is_empty) {
341         /* skip header size
342          * If header size is not given, header size is 4 bytes. */
343         if (get_bits1(&ctx->gb))
344             skip_bits(&ctx->gb, 16);
345
346         band->is_halfpel = get_bits(&ctx->gb, 2);
347         if (band->is_halfpel >= 2) {
348             av_log(avctx, AV_LOG_ERROR, "Invalid/unsupported mv resolution: %d!\n",
349                    band->is_halfpel);
350             return AVERROR_INVALIDDATA;
351         }
352 #if IVI4_STREAM_ANALYSER
353         if (!band->is_halfpel)
354             ctx->uses_fullpel = 1;
355 #endif
356
357         band->checksum_present = get_bits1(&ctx->gb);
358         if (band->checksum_present)
359             band->checksum = get_bits(&ctx->gb, 16);
360
361         indx = get_bits(&ctx->gb, 2);
362         if (indx == 3) {
363             av_log(avctx, AV_LOG_ERROR, "Invalid block size!\n");
364             return AVERROR_INVALIDDATA;
365         }
366         band->mb_size  = 16 >> indx;
367         band->blk_size = 8 >> (indx >> 1);
368
369         band->inherit_mv     = get_bits1(&ctx->gb);
370         band->inherit_qdelta = get_bits1(&ctx->gb);
371
372         band->glob_quant = get_bits(&ctx->gb, 5);
373
374         if (!get_bits1(&ctx->gb) || ctx->frame_type == FRAMETYPE_INTRA) {
375             transform_id = get_bits(&ctx->gb, 5);
376             if (transform_id >= FF_ARRAY_ELEMS(transforms) ||
377                 !transforms[transform_id].inv_trans) {
378                 av_log_ask_for_sample(avctx, "Unimplemented transform: %d!\n", transform_id);
379                 return AVERROR_PATCHWELCOME;
380             }
381             if ((transform_id >= 7 && transform_id <= 9) ||
382                  transform_id == 17) {
383                 av_log_ask_for_sample(avctx, "DCT transform not supported yet!\n");
384                 return AVERROR_PATCHWELCOME;
385             }
386
387             if (transform_id < 10 && band->blk_size < 8) {
388                 av_log(avctx, AV_LOG_ERROR, "wrong transform size!\n");
389                 return AVERROR_INVALIDDATA;
390             }
391 #if IVI4_STREAM_ANALYSER
392             if ((transform_id >= 0 && transform_id <= 2) || transform_id == 10)
393                 ctx->uses_haar = 1;
394 #endif
395
396             band->inv_transform = transforms[transform_id].inv_trans;
397             band->dc_transform  = transforms[transform_id].dc_trans;
398             band->is_2d_trans   = transforms[transform_id].is_2d_trans;
399             band->transform_size= (transform_id < 10) ? 8 : 4;
400
401             scan_indx = get_bits(&ctx->gb, 4);
402             if ((scan_indx>4 && scan_indx<10) != (band->blk_size==4)) {
403                 av_log(avctx, AV_LOG_ERROR, "mismatching scan table!\n");
404                 return AVERROR_INVALIDDATA;
405             }
406             if (scan_indx == 15) {
407                 av_log(avctx, AV_LOG_ERROR, "Custom scan pattern encountered!\n");
408                 return AVERROR_INVALIDDATA;
409             }
410             band->scan = scan_index_to_tab[scan_indx];
411
412             quant_mat = get_bits(&ctx->gb, 5);
413             if (quant_mat == 31) {
414                 av_log(avctx, AV_LOG_ERROR, "Custom quant matrix encountered!\n");
415                 return AVERROR_INVALIDDATA;
416             }
417             if (quant_mat > 21) {
418                 av_log(avctx, AV_LOG_ERROR, "Invalid quant matrix encountered!\n");
419                 return AVERROR_INVALIDDATA;
420             }
421             band->quant_mat = quant_mat;
422         }
423
424         /* decode block huffman codebook */
425         if (ff_ivi_dec_huff_desc(&ctx->gb, get_bits1(&ctx->gb), IVI_BLK_HUFF,
426                                  &band->blk_vlc, avctx))
427             return AVERROR_INVALIDDATA;
428
429         /* select appropriate rvmap table for this band */
430         band->rvmap_sel = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 3) : 8;
431
432         /* decode rvmap probability corrections if any */
433         band->num_corr = 0; /* there is no corrections */
434         if (get_bits1(&ctx->gb)) {
435             band->num_corr = get_bits(&ctx->gb, 8); /* get number of correction pairs */
436             if (band->num_corr > 61) {
437                 av_log(avctx, AV_LOG_ERROR, "Too many corrections: %d\n",
438                        band->num_corr);
439                 return AVERROR_INVALIDDATA;
440             }
441
442             /* read correction pairs */
443             for (i = 0; i < band->num_corr * 2; i++)
444                 band->corr[i] = get_bits(&ctx->gb, 8);
445         }
446     }
447
448     if (band->blk_size == 8) {
449         band->intra_base = &ivi4_quant_8x8_intra[quant_index_to_tab[band->quant_mat]][0];
450         band->inter_base = &ivi4_quant_8x8_inter[quant_index_to_tab[band->quant_mat]][0];
451     } else {
452         band->intra_base = &ivi4_quant_4x4_intra[quant_index_to_tab[band->quant_mat]][0];
453         band->inter_base = &ivi4_quant_4x4_inter[quant_index_to_tab[band->quant_mat]][0];
454     }
455
456     /* Indeo 4 doesn't use scale tables */
457     band->intra_scale = NULL;
458     band->inter_scale = NULL;
459
460     align_get_bits(&ctx->gb);
461
462     if (!band->scan) {
463         av_log(avctx, AV_LOG_ERROR, "band->scan not set\n");
464         return AVERROR_INVALIDDATA;
465     }
466
467     return 0;
468 }
469
470
471 /**
472  *  Decode information (block type, cbp, quant delta, motion vector)
473  *  for all macroblocks in the current tile.
474  *
475  *  @param[in,out] ctx       pointer to the decoder context
476  *  @param[in,out] band      pointer to the band descriptor
477  *  @param[in,out] tile      pointer to the tile descriptor
478  *  @param[in]     avctx     pointer to the AVCodecContext
479  *  @return        result code: 0 = OK, negative number = error
480  */
481 static int decode_mb_info(IVI4DecContext *ctx, IVIBandDesc *band,
482                           IVITile *tile, AVCodecContext *avctx)
483 {
484     int         x, y, mv_x, mv_y, mv_delta, offs, mb_offset, blks_per_mb,
485                 mv_scale, mb_type_bits, s;
486     IVIMbInfo   *mb, *ref_mb;
487     int         row_offset = band->mb_size * band->pitch;
488
489     mb     = tile->mbs;
490     ref_mb = tile->ref_mbs;
491     offs   = tile->ypos * band->pitch + tile->xpos;
492
493     blks_per_mb  = band->mb_size   != band->blk_size  ? 4 : 1;
494     mb_type_bits = ctx->frame_type == FRAMETYPE_BIDIR ? 2 : 1;
495
496     /* scale factor for motion vectors */
497     mv_scale = (ctx->planes[0].bands[0].mb_size >> 3) - (band->mb_size >> 3);
498     mv_x = mv_y = 0;
499
500     if (((tile->width + band->mb_size-1)/band->mb_size) * ((tile->height + band->mb_size-1)/band->mb_size) != tile->num_MBs) {
501         av_log(avctx, AV_LOG_ERROR, "num_MBs mismatch %d %d %d %d\n", tile->width, tile->height, band->mb_size, tile->num_MBs);
502         return -1;
503     }
504
505     for (y = tile->ypos; y < tile->ypos + tile->height; y += band->mb_size) {
506         mb_offset = offs;
507
508         for (x = tile->xpos; x < tile->xpos + tile->width; x += band->mb_size) {
509             mb->xpos     = x;
510             mb->ypos     = y;
511             mb->buf_offs = mb_offset;
512
513             if (get_bits1(&ctx->gb)) {
514                 if (ctx->frame_type == FRAMETYPE_INTRA) {
515                     av_log(avctx, AV_LOG_ERROR, "Empty macroblock in an INTRA picture!\n");
516                     return AVERROR_INVALIDDATA;
517                 }
518                 mb->type = 1; /* empty macroblocks are always INTER */
519                 mb->cbp  = 0; /* all blocks are empty */
520
521                 mb->q_delta = 0;
522                 if (!band->plane && !band->band_num && ctx->in_q) {
523                     mb->q_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
524                                            IVI_VLC_BITS, 1);
525                     mb->q_delta = IVI_TOSIGNED(mb->q_delta);
526                 }
527
528                 mb->mv_x = mb->mv_y = 0; /* no motion vector coded */
529                 if (band->inherit_mv && ref_mb) {
530                     /* motion vector inheritance */
531                     if (mv_scale) {
532                         mb->mv_x = ivi_scale_mv(ref_mb->mv_x, mv_scale);
533                         mb->mv_y = ivi_scale_mv(ref_mb->mv_y, mv_scale);
534                     } else {
535                         mb->mv_x = ref_mb->mv_x;
536                         mb->mv_y = ref_mb->mv_y;
537                     }
538                 }
539             } else {
540                 if (band->inherit_mv && ref_mb) {
541                     mb->type = ref_mb->type; /* copy mb_type from corresponding reference mb */
542                 } else if (ctx->frame_type == FRAMETYPE_INTRA) {
543                     mb->type = 0; /* mb_type is always INTRA for intra-frames */
544                 } else {
545                     mb->type = get_bits(&ctx->gb, mb_type_bits);
546                 }
547
548                 mb->cbp = get_bits(&ctx->gb, blks_per_mb);
549
550                 mb->q_delta = 0;
551                 if (band->inherit_qdelta) {
552                     if (ref_mb) mb->q_delta = ref_mb->q_delta;
553                 } else if (mb->cbp || (!band->plane && !band->band_num &&
554                            ctx->in_q)) {
555                     mb->q_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
556                                            IVI_VLC_BITS, 1);
557                     mb->q_delta = IVI_TOSIGNED(mb->q_delta);
558                 }
559
560                 if (!mb->type) {
561                     mb->mv_x = mb->mv_y = 0; /* there is no motion vector in intra-macroblocks */
562                 } else {
563                     if (band->inherit_mv && ref_mb) {
564                         /* motion vector inheritance */
565                         if (mv_scale) {
566                             mb->mv_x = ivi_scale_mv(ref_mb->mv_x, mv_scale);
567                             mb->mv_y = ivi_scale_mv(ref_mb->mv_y, mv_scale);
568                         } else {
569                             mb->mv_x = ref_mb->mv_x;
570                             mb->mv_y = ref_mb->mv_y;
571                         }
572                     } else {
573                         /* decode motion vector deltas */
574                         mv_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
575                                             IVI_VLC_BITS, 1);
576                         mv_y += IVI_TOSIGNED(mv_delta);
577                         mv_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
578                                             IVI_VLC_BITS, 1);
579                         mv_x += IVI_TOSIGNED(mv_delta);
580                         mb->mv_x = mv_x;
581                         mb->mv_y = mv_y;
582                     }
583                 }
584             }
585
586             s= band->is_halfpel;
587             if (mb->type)
588             if ( x +  (mb->mv_x   >>s) +                 (y+               (mb->mv_y   >>s))*band->pitch < 0 ||
589                  x + ((mb->mv_x+s)>>s) + band->mb_size - 1
590                    + (y+band->mb_size - 1 +((mb->mv_y+s)>>s))*band->pitch > band->bufsize -1) {
591                 av_log(avctx, AV_LOG_ERROR, "motion vector %d %d outside reference\n", x*s + mb->mv_x, y*s + mb->mv_y);
592                 return AVERROR_INVALIDDATA;
593             }
594
595             mb++;
596             if (ref_mb)
597                 ref_mb++;
598             mb_offset += band->mb_size;
599         }
600
601         offs += row_offset;
602     }
603
604     align_get_bits(&ctx->gb);
605
606     return 0;
607 }
608
609
610 /**
611  *  Decode an Indeo 4 band.
612  *
613  *  @param[in,out] ctx       pointer to the decoder context
614  *  @param[in,out] band      pointer to the band descriptor
615  *  @param[in]     avctx     pointer to the AVCodecContext
616  *  @return        result code: 0 = OK, negative number = error
617  */
618 static int decode_band(IVI4DecContext *ctx, int plane_num,
619                        IVIBandDesc *band, AVCodecContext *avctx)
620 {
621     int         result, i, t, pos, idx1, idx2;
622     IVITile     *tile;
623     int         ret = 0;
624
625     band->buf     = band->bufs[ctx->dst_buf];
626     band->ref_buf = band->bufs[ctx->ref_buf];
627
628     result = decode_band_hdr(ctx, band, avctx);
629     if (result) {
630         av_log(avctx, AV_LOG_ERROR, "Error decoding band header\n");
631         return result;
632     }
633
634     if (band->is_empty) {
635         av_log(avctx, AV_LOG_ERROR, "Empty band encountered!\n");
636         return AVERROR_INVALIDDATA;
637     }
638
639     band->rv_map = &ctx->rvmap_tabs[band->rvmap_sel];
640
641     /* apply corrections to the selected rvmap table if present */
642     for (i = 0; i < band->num_corr; i++) {
643         idx1 = band->corr[i * 2];
644         idx2 = band->corr[i * 2 + 1];
645         FFSWAP(uint8_t, band->rv_map->runtab[idx1], band->rv_map->runtab[idx2]);
646         FFSWAP(int16_t, band->rv_map->valtab[idx1], band->rv_map->valtab[idx2]);
647         if (idx1 == band->rv_map->eob_sym || idx2 == band->rv_map->eob_sym)
648             band->rv_map->eob_sym ^= idx1 ^ idx2;
649         if (idx1 == band->rv_map->esc_sym || idx2 == band->rv_map->esc_sym)
650             band->rv_map->esc_sym ^= idx1 ^ idx2;
651     }
652
653     pos = get_bits_count(&ctx->gb);
654
655     for (t = 0; t < band->num_tiles; t++) {
656         tile = &band->tiles[t];
657
658         tile->is_empty = get_bits1(&ctx->gb);
659         if (tile->is_empty) {
660             ff_ivi_process_empty_tile(avctx, band, tile,
661                                       (ctx->planes[0].bands[0].mb_size >> 3) - (band->mb_size >> 3));
662             av_dlog(avctx, "Empty tile encountered!\n");
663         } else {
664             tile->data_size = ff_ivi_dec_tile_data_size(&ctx->gb);
665             if (!tile->data_size) {
666                 av_log(avctx, AV_LOG_ERROR, "Tile data size is zero!\n");
667                 ret = AVERROR_INVALIDDATA;
668                 break;
669             }
670
671             result = decode_mb_info(ctx, band, tile, avctx);
672             if (result < 0)
673                 break;
674
675             result = ff_ivi_decode_blocks(&ctx->gb, band, tile);
676             if (result < 0 || ((get_bits_count(&ctx->gb) - pos) >> 3) != tile->data_size) {
677                 av_log(avctx, AV_LOG_ERROR, "Corrupted tile data encountered!\n");
678                 break;
679             }
680
681             pos += tile->data_size << 3; // skip to next tile
682         }
683     }
684
685     /* restore the selected rvmap table by applying its corrections in reverse order */
686     for (i = band->num_corr - 1; i >= 0; i--) {
687         idx1 = band->corr[i * 2];
688         idx2 = band->corr[i * 2 + 1];
689         FFSWAP(uint8_t, band->rv_map->runtab[idx1], band->rv_map->runtab[idx2]);
690         FFSWAP(int16_t, band->rv_map->valtab[idx1], band->rv_map->valtab[idx2]);
691         if (idx1 == band->rv_map->eob_sym || idx2 == band->rv_map->eob_sym)
692             band->rv_map->eob_sym ^= idx1 ^ idx2;
693         if (idx1 == band->rv_map->esc_sym || idx2 == band->rv_map->esc_sym)
694             band->rv_map->esc_sym ^= idx1 ^ idx2;
695     }
696
697 #if defined(DEBUG) && IVI4_DEBUG_CHECKSUM
698     if (band->checksum_present) {
699         uint16_t chksum = ivi_calc_band_checksum(band);
700         if (chksum != band->checksum) {
701             av_log(avctx, AV_LOG_ERROR,
702                    "Band checksum mismatch! Plane %d, band %d, received: %x, calculated: %x\n",
703                    band->plane, band->band_num, band->checksum, chksum);
704         }
705     }
706 #endif
707
708     align_get_bits(&ctx->gb);
709
710     return ret;
711 }
712
713
714 static av_cold int decode_init(AVCodecContext *avctx)
715 {
716     IVI4DecContext *ctx = avctx->priv_data;
717
718     ff_ivi_init_static_vlc();
719
720     /* copy rvmap tables in our context so we can apply changes to them */
721     memcpy(ctx->rvmap_tabs, ff_ivi_rvmap_tabs, sizeof(ff_ivi_rvmap_tabs));
722
723     /* Force allocation of the internal buffers */
724     /* during picture header decoding.          */
725     ctx->pic_conf.pic_width  = 0;
726     ctx->pic_conf.pic_height = 0;
727
728     avctx->pix_fmt = PIX_FMT_YUV410P;
729
730     return 0;
731 }
732
733
734 /**
735  *  Rearrange decoding and reference buffers.
736  *
737  *  @param[in,out] ctx       pointer to the decoder context
738  */
739 static void switch_buffers(IVI4DecContext *ctx)
740 {
741     switch (ctx->prev_frame_type) {
742     case FRAMETYPE_INTRA:
743     case FRAMETYPE_INTER:
744         ctx->buf_switch ^= 1;
745         ctx->dst_buf     = ctx->buf_switch;
746         ctx->ref_buf     = ctx->buf_switch ^ 1;
747         break;
748     case FRAMETYPE_INTER_NOREF:
749         break;
750     }
751
752     switch (ctx->frame_type) {
753     case FRAMETYPE_INTRA:
754         ctx->buf_switch = 0;
755         /* FALLTHROUGH */
756     case FRAMETYPE_INTER:
757         ctx->dst_buf = ctx->buf_switch;
758         ctx->ref_buf = ctx->buf_switch ^ 1;
759         break;
760     case FRAMETYPE_INTER_NOREF:
761     case FRAMETYPE_NULL_FIRST:
762     case FRAMETYPE_NULL_LAST:
763         break;
764     }
765 }
766
767
768 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
769                         AVPacket *avpkt)
770 {
771     IVI4DecContext  *ctx = avctx->priv_data;
772     const uint8_t   *buf = avpkt->data;
773     int             buf_size = avpkt->size;
774     int             result, p, b;
775
776     init_get_bits(&ctx->gb, buf, buf_size * 8);
777
778     result = decode_pic_hdr(ctx, avctx);
779     if (result) {
780         av_log(avctx, AV_LOG_ERROR, "Error decoding picture header\n");
781         return result;
782     }
783
784     switch_buffers(ctx);
785
786     if (ctx->frame_type < FRAMETYPE_NULL_FIRST) {
787         for (p = 0; p < 3; p++) {
788             for (b = 0; b < ctx->planes[p].num_bands; b++) {
789                 result = decode_band(ctx, p, &ctx->planes[p].bands[b], avctx);
790                 if (result) {
791                     av_log(avctx, AV_LOG_ERROR,
792                            "Error decoding band: %d, plane: %d\n", b, p);
793                     return result;
794                 }
795             }
796         }
797     }
798
799     /* If the bidirectional mode is enabled, next I and the following P frame will */
800     /* be sent together. Unfortunately the approach below seems to be the only way */
801     /* to handle the B-frames mode. That's exactly the same Intel decoders do.     */
802     if (ctx->frame_type == FRAMETYPE_INTRA) {
803         while (get_bits(&ctx->gb, 8)); // skip version string
804         skip_bits_long(&ctx->gb, 64);  // skip padding, TODO: implement correct 8-bytes alignment
805         if (get_bits_left(&ctx->gb) > 18 && show_bits(&ctx->gb, 18) == 0x3FFF8)
806             av_log(avctx, AV_LOG_ERROR, "Buffer contains IP frames!\n");
807     }
808
809     if (ctx->frame_type >= FRAMETYPE_NULL_FIRST)
810         return buf_size;
811
812     if (ctx->frame.data[0])
813         avctx->release_buffer(avctx, &ctx->frame);
814
815     avcodec_set_dimensions(avctx, ctx->planes[0].width, ctx->planes[0].height);
816     ctx->frame.reference = 0;
817     if ((result = avctx->get_buffer(avctx, &ctx->frame)) < 0) {
818         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
819         return result;
820     }
821
822     if (ctx->is_scalable) {
823         ff_ivi_recompose_haar(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0], 4);
824     } else {
825         ff_ivi_output_plane(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0]);
826     }
827
828     ff_ivi_output_plane(&ctx->planes[2], ctx->frame.data[1], ctx->frame.linesize[1]);
829     ff_ivi_output_plane(&ctx->planes[1], ctx->frame.data[2], ctx->frame.linesize[2]);
830
831     *data_size = sizeof(AVFrame);
832     *(AVFrame*)data = ctx->frame;
833
834     return buf_size;
835 }
836
837
838 static av_cold int decode_close(AVCodecContext *avctx)
839 {
840     IVI4DecContext *ctx = avctx->priv_data;
841
842     ff_ivi_free_buffers(&ctx->planes[0]);
843
844     if (ctx->frame.data[0])
845         avctx->release_buffer(avctx, &ctx->frame);
846
847 #if IVI4_STREAM_ANALYSER
848     if (ctx->is_scalable)
849         av_log(avctx, AV_LOG_ERROR, "This video uses scalability mode!\n");
850     if (ctx->uses_tiling)
851         av_log(avctx, AV_LOG_ERROR, "This video uses local decoding!\n");
852     if (ctx->has_b_frames)
853         av_log(avctx, AV_LOG_ERROR, "This video contains B-frames!\n");
854     if (ctx->has_transp)
855         av_log(avctx, AV_LOG_ERROR, "Transparency mode is enabled!\n");
856     if (ctx->uses_haar)
857         av_log(avctx, AV_LOG_ERROR, "This video uses Haar transform!\n");
858     if (ctx->uses_fullpel)
859         av_log(avctx, AV_LOG_ERROR, "This video uses fullpel motion vectors!\n");
860 #endif
861
862     return 0;
863 }
864
865
866 AVCodec ff_indeo4_decoder = {
867     .name           = "indeo4",
868     .type           = AVMEDIA_TYPE_VIDEO,
869     .id             = CODEC_ID_INDEO4,
870     .priv_data_size = sizeof(IVI4DecContext),
871     .init           = decode_init,
872     .close          = decode_close,
873     .decode         = decode_frame,
874     .long_name      = NULL_IF_CONFIG_SMALL("Intel Indeo Video Interactive 4"),
875 };