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