aboutsummaryrefslogtreecommitdiff
path: root/engines/cryomni3d/video/hnm_decoder.cpp
blob: db59782d6639bc7c2f2c71cb1ab6588b0525fff4 (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
/* 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/debug.h"
#include "common/endian.h"
#include "common/system.h"
#include "common/stream.h"
#include "common/file.h"
#include "common/textconsole.h"

#include "audio/decoders/raw.h"

#include "cryomni3d/video/hnm_decoder.h"
#include "cryomni3d/image/codecs/hlz.h"

namespace Video {

// When no sound display a frame every 80ms
HNMDecoder::HNMDecoder(bool loop, byte *initialPalette) : _regularFrameDelay(80),
	_videoTrack(nullptr), _audioTrack(nullptr), _stream(nullptr),
	_loop(loop), _initialPalette(initialPalette) {
}

HNMDecoder::~HNMDecoder() {
	close();

	delete[] _initialPalette;

	// We don't deallocate _videoTrack and _audioTrack as they are owned by base class
}

bool HNMDecoder::loadStream(Common::SeekableReadStream *stream) {
	close();

	uint32 tag = stream->readUint32BE();

	/* For now, only HNM4, HNM6 in the future */
	if (tag != MKTAG('H', 'N', 'M', '4')) {
		close();
		return false;
	}

	//uint32 ukn = stream->readUint32BE();
	stream->skip(4);
	uint16 width = stream->readUint16LE();
	uint16 height = stream->readUint16LE();
	//uint32 filesize = stream->readUint32LE();
	stream->skip(4);
	uint32 frameCount = stream->readUint32LE();
	//uint32 tabOffset = stream->readUint32LE();
	stream->skip(4);
	uint16 soundBits = stream->readUint16LE();
	uint16 soundChannels = stream->readUint16LE();
	uint32 frameSize = stream->readUint32LE();

	byte unknownStr[16];
	byte copyright[16];
	stream->read(unknownStr, sizeof(unknownStr));
	stream->read(copyright, sizeof(copyright));

	if (_loop) {
		// This will force loop mode
		frameCount = 0;
	}

	_videoTrack = new HNM4VideoTrack(width, height, frameSize, frameCount, _regularFrameDelay,
	                                 _initialPalette);
	if (soundBits != 0 && soundChannels != 0) {
		// HNM4 is 22050Hz
		_audioTrack = new DPCMAudioTrack(soundChannels, soundBits, 22050, getSoundType());
	} else {
		_audioTrack = nullptr;
	}
	addTrack(_videoTrack);
	addTrack(_audioTrack);

	_stream = stream;

	return true;
}

void HNMDecoder::close() {
	VideoDecoder::close();
	// Tracks are cleant by VideoDecoder::close
	_videoTrack = nullptr;
	_audioTrack = nullptr;

	delete _stream;
	_stream = nullptr;
}

void HNMDecoder::readNextPacket() {
	// We are called to feed a frame
	// Each chunk is packetized and a packet seems to contain only one frame
	uint32 superchunkRemaining = _stream->readUint32LE();
	if (!superchunkRemaining) {
		if (!_loop) {
			error("End of file but still requesting data");
		} else {
			// Looping: read back from start of file, skip header and read a new super chunk header
			_videoTrack->restart();
			_stream->seek(64, SEEK_SET);
			superchunkRemaining = _stream->readUint32LE();
		}
	}
	superchunkRemaining = (superchunkRemaining & 0x00ffffff) - 4;

	while (superchunkRemaining) {
		uint32 chunkSize = _stream->readUint32LE();
		uint16 chunkType = _stream->readUint16BE();
		//uint16 ukn        = _stream->readUint16LE();
		_stream->skip(2);

		if (chunkType == MKTAG16('P', 'L')) {
			_videoTrack->decodePalette(_stream, chunkSize - 8);
		} else if (chunkType == MKTAG16('I', 'Z')) {
			_stream->skip(4);
			_videoTrack->decodeIntraframe(_stream, chunkSize - 8 - 4);
		} else if (chunkType == MKTAG16('I', 'U')) {
			_videoTrack->decodeInterframe(_stream, chunkSize - 8);
		} else if (chunkType == MKTAG16('S', 'D')) {
			if (_audioTrack) {
				Audio::Timestamp duration = _audioTrack->decodeSound(_stream, chunkSize - 8);
				_videoTrack->setFrameDelay(duration.msecs());
			} else {
				error("Shouldn't have audio data");
			}
		} else {
			error("Got %d chunk: size %d", chunkType, chunkSize);
		}

		superchunkRemaining -= chunkSize;
	}
}

HNMDecoder::HNM4VideoTrack::HNM4VideoTrack(uint32 width, uint32 height, uint32 frameSize,
        uint32 frameCount, uint32 regularFrameDelay, const byte *initialPalette) :
	_frameCount(frameCount), _regularFrameDelay(regularFrameDelay), _nextFrameStartTime(0) {

	restart();

	_curFrame = -1;
	// Get the currently loaded palette for undefined colors
	if (initialPalette) {
		memcpy(_palette, initialPalette, 256 * 3);
	} else {
		memset(_palette, 0, 256 * 3);
	}

	if (width * height != frameSize) {
		error("Invalid frameSize");
	}

	// We will use _frameBufferC/P as the surface pixels, just init there with nullptr to avoid unintended usage of surface
	const Graphics::PixelFormat &f = Graphics::PixelFormat::createFormatCLUT8();
	_surface.init(width, height, width * f.bytesPerPixel, nullptr, f);
	_frameBufferC = new byte[frameSize];
	memset(_frameBufferC, 0, frameSize);
	_frameBufferP = new byte[frameSize];
	memset(_frameBufferP, 0, frameSize);
}

HNMDecoder::HNM4VideoTrack::~HNM4VideoTrack() {
	// Don't free _surface as we didn't used create() but init()
	delete[] _frameBufferC;
	_frameBufferC = nullptr;
	delete[] _frameBufferP;
	_frameBufferP = nullptr;
}

void HNMDecoder::HNM4VideoTrack::setFrameDelay(uint32 frameDelay) {
	if (_nextFrameDelay == uint32(-1)) {
		_nextFrameDelay = frameDelay;
	} else if (_nextNextFrameDelay == uint32(-1)) {
		_nextNextFrameDelay = frameDelay;
	} else {
		_nextNextFrameDelay += frameDelay;
	}
}


void HNMDecoder::HNM4VideoTrack::decodePalette(Common::SeekableReadStream *stream, uint32 size) {
	while (true) {
		if (size < 2) {
			break;
		}
		uint start = stream->readByte();
		uint count = stream->readByte();
		size -= 2;

		if (start == 255 && count == 255) {
			break;
		}
		if (count == 0) {
			count = 256;
		}

		if (size < count * 3) {
			error("Invalid palette chunk data");
		}
		if (start + count > 256) {
			error("Invalid palette start/count values");
		}

		size -= count * 3;
		byte *palette_ptr = &_palette[start * 3];
		for (; count > 0; count--) {
			byte r = stream->readByte();
			byte g = stream->readByte();
			byte b = stream->readByte();
			*(palette_ptr++) = r * 4;
			*(palette_ptr++) = g * 4;
			*(palette_ptr++) = b * 4;
		}
	}
	_dirtyPalette = true;

	if (size > 0) {
		stream->skip(size);
	}
}

void HNMDecoder::HNM4VideoTrack::decodeInterframe(Common::SeekableReadStream *stream, uint32 size) {
	SWAP(_frameBufferC, _frameBufferP);

	uint16 width = _surface.w;
	bool eop = false;

	uint currentPos = 0;

	while (!eop) {
		if (size < 1) {
			warning("Not enough data in chunk for interframe block");
			break;
		}
		byte countFlgs = stream->readByte();
		size -= 1;
		byte count = countFlgs & 0x3f;
		byte flgs = (countFlgs >> 6) & 0x3;

		if (count == 0) {
			byte c;
			switch (flgs) {
			case 0:
				if (size < 1) {
					error("Not enough data for case 0");
				}
				// Move in image
				c = stream->readByte();
				currentPos += c;
				size -= 1;
				break;
			case 1:
				if (size < 1) {
					error("Not enough data for case 1");
				}
				// New pixels
				c = stream->readByte();
				_frameBufferC[currentPos] = c;
				c = stream->readByte();
				_frameBufferC[currentPos + width] = c;
				currentPos++;
				size -= 2;
				break;
			case 2:
				// New line
				currentPos += width;
				break;
			case 3:
				// End of picture
				eop = true;
				break;
			}
		} else {
			if (size < 2) {
				error("Not enough data for count > 0");
			}

			bool negative = (flgs & 0x2) != 0;
			bool previous = (flgs & 0x1) != 0;
			int offset = stream->readUint16LE();
			size -= 2;

			if (negative) {
				offset -= 0x10000;
			}
			offset += currentPos;
			if (offset < 0) {
				error("Invalid offset");
			}

			byte *ptr;
			if (previous) {
				ptr = _frameBufferP;
			} else {
				ptr = _frameBufferC;
			}
			for (; count > 0; count--) {
				_frameBufferC[currentPos] = ptr[offset];
				_frameBufferC[currentPos + width] = ptr[offset + width];
				currentPos++;
				offset++;
			}
		}
	}
	_surface.setPixels(_frameBufferC);

	_curFrame++;
	_nextFrameStartTime += _nextFrameDelay != uint32(-1) ? _nextFrameDelay : _regularFrameDelay;
	_nextFrameDelay = _nextNextFrameDelay;
	_nextNextFrameDelay = uint32(-1);

	if (size > 0) {
		stream->skip(size);
	}
}

void HNMDecoder::HNM4VideoTrack::decodeIntraframe(Common::SeekableReadStream *stream, uint32 size) {
	Image::HLZDecoder::decodeFrameInPlace(*stream, size, _frameBufferC);
	memcpy(_frameBufferP, _frameBufferC, _surface.w * _surface.h);
	_surface.setPixels(_frameBufferC);

	_curFrame++;
	_nextFrameStartTime += _nextFrameDelay != uint32(-1) ? _nextFrameDelay : _regularFrameDelay;
	_nextFrameDelay = _nextNextFrameDelay;
	_nextNextFrameDelay = uint32(-1);
}

HNMDecoder::DPCMAudioTrack::DPCMAudioTrack(uint16 channels, uint16 bits, uint sampleRate,
        Audio::Mixer::SoundType soundType) : AudioTrack(soundType), _audioStream(nullptr),
	_gotLUT(false), _lastSample(0) {
	if (bits != 16) {
		error("Unsupported audio bits");
	}
	if (channels != 2) {
		warning("Unsupported %d audio channels", channels);
	}
	_audioStream = Audio::makeQueuingAudioStream(sampleRate, false);
}

HNMDecoder::DPCMAudioTrack::~DPCMAudioTrack() {
	delete _audioStream;
}

Audio::Timestamp HNMDecoder::DPCMAudioTrack::decodeSound(Common::SeekableReadStream *stream,
        uint32 size) {
	if (!_gotLUT) {
		if (size < 256 * sizeof(*_lut)) {
			error("Invalid first sound chunk");
		}
		stream->read(_lut, 256 * sizeof(*_lut));
		size -= 256 * sizeof(*_lut);
#ifndef SCUMM_LITTLE_ENDIAN
		for (uint i = 0; i < 256; i++) {
			_lut[i] = FROM_LE_16(_lut[i]);
		}
#endif
		_gotLUT = true;
	}

	if (size > 0) {
		uint16 *out = (uint16 *)malloc(size * sizeof(*out));
		uint16 *p = out;
		uint16 sample = _lastSample;
		for (uint32 i = 0; i < size; i++, p++) {
			byte deltaId = stream->readByte();
			sample += _lut[deltaId];
			*p = sample;
		}
		_lastSample = sample;

		byte flags = Audio::FLAG_16BITS;
#ifdef SCUMM_LITTLE_ENDIAN
		flags |= Audio::FLAG_LITTLE_ENDIAN;
#endif
		// channels is 2 but we are MONO!
		_audioStream->queueBuffer((byte *)out, size * sizeof(*out), DisposeAfterUse::YES, flags);
	}
	return Audio::Timestamp(0, size, 22050);
}

} // End of namespace Video