aboutsummaryrefslogtreecommitdiff
path: root/image/codecs/indeo/indeo.h
blob: c9d556a92fef8cfa0226f08764138b2304c9ef9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include "common/scummsys.h"
#include "graphics/managed_surface.h"
#include "image/codecs/codec.h"

/* Common structures, macros, and base class shared by both Indeo4 and 
 * Indeo5 decoders, derived from ffmpeg. We don't currently support Indeo5 
 * decoding, but just in case we eventually need it, this is kept as a separate
 * file like it is in ffmpeg.
 *
 * Original copyright note: * Intel Indeo 4 (IV41, IV42, etc.) video decoder for ffmpeg
 * written, produced, and directed by Alan Smithee
 */

#ifndef IMAGE_CODECS_INDEO_INDEO_H
#define IMAGE_CODECS_INDEO_INDEO_H

#include "image/codecs/indeo/get_bits.h"
#include "image/codecs/indeo/vlc.h"

namespace Image {
namespace Indeo {

/**
 *  Indeo 4 frame types.
 */
enum {
    IVI4_FRAMETYPE_INTRA       = 0,
    IVI4_FRAMETYPE_INTRA1      = 1,  ///< intra frame with slightly different bitstream coding
    IVI4_FRAMETYPE_INTER       = 2,  ///< non-droppable P-frame
    IVI4_FRAMETYPE_BIDIR       = 3,  ///< bidirectional frame
    IVI4_FRAMETYPE_INTER_NOREF = 4,  ///< droppable P-frame
    IVI4_FRAMETYPE_NULL_FIRST  = 5,  ///< empty frame with no data
    IVI4_FRAMETYPE_NULL_LAST   = 6   ///< empty frame with no data
};

enum {
    IVI_MB_HUFF   = 0,      /// Huffman table is used for coding macroblocks
    IVI_BLK_HUFF  = 1       /// Huffman table is used for coding blocks
};

/**
 *  Declare inverse transform function types
 */
typedef void (InvTransformPtr)(const int32 *in, int16 *out, uint32 pitch, const uint8 *flags);
typedef void (DCTransformPtr) (const int32 *in, int16 *out, uint32 pitch, int blk_size);

typedef void(*ivi_mc_func) (int16 *buf, const int16 *ref_buf,
	uint32 pitch, int mc_type);
typedef void(*ivi_mc_avg_func) (int16 *buf, const int16 *ref_buf1,
	const int16 *ref_buf2,
	uint32 pitch, int mc_type, int mc_type2);

#define IVI_VLC_BITS 13		///< max number of bits of the ivi's huffman codes
#define IVI5_IS_PROTECTED 0x20

/**
 * convert unsigned values into signed ones (the sign is in the LSB)
 */
#define IVI_TOSIGNED(val) (-(((val) >> 1) ^ -((val) & 1)))

/**
 * calculate number of macroblocks in a tile
 */
#define IVI_MBs_PER_TILE(tile_width, tile_height, mb_size) \
    ((((tile_width) + (mb_size) - 1) / (mb_size)) * (((tile_height) + (mb_size) - 1) / (mb_size)))

/**
 *  huffman codebook descriptor
 */
struct IVIHuffDesc {
    int32     num_rows;
    uint8     xbits[16];

	/*
	 *  Generate a huffman codebook from the given descriptor
	 *  and convert it into the FFmpeg VLC table.
	 *
	 *  @param[out]  vlc   where to place the generated VLC table
	 *  @param[in]   flag  flag: 1 - for static or 0 for dynamic tables
	 *  @return     result code: 0 - OK, -1 = error (invalid codebook descriptor)
	 */
	int ivi_create_huff_from_desc(VLC *vlc, int flag) const;

	/*
	 *  Compare two huffman codebook descriptors.
	 *
	 *  @param[in]  desc2  ptr to the 2nd descriptor to compare
	 *  @return         comparison result: 0 - equal, 1 - not equal
	 */
	bool ivi_huff_desc_cmp(const IVIHuffDesc *desc2) const;

	/*
	 *  Copy huffman codebook descriptors.
	 *
	 *  @param[in]   src  ptr to the source descriptor
	 */
	void ivi_huff_desc_copy(const IVIHuffDesc *src);
};

struct IVI45DecContext;

/**
 *  macroblock/block huffman table descriptor
 */
struct IVIHuffTab {
public:
	int32	tab_sel;    /// index of one of the predefined tables
						/// or "7" for custom one
    VLC		*tab;       /// pointer to the table associated with tab_sel

    /// the following are used only when tab_sel == 7
    IVIHuffDesc cust_desc;  /// custom Huffman codebook descriptor
    VLC         cust_tab;   /// vlc table for custom codebook

	/**
	 * Constructor
	 */
	IVIHuffTab();

	int ff_ivi_dec_huff_desc(IVI45DecContext *ctx, int desc_coded, int which_tab);
};

/**
 *  run-value (RLE) table descriptor
 */
struct RVMapDesc {
    uint8     eob_sym; ///< end of block symbol
    uint8     esc_sym; ///< escape symbol
    uint8     runtab[256];
    int8      valtab[256];
};

/**
 *  information for Indeo macroblock (16x16, 8x8 or 4x4)
 */
struct IVIMbInfo {
    int16     xpos;
    int16     ypos;
    uint32    buf_offs; ///< address in the output buffer for this mb
    uint8     type;     ///< macroblock type: 0 - INTRA, 1 - INTER
    uint8     cbp;      ///< coded block pattern
    int8      q_delta;  ///< quant delta
    int8      mv_x;     ///< motion vector (x component)
    int8      mv_y;     ///< motion vector (y component)
    int8      b_mv_x;   ///< second motion vector (x component)
    int8      b_mv_y;   ///< second motion vector (y component)

	IVIMbInfo();
};

/**
 *  information for Indeo tile
 */
struct IVITile {
    int         xpos;
    int         ypos;
    int         width;
    int         height;
    int         mb_size;
    int         is_empty;  ///< = 1 if this tile doesn't contain any data
    int         data_size; ///< size of the data in bytes
    int         num_MBs;   ///< number of macroblocks in this tile
    IVIMbInfo * mbs;      ///< array of macroblock descriptors
    IVIMbInfo * ref_mbs;  ///< ptr to the macroblock descriptors of the reference tile

	IVITile();
};

/**
 *  information for Indeo wavelet band
 */
struct IVIBandDesc {
    int             plane;          ///< plane number this band belongs to
    int             band_num;       ///< band number
    int             width;
    int             height;
    int             aheight;        ///< aligned band height
    const uint8 *   data_ptr;       ///< ptr to the first byte of the band data
    int             data_size;      ///< size of the band data
    int16 *         buf;            ///< pointer to the output buffer for this band
    int16 *         ref_buf;        ///< pointer to the reference frame buffer (for motion compensation)
    int16 *         b_ref_buf;      ///< pointer to the second reference frame buffer (for motion compensation)
    int16 *         bufs[4];        ///< array of pointers to the band buffers
    int             pitch;          ///< pitch associated with the buffers above
    int             is_empty;       ///< = 1 if this band doesn't contain any data
    int             mb_size;        ///< macroblock size
    int             blk_size;       ///< block size
    int             is_halfpel;     ///< precision of the motion compensation: 0 - fullpel, 1 - halfpel
    int             inherit_mv;     ///< tells if motion vector is inherited from reference macroblock
    int             inherit_qdelta; ///< tells if quantiser delta is inherited from reference macroblock
    int             qdelta_present; ///< tells if Qdelta signal is present in the bitstream (Indeo5 only)
    int             quant_mat;      ///< dequant matrix index
    int             glob_quant;     ///< quant base for this band
    const uint8 *   scan;           ///< ptr to the scan pattern
    int             scan_size;      ///< size of the scantable

    IVIHuffTab      blk_vlc;        ///< vlc table for decoding block data

    int             num_corr;       ///< number of correction entries
    uint8           corr[61 * 2];   ///< rvmap correction pairs
    int             rvmap_sel;      ///< rvmap table selector
    RVMapDesc *     rv_map;         ///< ptr to the RLE table for this band
    int             num_tiles;      ///< number of tiles in this band
    IVITile *       tiles;          ///< array of tile descriptors
    InvTransformPtr *inv_transform;
    int             transform_size;
    DCTransformPtr  *dc_transform;
    int             is_2d_trans;    ///< 1 indicates that the two-dimensional inverse transform is used
    int32           checksum;       ///< for debug purposes
    int             checksum_present;
    int             bufsize;        ///< band buffer size in bytes
    const uint16 *  intra_base;     ///< quantization matrix for intra blocks
    const uint16 *  inter_base;     ///< quantization matrix for inter blocks
    const uint8 *   intra_scale;    ///< quantization coefficient for intra blocks
    const uint8 *   inter_scale;    ///< quantization coefficient for inter blocks

	IVIBandDesc();

	int ivi_init_tiles(IVITile *ref_tile, int p, int b, int t_height, int t_width);
};

struct IVIPicConfig {
    uint16    pic_width;
    uint16    pic_height;
    uint16    chroma_width;
    uint16    chroma_height;
    uint16    tile_width;
    uint16    tile_height;
    uint8     luma_bands;
    uint8     chroma_bands;

	IVIPicConfig();

	/**
	 * Compare some properties of two pictures
	 */
	bool ivi_pic_config_cmp(const IVIPicConfig &cfg2);
};

/**
 *  color plane (luma or chroma) information
 */
struct IVIPlaneDesc {
    uint16    width;
    uint16    height;
    uint8     num_bands;  ///< number of bands this plane subdivided into
    IVIBandDesc *bands;   ///< array of band descriptors

	IVIPlaneDesc();

	static int ff_ivi_init_planes(IVIPlaneDesc *planes, const IVIPicConfig *cfg, bool is_indeo4);

	static int ff_ivi_init_tiles(IVIPlaneDesc *planes, int tile_width, int tile_height);

	/*
	 *  Free planes, bands and macroblocks buffers.
	 *
	 *  @param[in]  planes  pointer to the array of the plane descriptors
	 */
	static void ivi_free_buffers(IVIPlaneDesc *planes);
};

struct AVFrame {
	/**
	 * Dimensions
	 */
	int _width, _height;

#define AV_NUM_DATA_POINTERS 3
	/**
	* pointer to the picture/channel planes.
	* This might be different from the first allocated byte
	*
	* Some decoders access areas outside 0,0 - width,height, please
	* see avcodec_align_dimensions2(). Some filters and swscale can read
	* up to 16 bytes beyond the planes, if these filters are to be used,
	* then 16 extra bytes must be allocated.
	*
	* NOTE: Except for hwaccel formats, pointers not needed by the format
	* MUST be set to NULL.
	*/
	uint8 *_data[AV_NUM_DATA_POINTERS];

   /**
     * For video, size in bytes of each picture line.
     * For audio, size in bytes of each plane.
     *
     * For audio, only linesize[0] may be set. For planar audio, each channel
     * plane must be the same size.
     *
     * For video the linesizes should be multiples of the CPUs alignment
     * preference, this is 16 or 32 for modern desktop CPUs.
     * Some code requires such alignment other code can be slower without
     * correct alignment, for yet other it makes no difference.
     *
     * @note The linesize may be larger than the size of usable data -- there
     * may be extra padding present for performance reasons.
     */
    int _linesize[AV_NUM_DATA_POINTERS];

	/**
	 * Constructor
	 */
	AVFrame();
	
	/**
	 * Destructor
	 */
	~AVFrame() { av_frame_free(); }

	/**
	 * Sets the frame dimensions
	 */
	int ff_set_dimensions(uint16 width, uint16 height);

	/**
	 * Get a buffer for a frame
	 */
	int ff_get_buffer(int flags);

	/**
	 * Frees any data loaded for the frame
	 */
	void av_frame_free();
};

struct IVI45DecContext {
	friend struct IVIHuffTab;
private:
	VLC_TYPE table_data[8192 * 16][2];
	VLC ivi_mb_vlc_tabs[8];  ///< static macroblock Huffman tables
	VLC ivi_blk_vlc_tabs[8]; ///< static block Huffman tables
public:
    GetBits *		gb;
    RVMapDesc       rvmap_tabs[9];   ///< local corrected copy of the static rvmap tables

    uint32          frame_num;
    int             frame_type;
    int             prev_frame_type; ///< frame type of the previous frame
    uint32          data_size;       ///< size of the frame data in bytes from picture header
    int             is_scalable;
    const uint8 *   frame_data;      ///< input frame data pointer
    int             inter_scal;      ///< signals a sequence of scalable inter frames
    uint32          frame_size;      ///< frame size in bytes
    uint32          pic_hdr_size;    ///< picture header size in bytes
    uint8           frame_flags;
    uint16          checksum;        ///< frame checksum

    IVIPicConfig    pic_conf;
    IVIPlaneDesc    planes[3];       ///< color planes

    int             buf_switch;      ///< used to switch between three buffers
    int             dst_buf;         ///< buffer index for the currently decoded frame
    int             ref_buf;         ///< inter frame reference buffer index
    int             ref2_buf;        ///< temporal storage for switching buffers
    int             b_ref_buf;       ///< second reference frame buffer index

    IVIHuffTab      mb_vlc;          ///< current macroblock table descriptor
    IVIHuffTab      blk_vlc;         ///< current block table descriptor

    uint8           rvmap_sel;
    uint8           in_imf;
    uint8           in_q;            ///< flag for explicitly stored quantiser delta
    uint8           pic_glob_quant;
    uint8           unknown1;

    uint16          gop_hdr_size;
    uint8           gop_flags;
    uint32          lock_word;

    uint8           has_b_frames;
    uint8           has_transp;      ///< transparency mode status: 1 - enabled
    uint8           uses_tiling;
    uint8           uses_haar;
    uint8           uses_fullpel;

    int gop_invalid;
    int buf_invalid[4];

    int is_indeo4;

    AVFrame *       p_frame;
    int             got_p_frame;

	IVI45DecContext();
private:
	/**
	 *  Initial Run-value (RLE) tables.
	 */
	static const RVMapDesc _ff_ivi_rvmap_tabs[9];
};

class IndeoDecoderBase : public Codec {
private:
	/**
	 *  Decode an Indeo 4 or 5 band.
	 *
	 *  @param[in,out]  band   ptr to the band descriptor
	 *  @returns        result code: 0 = OK, -1 = error
	 */
	int decode_band(IVIBandDesc *band);

	/**
	 *  Haar wavelet recomposition filter for Indeo 4
	 *
	 *  @param[in]  plane        pointer to the descriptor of the plane being processed
	 *  @param[out] dst          pointer to the destination buffer
	 *  @param[in]  dst_pitch    pitch of the destination buffer
	 */
	void ff_ivi_recompose_haar(const IVIPlaneDesc *plane, uint8 *dst,
		const int dst_pitch);

	/**
	 *  5/3 wavelet recomposition filter for Indeo5
	 *
	 *  @param[in]   plane        pointer to the descriptor of the plane being processed
	 *  @param[out]  dst          pointer to the destination buffer
	 *  @param[in]   dst_pitch    pitch of the destination buffer
	 */
	void ff_ivi_recompose53(const IVIPlaneDesc *plane,
		uint8 *dst, const int dst_pitch);

	/*
	 *  Convert and output the current plane.
	 *  This conversion is done by adding back the bias value of 128
	 *  (subtracted in the encoder) and clipping the result.
	 *
	 *  @param[in]   plane      pointer to the descriptor of the plane being processed
	 *  @param[out]  dst        pointer to the buffer receiving converted pixels
	 *  @param[in]   dst_pitch  pitch for moving to the next y line
	 */
	void ivi_output_plane(IVIPlaneDesc *plane, uint8 *dst, int dst_pitch);

	/**
	 *  Handle empty tiles by performing data copying and motion
	 *  compensation respectively.
	 *
	 *  @param[in]  band      pointer to the band descriptor
	 *  @param[in]  tile      pointer to the tile descriptor
	 *  @param[in]  mv_scale  scaling factor for motion vectors
	 */
	int ivi_process_empty_tile(IVIBandDesc *band, IVITile *tile, int32 mv_scale);

	/*
	 *  Decode size of the tile data.
	 *  The size is stored as a variable-length field having the following format:
	 *  if (tile_data_size < 255) than this field is only one byte long
	 *  if (tile_data_size >= 255) than this field four is byte long: 0xFF X1 X2 X3
	 *  where X1-X3 is size of the tile data
	 *
	 *  @param[in,out]  gb  the GetBit context
	 *  @return     size of the tile data in bytes
	 */
	int ivi_dec_tile_data_size(GetBits *gb);

	/*
	 *  Decode block data:
	 *  extract huffman-coded transform coefficients from the bitstream,
	 *  dequantize them, apply inverse transform and motion compensation
	 *  in order to reconstruct the picture.
	 *
	 *  @param[in,out]  gb    the GetBit context
	 *  @param[in]      band  pointer to the band descriptor
	 *  @param[in]      tile  pointer to the tile descriptor
	 *  @return     result code: 0 - OK, -1 = error (corrupted blocks data)
	 */
	int ivi_decode_blocks(GetBits *gb, IVIBandDesc *band, IVITile *tile);

	int ivi_mc(IVIBandDesc *band, ivi_mc_func mc, ivi_mc_avg_func mc_avg,
		int offs, int mv_x, int mv_y, int mv_x2, int mv_y2,
		int mc_type, int mc_type2);

	int ivi_decode_coded_blocks(GetBits *gb, IVIBandDesc *band,
		ivi_mc_func mc, ivi_mc_avg_func mc_avg, int mv_x, int mv_y,
		int mv_x2, int mv_y2, int *prev_dc, int is_intra,
		int mc_type, int mc_type2, uint32 quant, int offs);

	int ivi_dc_transform(IVIBandDesc *band, int *prev_dc, int buf_offs,
		int blk_size);
protected:
	IVI45DecContext _ctx;
	Graphics::PixelFormat _pixelFormat;
	Graphics::ManagedSurface *_surface;

	/**
	 *  Scan patterns shared between indeo4 and indeo5
	 */
	static const uint8 _ff_ivi_vertical_scan_8x8[64];
	static const uint8 _ff_ivi_horizontal_scan_8x8[64];
	static const uint8 _ff_ivi_direct_scan_4x4[16];
protected:
	/**
	 * Returns the pixel format for the decoder's surface
	 */
	virtual Graphics::PixelFormat getPixelFormat() const { return _pixelFormat; }

	/**
	 * Decode the Indeo picture header.
	 * @returns		0 = Ok, negative number = error
	 */
	virtual int decodePictureHeader() = 0;

	/**
	 *  Rearrange decoding and reference buffers.
	 */
	virtual void switch_buffers() = 0;

	virtual bool is_nonnull_frame() const = 0;

	/**
	 *  Decode Indeo band header.
	 *
	 *  @param[in,out] band      pointer to the band descriptor
	 *  @return        result code: 0 = OK, negative number = error
	 */
	virtual int decode_band_hdr(IVIBandDesc *band) = 0;

	/**
	*  Decode information (block type, cbp, quant delta, motion vector)
	*  for all macroblocks in the current tile.
	*
	*  @param[in,out] band      pointer to the band descriptor
	*  @param[in,out] tile      pointer to the tile descriptor
	*  @return        result code: 0 = OK, negative number = error
	*/
	virtual int decode_mb_info(IVIBandDesc *band, IVITile *tile)= 0;

	/**
	 * Decodes the Indeo frame from the bit reader already 
	 * loaded into the context
	 */
	int decodeIndeoFrame();

	/**
	 * scale motion vector
	 */
	int ivi_scale_mv(int mv, int mv_scale);
public:
	IndeoDecoderBase(uint16 width, uint16 height);
	virtual ~IndeoDecoderBase();
};

/*------------------------------------------------------------------------*/

/**
 * Check if the given dimension of an image is valid, meaning that all
 * bytes of the image can be addressed with a signed int.
 *
 * @param w the width of the picture
 * @param h the height of the picture
 * @param log_offset the offset to sum to the log level for logging with log_ctx
 * @returns >= 0 if valid, a negative error code otherwise
 */
extern int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx);

} // End of namespace Indeo
} // End of namespace Image

#endif