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