]> git.sesse.net Git - ffmpeg/blob - libavcodec/indeo5.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / indeo5.c
1 /*
2  * Indeo Video Interactive v5 compatible decoder
3  * Copyright (c) 2009 Maxim Poliakovski
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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 5 decoder
25  *
26  * Indeo5 data is usually transported within .avi or .mov files.
27  * Known FOURCCs: 'IV50'
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 "indeo5data.h"
37
38 /**
39  *  Indeo5 frame types.
40  */
41 enum {
42     FRAMETYPE_INTRA       = 0,
43     FRAMETYPE_INTER       = 1,  ///< non-droppable P-frame
44     FRAMETYPE_INTER_SCAL  = 2,  ///< droppable P-frame used in the scalability mode
45     FRAMETYPE_INTER_NOREF = 3,  ///< droppable P-frame
46     FRAMETYPE_NULL        = 4   ///< empty frame with no data
47 };
48
49 #define IVI5_PIC_SIZE_ESC       15
50
51 #define IVI5_IS_PROTECTED       0x20
52
53 typedef struct {
54     GetBitContext   gb;
55     AVFrame         frame;
56     RVMapDesc       rvmap_tabs[9];   ///< local corrected copy of the static rvmap tables
57     IVIPlaneDesc    planes[3];       ///< color planes
58     const uint8_t   *frame_data;     ///< input frame data pointer
59     int             buf_switch;      ///< used to switch between three buffers
60     int             inter_scal;      ///< signals a sequence of scalable inter frames
61     int             dst_buf;         ///< buffer index for the currently decoded frame
62     int             ref_buf;         ///< inter frame reference buffer index
63     int             ref2_buf;        ///< temporal storage for switching buffers
64     uint32_t        frame_size;      ///< frame size in bytes
65     int             frame_type;
66     int             prev_frame_type; ///< frame type of the previous frame
67     int             frame_num;
68     uint32_t        pic_hdr_size;    ///< picture header size in bytes
69     uint8_t         frame_flags;
70     uint16_t        checksum;        ///< frame checksum
71
72     IVIHuffTab      mb_vlc;          ///< vlc table for decoding macroblock data
73
74     uint16_t        gop_hdr_size;
75     uint8_t         gop_flags;
76     int             is_scalable;
77     uint32_t        lock_word;
78     IVIPicConfig    pic_conf;
79
80     int gop_invalid;
81     int buf_invalid[3];
82 } IVI5DecContext;
83
84
85 /**
86  *  Decode Indeo5 GOP (Group of pictures) header.
87  *  This header is present in key frames only.
88  *  It defines parameters for all frames in a GOP.
89  *
90  *  @param[in,out] ctx    ptr to the decoder context
91  *  @param[in]     avctx  ptr to the AVCodecContext
92  *  @return         result code: 0 = OK, -1 = error
93  */
94 static int decode_gop_header(IVI5DecContext *ctx, AVCodecContext *avctx)
95 {
96     int             result, i, p, tile_size, pic_size_indx, mb_size, blk_size, is_scalable;
97     int             quant_mat, blk_size_changed = 0;
98     IVIBandDesc     *band, *band1, *band2;
99     IVIPicConfig    pic_conf;
100
101     ctx->gop_flags = get_bits(&ctx->gb, 8);
102
103     ctx->gop_hdr_size = (ctx->gop_flags & 1) ? get_bits(&ctx->gb, 16) : 0;
104
105     if (ctx->gop_flags & IVI5_IS_PROTECTED)
106         ctx->lock_word = get_bits_long(&ctx->gb, 32);
107
108     tile_size = (ctx->gop_flags & 0x40) ? 64 << get_bits(&ctx->gb, 2) : 0;
109     if (tile_size > 256) {
110         av_log(avctx, AV_LOG_ERROR, "Invalid tile size: %d\n", tile_size);
111         return -1;
112     }
113
114     /* decode number of wavelet bands */
115     /* num_levels * 3 + 1 */
116     pic_conf.luma_bands   = get_bits(&ctx->gb, 2) * 3 + 1;
117     pic_conf.chroma_bands = get_bits1(&ctx->gb)   * 3 + 1;
118     is_scalable = pic_conf.luma_bands != 1 || pic_conf.chroma_bands != 1;
119     if (is_scalable && (pic_conf.luma_bands != 4 || pic_conf.chroma_bands != 1)) {
120         av_log(avctx, AV_LOG_ERROR, "Scalability: unsupported subdivision! Luma bands: %d, chroma bands: %d\n",
121                pic_conf.luma_bands, pic_conf.chroma_bands);
122         return -1;
123     }
124
125     pic_size_indx = get_bits(&ctx->gb, 4);
126     if (pic_size_indx == IVI5_PIC_SIZE_ESC) {
127         pic_conf.pic_height = get_bits(&ctx->gb, 13);
128         pic_conf.pic_width  = get_bits(&ctx->gb, 13);
129     } else {
130         pic_conf.pic_height = ivi5_common_pic_sizes[pic_size_indx * 2 + 1] << 2;
131         pic_conf.pic_width  = ivi5_common_pic_sizes[pic_size_indx * 2    ] << 2;
132     }
133
134     if (ctx->gop_flags & 2) {
135         av_log(avctx, AV_LOG_ERROR, "YV12 picture format not supported!\n");
136         return -1;
137     }
138
139     pic_conf.chroma_height = (pic_conf.pic_height + 3) >> 2;
140     pic_conf.chroma_width  = (pic_conf.pic_width  + 3) >> 2;
141
142     if (!tile_size) {
143         pic_conf.tile_height = pic_conf.pic_height;
144         pic_conf.tile_width  = pic_conf.pic_width;
145     } else {
146         pic_conf.tile_height = pic_conf.tile_width = tile_size;
147     }
148
149     /* check if picture layout was changed and reallocate buffers */
150     if (ivi_pic_config_cmp(&pic_conf, &ctx->pic_conf)) {
151         result = ff_ivi_init_planes(ctx->planes, &pic_conf);
152         if (result) {
153             av_log(avctx, AV_LOG_ERROR, "Couldn't reallocate color planes!\n");
154             return -1;
155         }
156         ctx->pic_conf = pic_conf;
157         ctx->is_scalable = is_scalable;
158         blk_size_changed = 1; /* force reallocation of the internal structures */
159     }
160
161     for (p = 0; p <= 1; p++) {
162         for (i = 0; i < (!p ? pic_conf.luma_bands : pic_conf.chroma_bands); i++) {
163             band = &ctx->planes[p].bands[i];
164
165             band->is_halfpel = get_bits1(&ctx->gb);
166
167             mb_size  = get_bits1(&ctx->gb);
168             blk_size = 8 >> get_bits1(&ctx->gb);
169             mb_size  = blk_size << !mb_size;
170
171             if (p==0 && blk_size==4) {
172                 av_log(avctx, AV_LOG_ERROR, "4x4 luma blocks are unsupported!\n");
173                 return AVERROR_PATCHWELCOME;
174             }
175
176             blk_size_changed = mb_size != band->mb_size || blk_size != band->blk_size;
177             if (blk_size_changed) {
178                 band->mb_size  = mb_size;
179                 band->blk_size = blk_size;
180             }
181
182             if (get_bits1(&ctx->gb)) {
183                 av_log(avctx, AV_LOG_ERROR, "Extended transform info encountered!\n");
184                 return -1;
185             }
186
187             /* select transform function and scan pattern according to plane and band number */
188             switch ((p << 2) + i) {
189             case 0:
190                 band->inv_transform = ff_ivi_inverse_slant_8x8;
191                 band->dc_transform  = ff_ivi_dc_slant_2d;
192                 band->scan          = ff_zigzag_direct;
193                 band->transform_size= 8;
194                 break;
195
196             case 1:
197                 band->inv_transform = ff_ivi_row_slant8;
198                 band->dc_transform  = ff_ivi_dc_row_slant;
199                 band->scan          = ff_ivi_vertical_scan_8x8;
200                 band->transform_size= 8;
201                 break;
202
203             case 2:
204                 band->inv_transform = ff_ivi_col_slant8;
205                 band->dc_transform  = ff_ivi_dc_col_slant;
206                 band->scan          = ff_ivi_horizontal_scan_8x8;
207                 band->transform_size= 8;
208                 break;
209
210             case 3:
211                 band->inv_transform = ff_ivi_put_pixels_8x8;
212                 band->dc_transform  = ff_ivi_put_dc_pixel_8x8;
213                 band->scan          = ff_ivi_horizontal_scan_8x8;
214                 band->transform_size= 8;
215                 break;
216
217             case 4:
218                 band->inv_transform = ff_ivi_inverse_slant_4x4;
219                 band->dc_transform  = ff_ivi_dc_slant_2d;
220                 band->scan          = ff_ivi_direct_scan_4x4;
221                 band->transform_size= 4;
222                 break;
223             }
224
225             band->is_2d_trans = band->inv_transform == ff_ivi_inverse_slant_8x8 ||
226                                 band->inv_transform == ff_ivi_inverse_slant_4x4;
227
228             /* select dequant matrix according to plane and band number */
229             if (!p) {
230                 quant_mat = (pic_conf.luma_bands > 1) ? i+1 : 0;
231             } else {
232                 quant_mat = 5;
233             }
234
235             if (band->blk_size == 8) {
236                 band->intra_base  = &ivi5_base_quant_8x8_intra[quant_mat][0];
237                 band->inter_base  = &ivi5_base_quant_8x8_inter[quant_mat][0];
238                 band->intra_scale = &ivi5_scale_quant_8x8_intra[quant_mat][0];
239                 band->inter_scale = &ivi5_scale_quant_8x8_inter[quant_mat][0];
240             } else {
241                 band->intra_base  = ivi5_base_quant_4x4_intra;
242                 band->inter_base  = ivi5_base_quant_4x4_inter;
243                 band->intra_scale = ivi5_scale_quant_4x4_intra;
244                 band->inter_scale = ivi5_scale_quant_4x4_inter;
245             }
246
247             if (get_bits(&ctx->gb, 2)) {
248                 av_log(avctx, AV_LOG_ERROR, "End marker missing!\n");
249                 return -1;
250             }
251         }
252     }
253
254     /* copy chroma parameters into the 2nd chroma plane */
255     for (i = 0; i < pic_conf.chroma_bands; i++) {
256         band1 = &ctx->planes[1].bands[i];
257         band2 = &ctx->planes[2].bands[i];
258
259         band2->width         = band1->width;
260         band2->height        = band1->height;
261         band2->mb_size       = band1->mb_size;
262         band2->blk_size      = band1->blk_size;
263         band2->is_halfpel    = band1->is_halfpel;
264         band2->intra_base    = band1->intra_base;
265         band2->inter_base    = band1->inter_base;
266         band2->intra_scale   = band1->intra_scale;
267         band2->inter_scale   = band1->inter_scale;
268         band2->scan          = band1->scan;
269         band2->inv_transform = band1->inv_transform;
270         band2->dc_transform  = band1->dc_transform;
271         band2->is_2d_trans   = band1->is_2d_trans;
272         band2->transform_size= band1->transform_size;
273     }
274
275     /* reallocate internal structures if needed */
276     if (blk_size_changed) {
277         result = ff_ivi_init_tiles(ctx->planes, pic_conf.tile_width,
278                                    pic_conf.tile_height);
279         if (result) {
280             av_log(avctx, AV_LOG_ERROR,
281                    "Couldn't reallocate internal structures!\n");
282             return -1;
283         }
284     }
285
286     if (ctx->gop_flags & 8) {
287         if (get_bits(&ctx->gb, 3)) {
288             av_log(avctx, AV_LOG_ERROR, "Alignment bits are not zero!\n");
289             return -1;
290         }
291
292         if (get_bits1(&ctx->gb))
293             skip_bits_long(&ctx->gb, 24); /* skip transparency fill color */
294     }
295
296     align_get_bits(&ctx->gb);
297
298     skip_bits(&ctx->gb, 23); /* FIXME: unknown meaning */
299
300     /* skip GOP extension if any */
301     if (get_bits1(&ctx->gb)) {
302         do {
303             i = get_bits(&ctx->gb, 16);
304         } while (i & 0x8000);
305     }
306
307     align_get_bits(&ctx->gb);
308
309     return 0;
310 }
311
312
313 /**
314  *  Skip a header extension.
315  *
316  *  @param[in,out]  gb  the GetBit context
317  */
318 static inline void skip_hdr_extension(GetBitContext *gb)
319 {
320     int i, len;
321
322     do {
323         len = get_bits(gb, 8);
324         for (i = 0; i < len; i++) skip_bits(gb, 8);
325     } while(len);
326 }
327
328
329 /**
330  *  Decode Indeo5 picture header.
331  *
332  *  @param[in,out]  ctx    ptr to the decoder context
333  *  @param[in]      avctx  ptr to the AVCodecContext
334  *  @return         result code: 0 = OK, -1 = error
335  */
336 static int decode_pic_hdr(IVI5DecContext *ctx, AVCodecContext *avctx)
337 {
338     if (get_bits(&ctx->gb, 5) != 0x1F) {
339         av_log(avctx, AV_LOG_ERROR, "Invalid picture start code!\n");
340         return -1;
341     }
342
343     ctx->prev_frame_type = ctx->frame_type;
344     ctx->frame_type      = get_bits(&ctx->gb, 3);
345     if (ctx->frame_type >= 5) {
346         av_log(avctx, AV_LOG_ERROR, "Invalid frame type: %d \n", ctx->frame_type);
347         return -1;
348     }
349
350     ctx->frame_num = get_bits(&ctx->gb, 8);
351
352     if (ctx->frame_type == FRAMETYPE_INTRA) {
353         ctx->gop_invalid = 1;
354         if (decode_gop_header(ctx, avctx))
355             return -1;
356         ctx->gop_invalid = 0;
357     }
358
359     if (ctx->frame_type == FRAMETYPE_INTER_SCAL && !ctx->is_scalable) {
360         av_log(avctx, AV_LOG_ERROR, "Scalable inter frame in non scaleable stream\n");
361         ctx->frame_type = FRAMETYPE_INTER;
362         return AVERROR_INVALIDDATA;
363     }
364
365     if (ctx->frame_type != FRAMETYPE_NULL) {
366         ctx->frame_flags = get_bits(&ctx->gb, 8);
367
368         ctx->pic_hdr_size = (ctx->frame_flags & 1) ? get_bits_long(&ctx->gb, 24) : 0;
369
370         ctx->checksum = (ctx->frame_flags & 0x10) ? get_bits(&ctx->gb, 16) : 0;
371
372         /* skip unknown extension if any */
373         if (ctx->frame_flags & 0x20)
374             skip_hdr_extension(&ctx->gb); /* XXX: untested */
375
376         /* decode macroblock huffman codebook */
377         if (ff_ivi_dec_huff_desc(&ctx->gb, ctx->frame_flags & 0x40, IVI_MB_HUFF, &ctx->mb_vlc, avctx))
378             return -1;
379
380         skip_bits(&ctx->gb, 3); /* FIXME: unknown meaning! */
381     }
382
383     align_get_bits(&ctx->gb);
384
385     return 0;
386 }
387
388
389 /**
390  *  Decode Indeo5 band header.
391  *
392  *  @param[in,out]  ctx    ptr to the decoder context
393  *  @param[in,out]  band   ptr to the band descriptor
394  *  @param[in]      avctx  ptr to the AVCodecContext
395  *  @return         result code: 0 = OK, -1 = error
396  */
397 static int decode_band_hdr(IVI5DecContext *ctx, IVIBandDesc *band,
398                            AVCodecContext *avctx)
399 {
400     int         i;
401     uint8_t     band_flags;
402
403     band_flags = get_bits(&ctx->gb, 8);
404
405     if (band_flags & 1) {
406         band->is_empty = 1;
407         return 0;
408     }
409
410     band->data_size = (ctx->frame_flags & 0x80) ? get_bits_long(&ctx->gb, 24) : 0;
411
412     band->inherit_mv     = band_flags & 2;
413     band->inherit_qdelta = band_flags & 8;
414     band->qdelta_present = band_flags & 4;
415     if (!band->qdelta_present) band->inherit_qdelta = 1;
416
417     /* decode rvmap probability corrections if any */
418     band->num_corr = 0; /* there are no corrections */
419     if (band_flags & 0x10) {
420         band->num_corr = get_bits(&ctx->gb, 8); /* get number of correction pairs */
421         if (band->num_corr > 61) {
422             av_log(avctx, AV_LOG_ERROR, "Too many corrections: %d\n",
423                    band->num_corr);
424             return -1;
425         }
426
427         /* read correction pairs */
428         for (i = 0; i < band->num_corr * 2; i++)
429             band->corr[i] = get_bits(&ctx->gb, 8);
430     }
431
432     /* select appropriate rvmap table for this band */
433     band->rvmap_sel = (band_flags & 0x40) ? get_bits(&ctx->gb, 3) : 8;
434
435     /* decode block huffman codebook */
436     if (ff_ivi_dec_huff_desc(&ctx->gb, band_flags & 0x80, IVI_BLK_HUFF, &band->blk_vlc, avctx))
437         return -1;
438
439     band->checksum_present = get_bits1(&ctx->gb);
440     if (band->checksum_present)
441         band->checksum = get_bits(&ctx->gb, 16);
442
443     band->glob_quant = get_bits(&ctx->gb, 5);
444
445     /* skip unknown extension if any */
446     if (band_flags & 0x20) { /* XXX: untested */
447         align_get_bits(&ctx->gb);
448         skip_hdr_extension(&ctx->gb);
449     }
450
451     align_get_bits(&ctx->gb);
452
453     return 0;
454 }
455
456
457 /**
458  *  Decode info (block type, cbp, quant delta, motion vector)
459  *  for all macroblocks in the current tile.
460  *
461  *  @param[in,out]  ctx    ptr to the decoder context
462  *  @param[in,out]  band   ptr to the band descriptor
463  *  @param[in,out]  tile   ptr to the tile descriptor
464  *  @param[in]      avctx  ptr to the AVCodecContext
465  *  @return         result code: 0 = OK, -1 = error
466  */
467 static int decode_mb_info(IVI5DecContext *ctx, IVIBandDesc *band,
468                           IVITile *tile, AVCodecContext *avctx)
469 {
470     int         x, y, mv_x, mv_y, mv_delta, offs, mb_offset,
471                 mv_scale, blks_per_mb, s;
472     IVIMbInfo   *mb, *ref_mb;
473     int         row_offset = band->mb_size * band->pitch;
474
475     mb     = tile->mbs;
476     ref_mb = tile->ref_mbs;
477     offs   = tile->ypos * band->pitch + tile->xpos;
478
479     if (!ref_mb &&
480         ((band->qdelta_present && band->inherit_qdelta) || band->inherit_mv))
481         return AVERROR_INVALIDDATA;
482
483     if( tile->num_MBs != IVI_MBs_PER_TILE(tile->width, tile->height, band->mb_size) ){
484         av_log(avctx, AV_LOG_ERROR, "allocated tile size %d mismatches parameters %d\n",
485                tile->num_MBs, IVI_MBs_PER_TILE(tile->width, tile->height, band->mb_size));
486         return AVERROR_INVALIDDATA;
487     }
488
489     /* scale factor for motion vectors */
490     mv_scale = (ctx->planes[0].bands[0].mb_size >> 3) - (band->mb_size >> 3);
491     mv_x = mv_y = 0;
492
493     for (y = tile->ypos; y < (tile->ypos + tile->height); y += band->mb_size) {
494         mb_offset = offs;
495
496         for (x = tile->xpos; x < (tile->xpos + tile->width); x += band->mb_size) {
497             mb->xpos     = x;
498             mb->ypos     = y;
499             mb->buf_offs = mb_offset;
500
501             if (get_bits1(&ctx->gb)) {
502                 if (ctx->frame_type == FRAMETYPE_INTRA) {
503                     av_log(avctx, AV_LOG_ERROR, "Empty macroblock in an INTRA picture!\n");
504                     return -1;
505                 }
506                 mb->type = 1; /* empty macroblocks are always INTER */
507                 mb->cbp  = 0; /* all blocks are empty */
508
509                 mb->q_delta = 0;
510                 if (!band->plane && !band->band_num && (ctx->frame_flags & 8)) {
511                     mb->q_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
512                                            IVI_VLC_BITS, 1);
513                     mb->q_delta = IVI_TOSIGNED(mb->q_delta);
514                 }
515
516                 mb->mv_x = mb->mv_y = 0; /* no motion vector coded */
517                 if (band->inherit_mv && ref_mb){
518                     /* motion vector inheritance */
519                     if (mv_scale) {
520                         mb->mv_x = ivi_scale_mv(ref_mb->mv_x, mv_scale);
521                         mb->mv_y = ivi_scale_mv(ref_mb->mv_y, mv_scale);
522                     } else {
523                         mb->mv_x = ref_mb->mv_x;
524                         mb->mv_y = ref_mb->mv_y;
525                     }
526                 }
527             } else {
528                 if (band->inherit_mv && ref_mb) {
529                     mb->type = ref_mb->type; /* copy mb_type from corresponding reference mb */
530                 } else if (ctx->frame_type == FRAMETYPE_INTRA) {
531                     mb->type = 0; /* mb_type is always INTRA for intra-frames */
532                 } else {
533                     mb->type = get_bits1(&ctx->gb);
534                 }
535
536                 blks_per_mb = band->mb_size != band->blk_size ? 4 : 1;
537                 mb->cbp = get_bits(&ctx->gb, blks_per_mb);
538
539                 mb->q_delta = 0;
540                 if (band->qdelta_present) {
541                     if (band->inherit_qdelta) {
542                         if (ref_mb) mb->q_delta = ref_mb->q_delta;
543                     } else if (mb->cbp || (!band->plane && !band->band_num &&
544                                            (ctx->frame_flags & 8))) {
545                         mb->q_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
546                                                IVI_VLC_BITS, 1);
547                         mb->q_delta = IVI_TOSIGNED(mb->q_delta);
548                     }
549                 }
550
551                 if (!mb->type) {
552                     mb->mv_x = mb->mv_y = 0; /* there is no motion vector in intra-macroblocks */
553                 } else {
554                     if (band->inherit_mv && ref_mb){
555                         /* motion vector inheritance */
556                         if (mv_scale) {
557                             mb->mv_x = ivi_scale_mv(ref_mb->mv_x, mv_scale);
558                             mb->mv_y = ivi_scale_mv(ref_mb->mv_y, mv_scale);
559                         } else {
560                             mb->mv_x = ref_mb->mv_x;
561                             mb->mv_y = ref_mb->mv_y;
562                         }
563                     } else {
564                         /* decode motion vector deltas */
565                         mv_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
566                                             IVI_VLC_BITS, 1);
567                         mv_y += IVI_TOSIGNED(mv_delta);
568                         mv_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
569                                             IVI_VLC_BITS, 1);
570                         mv_x += IVI_TOSIGNED(mv_delta);
571                         mb->mv_x = mv_x;
572                         mb->mv_y = mv_y;
573                     }
574                 }
575             }
576
577             s= band->is_halfpel;
578             if (mb->type)
579             if ( x +  (mb->mv_x   >>s) +                 (y+               (mb->mv_y   >>s))*band->pitch < 0 ||
580                  x + ((mb->mv_x+s)>>s) + band->mb_size - 1
581                    + (y+band->mb_size - 1 +((mb->mv_y+s)>>s))*band->pitch > band->bufsize - 1) {
582                 av_log(avctx, AV_LOG_ERROR, "motion vector %d %d outside reference\n", x*s + mb->mv_x, y*s + mb->mv_y);
583                 return AVERROR_INVALIDDATA;
584             }
585
586             mb++;
587             if (ref_mb)
588                 ref_mb++;
589             mb_offset += band->mb_size;
590         }
591
592         offs += row_offset;
593     }
594
595     align_get_bits(&ctx->gb);
596
597     return 0;
598 }
599
600
601 /**
602  *  Decode an Indeo5 band.
603  *
604  *  @param[in,out]  ctx    ptr to the decoder context
605  *  @param[in,out]  band   ptr to the band descriptor
606  *  @param[in]      avctx  ptr to the AVCodecContext
607  *  @return         result code: 0 = OK, -1 = error
608  */
609 static int decode_band(IVI5DecContext *ctx, int plane_num,
610                        IVIBandDesc *band, AVCodecContext *avctx)
611 {
612     int         result, i, t, idx1, idx2, pos;
613     IVITile     *tile;
614
615     band->buf     = band->bufs[ctx->dst_buf];
616     band->ref_buf = band->bufs[ctx->ref_buf];
617     band->data_ptr = ctx->frame_data + (get_bits_count(&ctx->gb) >> 3);
618
619     result = decode_band_hdr(ctx, band, avctx);
620     if (result) {
621         av_log(avctx, AV_LOG_ERROR, "Error while decoding band header: %d\n",
622                result);
623         return -1;
624     }
625
626     if (band->is_empty) {
627         av_log(avctx, AV_LOG_ERROR, "Empty band encountered!\n");
628         return -1;
629     }
630
631     band->rv_map = &ctx->rvmap_tabs[band->rvmap_sel];
632
633     /* apply corrections to the selected rvmap table if present */
634     for (i = 0; i < band->num_corr; i++) {
635         idx1 = band->corr[i*2];
636         idx2 = band->corr[i*2+1];
637         FFSWAP(uint8_t, band->rv_map->runtab[idx1], band->rv_map->runtab[idx2]);
638         FFSWAP(int16_t, band->rv_map->valtab[idx1], band->rv_map->valtab[idx2]);
639     }
640
641     pos = get_bits_count(&ctx->gb);
642
643     for (t = 0; t < band->num_tiles; t++) {
644         tile = &band->tiles[t];
645
646         tile->is_empty = get_bits1(&ctx->gb);
647         if (tile->is_empty) {
648             ff_ivi_process_empty_tile(avctx, band, tile,
649                                       (ctx->planes[0].bands[0].mb_size >> 3) - (band->mb_size >> 3));
650         } else {
651             tile->data_size = ff_ivi_dec_tile_data_size(&ctx->gb);
652
653             result = decode_mb_info(ctx, band, tile, avctx);
654             if (result < 0)
655                 break;
656
657             result = ff_ivi_decode_blocks(&ctx->gb, band, tile);
658             if (result < 0 || (get_bits_count(&ctx->gb) - pos) >> 3 != tile->data_size) {
659                 av_log(avctx, AV_LOG_ERROR, "Corrupted tile data encountered!\n");
660                 break;
661             }
662             pos += tile->data_size << 3; // skip to next tile
663         }
664     }
665
666     /* restore the selected rvmap table by applying its corrections in reverse order */
667     for (i = band->num_corr-1; i >= 0; i--) {
668         idx1 = band->corr[i*2];
669         idx2 = band->corr[i*2+1];
670         FFSWAP(uint8_t, band->rv_map->runtab[idx1], band->rv_map->runtab[idx2]);
671         FFSWAP(int16_t, band->rv_map->valtab[idx1], band->rv_map->valtab[idx2]);
672     }
673
674 #ifdef DEBUG
675     if (band->checksum_present) {
676         uint16_t chksum = ivi_calc_band_checksum(band);
677         if (chksum != band->checksum) {
678             av_log(avctx, AV_LOG_ERROR,
679                    "Band checksum mismatch! Plane %d, band %d, received: %x, calculated: %x\n",
680                    band->plane, band->band_num, band->checksum, chksum);
681         }
682     }
683 #endif
684
685     align_get_bits(&ctx->gb);
686
687     return result;
688 }
689
690
691 /**
692  *  Switch buffers.
693  *
694  *  @param[in,out] ctx  ptr to the decoder context
695  */
696 static void switch_buffers(IVI5DecContext *ctx)
697 {
698     switch (ctx->prev_frame_type) {
699     case FRAMETYPE_INTRA:
700     case FRAMETYPE_INTER:
701         ctx->buf_switch ^= 1;
702         ctx->dst_buf = ctx->buf_switch;
703         ctx->ref_buf = ctx->buf_switch ^ 1;
704         break;
705     case FRAMETYPE_INTER_SCAL:
706         if (!ctx->inter_scal) {
707             ctx->ref2_buf   = 2;
708             ctx->inter_scal = 1;
709         }
710         FFSWAP(int, ctx->dst_buf, ctx->ref2_buf);
711         ctx->ref_buf = ctx->ref2_buf;
712         break;
713     case FRAMETYPE_INTER_NOREF:
714         break;
715     }
716
717     switch (ctx->frame_type) {
718     case FRAMETYPE_INTRA:
719         ctx->buf_switch = 0;
720         /* FALLTHROUGH */
721     case FRAMETYPE_INTER:
722         ctx->inter_scal = 0;
723         ctx->dst_buf = ctx->buf_switch;
724         ctx->ref_buf = ctx->buf_switch ^ 1;
725         break;
726     case FRAMETYPE_INTER_SCAL:
727     case FRAMETYPE_INTER_NOREF:
728     case FRAMETYPE_NULL:
729         break;
730     }
731 }
732
733
734 /**
735  *  Initialize Indeo5 decoder.
736  */
737 static av_cold int decode_init(AVCodecContext *avctx)
738 {
739     IVI5DecContext  *ctx = avctx->priv_data;
740     int             result;
741
742     ff_ivi_init_static_vlc();
743
744     /* copy rvmap tables in our context so we can apply changes to them */
745     memcpy(ctx->rvmap_tabs, ff_ivi_rvmap_tabs, sizeof(ff_ivi_rvmap_tabs));
746
747     /* set the initial picture layout according to the basic profile:
748        there is only one band per plane (no scalability), only one tile (no local decoding)
749        and picture format = YVU9 */
750     ctx->pic_conf.pic_width     = avctx->width;
751     ctx->pic_conf.pic_height    = avctx->height;
752     ctx->pic_conf.chroma_width  = (avctx->width  + 3) >> 2;
753     ctx->pic_conf.chroma_height = (avctx->height + 3) >> 2;
754     ctx->pic_conf.tile_width    = avctx->width;
755     ctx->pic_conf.tile_height   = avctx->height;
756     ctx->pic_conf.luma_bands    = ctx->pic_conf.chroma_bands = 1;
757
758     avcodec_get_frame_defaults(&ctx->frame);
759
760     result = ff_ivi_init_planes(ctx->planes, &ctx->pic_conf);
761     if (result) {
762         av_log(avctx, AV_LOG_ERROR, "Couldn't allocate color planes!\n");
763         return -1;
764     }
765
766     ctx->buf_switch = 0;
767     ctx->inter_scal = 0;
768
769     avctx->pix_fmt = PIX_FMT_YUV410P;
770
771     return 0;
772 }
773
774
775 /**
776  *  main decoder function
777  */
778 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
779                         AVPacket *avpkt)
780 {
781     IVI5DecContext  *ctx = avctx->priv_data;
782     const uint8_t   *buf = avpkt->data;
783     int             buf_size = avpkt->size;
784     int             result, p, b;
785
786     init_get_bits(&ctx->gb, buf, buf_size * 8);
787     ctx->frame_data = buf;
788     ctx->frame_size = buf_size;
789
790     result = decode_pic_hdr(ctx, avctx);
791     if (result || ctx->gop_invalid) {
792         av_log(avctx, AV_LOG_ERROR,
793                "Error while decoding picture header: %d\n", result);
794         return -1;
795     }
796
797     if (ctx->gop_flags & IVI5_IS_PROTECTED) {
798         av_log(avctx, AV_LOG_ERROR, "Password-protected clip!\n");
799         return -1;
800     }
801
802     switch_buffers(ctx);
803
804     //{ START_TIMER;
805
806     if (ctx->frame_type != FRAMETYPE_NULL) {
807         ctx->buf_invalid[ctx->dst_buf] = 1;
808         for (p = 0; p < 3; p++) {
809             for (b = 0; b < ctx->planes[p].num_bands; b++) {
810                 result = decode_band(ctx, p, &ctx->planes[p].bands[b], avctx);
811                 if (result) {
812                     av_log(avctx, AV_LOG_ERROR,
813                            "Error while decoding band: %d, plane: %d\n", b, p);
814                     return -1;
815                 }
816             }
817         }
818         ctx->buf_invalid[ctx->dst_buf] = 0;
819     }
820     if (ctx->buf_invalid[ctx->dst_buf])
821         return -1;
822
823     //STOP_TIMER("decode_planes"); }
824
825     if (ctx->frame.data[0])
826         avctx->release_buffer(avctx, &ctx->frame);
827
828     if(   avctx->width  != ctx->planes[0].width
829        || avctx->height != ctx->planes[0].height)
830         avcodec_set_dimensions(avctx, ctx->planes[0].width, ctx->planes[0].height);
831
832     ctx->frame.reference = 0;
833     if (avctx->get_buffer(avctx, &ctx->frame) < 0) {
834         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
835         return -1;
836     }
837
838     if (ctx->is_scalable) {
839         ff_ivi_recompose53 (&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0], 4);
840     } else {
841         ff_ivi_output_plane(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0]);
842     }
843
844     ff_ivi_output_plane(&ctx->planes[2], ctx->frame.data[1], ctx->frame.linesize[1]);
845     ff_ivi_output_plane(&ctx->planes[1], ctx->frame.data[2], ctx->frame.linesize[2]);
846
847     *data_size = sizeof(AVFrame);
848     *(AVFrame*)data = ctx->frame;
849
850     return buf_size;
851 }
852
853
854 /**
855  *  Close Indeo5 decoder and clean up its context.
856  */
857 static av_cold int decode_close(AVCodecContext *avctx)
858 {
859     IVI5DecContext *ctx = avctx->priv_data;
860
861     ff_ivi_free_buffers(&ctx->planes[0]);
862
863     if (ctx->mb_vlc.cust_tab.table)
864         ff_free_vlc(&ctx->mb_vlc.cust_tab);
865
866     if (ctx->frame.data[0])
867         avctx->release_buffer(avctx, &ctx->frame);
868
869     return 0;
870 }
871
872
873 AVCodec ff_indeo5_decoder = {
874     .name           = "indeo5",
875     .type           = AVMEDIA_TYPE_VIDEO,
876     .id             = CODEC_ID_INDEO5,
877     .priv_data_size = sizeof(IVI5DecContext),
878     .init           = decode_init,
879     .close          = decode_close,
880     .decode         = decode_frame,
881     .long_name      = NULL_IF_CONFIG_SMALL("Intel Indeo Video Interactive 5"),
882 };