aboutsummaryrefslogtreecommitdiff
path: root/image/codecs/indeo/indeo.h
blob: dcb7330318bd1577bc1cb7835933ce1c32df1381 (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
582
583
584
585
586
587
588
589
/* 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/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 blkSize);

typedef void (*IviMCFunc)(int16 *buf, const int16 *refBuf, uint32 pitch, int mcType);
typedef void (*IviMCAvgFunc)(int16 *buf, const int16 *refBuf1, const int16 *refBuf2,
	uint32 pitch, int mcType, int mcType2);

///< max number of bits of the ivi's huffman codes
#define IVI_VLC_BITS 13
#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(tileWidth, tileHeight, mbSize) \
	((((tileWidth) + (mbSize) - 1) / (mbSize)) * (((tileHeight) + (mbSize) - 1) / (mbSize)))

/**
 *  huffman codebook descriptor
 */
struct IVIHuffDesc {
	int32		_numRows;
	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: true - for static or false for dynamic tables
	 *  @returns	result code: 0 - OK, -1 = error (invalid codebook descriptor)
	 */
	int createHuffFromDesc(VLC *vlc, bool flag) const;

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

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

struct IVI45DecContext;

/**
 *  Macroblock/block huffman table descriptor
 */
struct IVIHuffTab {
public:
	int32	_tabSel;	/// 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 _custDesc;	/// custom Huffman codebook descriptor
	VLC         _custTab;	/// vlc table for custom codebook

	/**
	 * Constructor
	 */
	IVIHuffTab();

	/**
	 *  Decode a huffman codebook descriptor from the bitstream
	 *  and select specified huffman table.
	 *
	 *  @param[in]		ctx			Decoder context
	 *  @param[in]      descCoded	Flag signalling if table descriptor was coded
	 *  @param[in]      whichTab	Codebook purpose (IVI_MB_HUFF or IVI_BLK_HUFF)
	 *  @returns	Zero on success, negative value otherwise
	 */
	int decodeHuffDesc(IVI45DecContext *ctx, int descCoded, int whichTab);
};

/**
 *  run-value (RLE) table descriptor
 */
struct RVMapDesc {
	uint8     _eobSym; ///< end of block symbol
	uint8     _escSym; ///< escape symbol
	uint8     _runtab[256];
	int8      _valtab[256];
};

/**
 *  information for Indeo macroblock (16x16, 8x8 or 4x4)
 */
struct IVIMbInfo {
	int16	_xPos;
	int16	_yPos;
	uint32	_bufOffs;	///< address in the output buffer for this mb
	uint8	_type;		///< macroblock type: 0 - INTRA, 1 - INTER
	uint8	_cbp;		///< coded block pattern
	int8	_qDelta;	///< quant delta
	int8	_mvX;		///< motion vector (x component)
	int8	_mvY;		///< motion vector (y component)
	int8	_bMvX;		///< second motion vector (x component)
	int8	_bMvY;		///< second motion vector (y component)

	IVIMbInfo();
};

/**
 *  information for Indeo tile
 */
struct IVITile {
	int			_xPos;
	int			_yPos;
	int			_width;
	int			_height;
	int			_mbSize;
	bool		_isEmpty;
	int			_dataSize;	///< size of the data in bytes
	int			_numMBs;	///< number of macroblocks in this tile
	IVIMbInfo *	_mbs;		///< array of macroblock descriptors
	IVIMbInfo *	_refMbs;	///< 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				_bandNum;		///< band number
	int				_width;
	int				_height;
	int				_aHeight;		///< aligned band height
	const uint8 *	_dataPtr;		///< ptr to the first byte of the band data
	int				_dataSize;		///< size of the band data
	int16 *			_buf;			///< pointer to the output buffer for this band
	int16 *			_refBuf;		///< pointer to the reference frame buffer (for motion compensation)
	int16 *			_bRefBuf;		///< 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
	bool			_isEmpty;
	int				_mbSize;		///< macroblock size
	int				_blkSize;		///< block size
	uint8			_isHalfpel;		///< precision of the motion compensation: 0 - fullpel, 1 - halfpel
	bool			_inheritMv;		///< tells if motion vector is inherited from reference macroblock
	bool			_inheritQDelta;	///< tells if quantiser delta is inherited from reference macroblock
	bool			_qdeltaPresent;	///< tells if Qdelta signal is present in the bitstream (Indeo5 only)
	int				_quantMat;		///< dequant matrix index
	int				_globQuant;		///< quant base for this band
	const uint8 *	_scan;			///< ptr to the scan pattern
	int				_scanSize;		///< size of the scantable

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

	int				_numCorr;		///< number of correction entries
	uint8			_corr[61 * 2];	///< rvmap correction pairs
	int				_rvmapSel;		///< rvmap table selector
	RVMapDesc *		_rvMap;			///< ptr to the RLE table for this band
	int				_numTiles;		///< number of tiles in this band
	IVITile *		_tiles;			///< array of tile descriptors
	InvTransformPtr *_invTransform;
	int				_transformSize;
	DCTransformPtr *_dcTransform;
	bool			_is2dTrans;
	int32			_checksum;		///< for debug purposes
	int				_checksumPresent;
	int				_bufSize;		///< band buffer size in bytes
	const uint16 *	_intraBase;		///< quantization matrix for intra blocks
	const uint16 *	_interBase;		///< quantization matrix for inter blocks
	const uint8 *	_intraScale;	///< quantization coefficient for intra blocks
	const uint8 *	_interScale;	///< quantization coefficient for inter blocks

	IVIBandDesc();

	int initTiles(IVITile *refTile, int p, int b, int tHeight, int tWidth);
};

struct IVIPicConfig {
	uint16		_picWidth;
	uint16		_picHeight;
	uint16		_chromaWidth;
	uint16		_chromaHeight;
	uint16		_tileWidth;
	uint16		_tileHeight;
	uint8		_lumaBands;
	uint8		_chromaBands;

	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			_numBands;	///< number of bands this plane subdivided into
	IVIBandDesc *	_bands;		///< array of band descriptors

	IVIPlaneDesc();

	static int initPlanes(IVIPlaneDesc *planes, const IVIPicConfig *cfg, bool isIndeo4);

	static int initTiles(IVIPlaneDesc *planes, int tileWidth, int tileHeight);

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

	/**
	 * 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
	 */
	static int checkImageSize(unsigned int w, unsigned int h, int logOffset);
};

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() { freeFrame(); }

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

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

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

struct IVI45DecContext {
	friend struct IVIHuffTab;
private:
	VLC_TYPE _tableData[8192 * 16][2];
	VLC _iviMbVlcTabs[8];			///< static macroblock Huffman tables
	VLC _iviBlkVlcTabs[8];			///< static block Huffman tables
public:
	GetBits *		_gb;
	RVMapDesc		_rvmapTabs[9];	///< local corrected copy of the static rvmap tables

	uint32			_frameNum;
	int				_frameType;
	int				_prevFrameType;	///< frame type of the previous frame
	uint32			_dataSize;		///< size of the frame data in bytes from picture header
	int				_isScalable;
	const uint8 *	_frameData;		///< input frame data pointer
	int				_interScal;		///< signals a sequence of scalable inter frames
	uint32			_frameSize;		///< frame size in bytes
	uint32			_picHdrSize;	///< picture header size in bytes
	uint8			_frameFlags;
	uint16			_checksum;		///< frame _checksum

	IVIPicConfig	_picConf;
	IVIPlaneDesc	_planes[3];		///< color planes

	int				_bufSwitch;		///< used to switch between three buffers
	int				_dstBuf;		///< buffer index for the currently decoded frame
	int				_refBuf;		///< inter frame reference buffer index
	int				_ref2Buf;		///< temporal storage for switching buffers
	int				_bRefBuf;		///< second reference frame buffer index

	IVIHuffTab		_mbVlc;			///< current macroblock table descriptor
	IVIHuffTab		_blkVlc;		///< current block table descriptor

	uint8			_rvmapSel;
	bool			_inImf;
	bool			_inQ;			///< flag for explicitly stored quantiser delta
	uint8			_picGlobQuant;
	uint8			_unknown1;

	uint16			_gopHdrSize;
	uint8			_gopFlags;
	uint32			_lockWord;

	bool			_hasBFrames;
	bool			_hasTransp;		///< transparency mode enabled
	bool			_usesTiling;
	bool			_usesHaar;
	bool			_usesFullpel;

	bool			_gopInvalid;
	int				_bufInvalid[4];

	bool			_isIndeo4;

	AVFrame *		_pFrame;
	bool			_gotPFrame;

	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]  dstPitch	Pitch of the destination buffer
	 */
	void recomposeHaar(const IVIPlaneDesc *plane, uint8 *dst, const int dstPitch);

	/**
	 *  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]   dstPitch     Pitch of the destination buffer
	 */
	void recompose53(const IVIPlaneDesc *plane, uint8 *dst, const int dstPitch);

	/*
	 *  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]   dstPitch	Pitch for moving to the next y line
	 */
	void outputPlane(IVIPlaneDesc *plane, uint8 *dst, int dstPitch);

	/**
	 *  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]  mvScale		Scaling factor for motion vectors
	 */
	int processEmptyTile(IVIBandDesc *band, IVITile *tile, int32 mvScale);

	/*
	 *  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
	 *  @returns	Size of the tile data in bytes
	 */
	int decodeTileDataSize(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
	 *  @returns	Result code: 0 - OK, -1 = error (corrupted blocks data)
	 */
	int decodeBlocks(GetBits *gb, IVIBandDesc *band, IVITile *tile);

	int iviMc(IVIBandDesc *band, IviMCFunc mc, IviMCAvgFunc mcAvg,
		int offs, int mvX, int mvY, int mvX2, int mvY2, int mcType, int mcType2);

	int decodeCodedBlocks(GetBits *gb, IVIBandDesc *band,
		IviMCFunc mc, IviMCAvgFunc mcAvg, int mvX, int mvY,
		int mvX2, int mvY2, int32 *prevDc, int isIntra,
		int mcType, int mcType2, uint32 quant, int offs);

	int iviDcTransform(IVIBandDesc *band, int32 *prevDc, int bufOffs,
		int blkSize);
protected:
	IVI45DecContext _ctx;
	Graphics::PixelFormat _pixelFormat;
	Graphics::Surface *_surface;

	/**
	 *  Scan patterns shared between indeo4 and indeo5
	 */
	static const uint8 _ffIviVerticalScan8x8[64];
	static const uint8 _ffIviHorizontalScan8x8[64];
	static const uint8 _ffIviDirectScan4x4[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 switchBuffers() = 0;

	virtual bool isNonNullFrame() const = 0;

	/**
	 *  Decode Indeo band header.
	 *
	 *  @param[in,out] band		Pointer to the band descriptor
	 *  @returns	Result code: 0 = OK, negative number = error
	 */
	virtual int decodeBandHeader(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
	*  @returns		Result code: 0 = OK, negative number = error
	*/
	virtual int decodeMbInfo(IVIBandDesc *band, IVITile *tile) = 0;

	/**
	 * Decodes optional transparency data within Indeo frames
	 */
	virtual void decodeTransparency() {}

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

	/**
	 * scale motion vector
	 */
	int scaleMV(int mv, int mvScale);
public:
	IndeoDecoderBase(uint16 width, uint16 height, uint bitsPerPixel);
	virtual ~IndeoDecoderBase();
};

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

#endif