[Scummvm-git-logs] scummvm master -> ba528657de0c7e6859f7a41291251125255a8b80

aquadran noreply at scummvm.org
Sat Oct 31 19:02:45 UTC 2026


This automated email contains information about 32 new commits which have been
pushed to the 'scummvm' repo located at https://api.github.com/repos/scummvm/scummvm .

Summary:
dd96261ccc GRIM: IMUSE: Bring iMUSE engine from SCUMM in GRIM codebase
879b900f0e GRIM: IMUSE: Port GRIM differences on SCUMM-derived iMUSE code
ee9278fe45 GRIM: IMUSE: Port GRIM differences in dimuse_dispatch.cpp
e9a5938c74 GRIM: IMUSE: Implement original mixer
3b0a8cba6f GRIM: IMUSE: Port muscript section
0379af169d GRIM: IMUSE: Simplify iMUSE calls
26455cd323 GRIM: IMUSE: Begin porting original file layer
69f0cf60fb GRIM: IMUSE: Clean-up leftover files
7d556836b8 GRIM: IMUSE: Port original SFX cache and external format detection
8555512555 GRIM: IMUSE: Change some allocation sizes to match the original
918f8d4cab GRIM: IMUSE: Port voice and lipsync routines
43f4d4527a GRIM: IMUSE: Port HMIFX DSP effects usage
5701e5cc73 GRIM: IMUSE: Hook up the new DiMUSE engine to the game
7ce719034b GRIM: IMUSE: Implement saving and post-load fix for old savegames
4ae2ee9cf7 GRIM: IMUSE: Port original sound positioning formulas
75e5d511d7 GRIM: IMUSE: Implement 3D speech positioning
4fa87fe0d4 GRIM: IMUSE: Port original costume sound components
4aa1d3c599 GRIM: IMUSE: Remove old iMUSE implementation files
d8df7ed005 GRIM: IMUSE: Mass renames to new iMUSE files
bcce93fce5 GRIM: IMUSE: Insert missing mutex lock
49efc2380a GRIM: IMUSE: Remove unused SCUMM leftovers
d9ba5b2d82 GRIM: IMUSE: Apply GMM mixer volumes to the sound groups
7feed580ec GRIM: IMUSE: Add missing ImSetAttribute and ImSetCuePoint Lua opcodes
c29231a73d GRIM: IMUSE: Clean-up a TODO comment
a2ade3c205 GRIM: IMUSE: Sync the lipsync code with the disasm
691550b0cf GRIM: IMUSE: Add ImStartVoice, ImStopVoice, master volume and other missing Lua opcodes
2424c530d6 GRIM: IMUSE: Remove speech delay hack
567ae10dc2 GRIM: IMUSE: Clean-up
07787ada45 GRIM: IMUSE: Add support for demo
369f3f5afb GRIM: IMUSE: Add support for remastered
bcc06b7299 GRIM: Remove mistakenly added opcodes
ba528657de GRIM: Remove mistakenly added opcodes pt.2


Commit: dd96261ccc832cc60c6e0303d6d77174d99bf67d
    https://github.com/scummvm/scummvm/commit/dd96261ccc832cc60c6e0303d6d77174d99bf67d
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Bring iMUSE engine from SCUMM in GRIM codebase

Just a minimum compilable version of the COMI iMUSE engine,
it's not hooked up yet...

Changed paths:
  A engines/grim/imuse/dimuse_bndmgr.cpp
  A engines/grim/imuse/dimuse_bndmgr.h
  A engines/grim/imuse/dimuse_cmds.cpp
  A engines/grim/imuse/dimuse_codecs.cpp
  A engines/grim/imuse/dimuse_codecs.h
  A engines/grim/imuse/dimuse_defs.h
  A engines/grim/imuse/dimuse_dispatch.cpp
  A engines/grim/imuse/dimuse_engine.cpp
  A engines/grim/imuse/dimuse_engine.h
  A engines/grim/imuse/dimuse_fades.cpp
  A engines/grim/imuse/dimuse_fades.h
  A engines/grim/imuse/dimuse_files.cpp
  A engines/grim/imuse/dimuse_files.h
  A engines/grim/imuse/dimuse_groups.cpp
  A engines/grim/imuse/dimuse_groups.h
  A engines/grim/imuse/dimuse_internalmixer.cpp
  A engines/grim/imuse/dimuse_internalmixer.h
  A engines/grim/imuse/dimuse_scripts.cpp
  A engines/grim/imuse/dimuse_sndmgr.cpp
  A engines/grim/imuse/dimuse_sndmgr.h
  A engines/grim/imuse/dimuse_streamer.cpp
  A engines/grim/imuse/dimuse_tables.cpp
  A engines/grim/imuse/dimuse_tables.h
  A engines/grim/imuse/dimuse_tracks.cpp
  A engines/grim/imuse/dimuse_triggers.cpp
  A engines/grim/imuse/dimuse_triggers.h
  A engines/grim/imuse/dimuse_utils.cpp
  A engines/grim/imuse/dimuse_wave.cpp
  A engines/grim/imuse/dimuse_waveout.cpp
    engines/grim/imuse/imuse_sndmgr.h
    engines/grim/imuse/imuse_tables.h
    engines/grim/module.mk


diff --git a/engines/grim/imuse/dimuse_bndmgr.cpp b/engines/grim/imuse/dimuse_bndmgr.cpp
new file mode 100644
index 00000000000..a78965268ed
--- /dev/null
+++ b/engines/grim/imuse/dimuse_bndmgr.cpp
@@ -0,0 +1,413 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+
+#include "common/scummsys.h"
+#include "engines/grim/imuse/dimuse_bndmgr.h"
+#include "engines/grim/imuse/dimuse_codecs.h"
+
+namespace Grim {
+
+BundleDirCache::BundleDirCache() {
+	for (int fileId = 0; fileId < ARRAYSIZE(_bundleDirCache); fileId++) {
+		_bundleDirCache[fileId].bundleTable = nullptr;
+		_bundleDirCache[fileId].fileName[0] = 0;
+		_bundleDirCache[fileId].numFiles = 0;
+		_bundleDirCache[fileId].isCompressed = false;
+		_bundleDirCache[fileId].indexTable = nullptr;
+	}
+}
+
+BundleDirCache::~BundleDirCache() {
+	for (int fileId = 0; fileId < ARRAYSIZE(_bundleDirCache); fileId++) {
+		free(_bundleDirCache[fileId].bundleTable);
+		free(_bundleDirCache[fileId].indexTable);
+	}
+}
+
+BundleDirCache::AudioTable *BundleDirCache::getTable(int slot) {
+	return _bundleDirCache[slot].bundleTable;
+}
+
+int32 BundleDirCache::getNumFiles(int slot) {
+	return _bundleDirCache[slot].numFiles;
+}
+
+BundleDirCache::IndexNode *BundleDirCache::getIndexTable(int slot) {
+	return _bundleDirCache[slot].indexTable;
+}
+
+bool BundleDirCache::isSndDataExtComp(int slot) {
+	return _bundleDirCache[slot].isCompressed;
+}
+
+int BundleDirCache::matchFile(const char *filename) {
+	int32 tag, offset;
+	bool found = false;
+	int freeSlot = -1;
+	int fileId;
+
+	for (fileId = 0; fileId < ARRAYSIZE(_bundleDirCache); fileId++) {
+		if ((_bundleDirCache[fileId].bundleTable == nullptr) && (freeSlot == -1)) {
+			freeSlot = fileId;
+		}
+		if (scumm_stricmp(filename, _bundleDirCache[fileId].fileName) == 0) {
+			found = true;
+			break;
+		}
+	}
+
+	if (!found) {
+		Common::File file;
+
+		// TODO
+		// if (g_scumm->openFile(file, filename) == false) {
+		// 	error("BundleDirCache::matchFile() Can't open bundle file: %s", filename);
+		// 	return false;
+		// }
+
+		if (freeSlot == -1)
+			error("BundleDirCache::matchFileFile() Can't find free slot for file bundle dir cache");
+
+		tag = file.readUint32BE();
+		if (tag == MKTAG('L','B','2','3'))
+			_bundleDirCache[freeSlot].isCompressed = true;
+		offset = file.readUint32BE();
+
+		Common::strlcpy(_bundleDirCache[freeSlot].fileName, filename, sizeof(_bundleDirCache[freeSlot].fileName));
+		_bundleDirCache[freeSlot].numFiles = file.readUint32BE();
+		_bundleDirCache[freeSlot].bundleTable = (AudioTable *)malloc(_bundleDirCache[freeSlot].numFiles * sizeof(AudioTable));
+		assert(_bundleDirCache[freeSlot].bundleTable);
+
+		file.seek(offset, SEEK_SET);
+
+		_bundleDirCache[freeSlot].indexTable =
+				(IndexNode *)calloc(_bundleDirCache[freeSlot].numFiles, sizeof(IndexNode));
+		assert(_bundleDirCache[freeSlot].indexTable);
+
+		for (int32 i = 0; i < _bundleDirCache[freeSlot].numFiles; i++) {
+			char name[24], c;
+			int32 z = 0;
+			int32 z2;
+
+			if (tag == MKTAG('L','B','2','3')) {
+				file.read(_bundleDirCache[freeSlot].bundleTable[i].filename, 24);
+			} else {
+				for (z2 = 0; z2 < 8; z2++)
+					if ((c = file.readByte()) != 0)
+						name[z++] = c;
+				name[z++] = '.';
+				for (z2 = 0; z2 < 4; z2++)
+					if ((c = file.readByte()) != 0)
+						name[z++] = c;
+
+				name[z] = '\0';
+				Common::strlcpy(_bundleDirCache[freeSlot].bundleTable[i].filename, name, sizeof(_bundleDirCache[freeSlot].bundleTable[i].filename));
+			}
+			_bundleDirCache[freeSlot].bundleTable[i].offset = file.readUint32BE();
+			_bundleDirCache[freeSlot].bundleTable[i].size = file.readUint32BE();
+			Common::strlcpy(_bundleDirCache[freeSlot].indexTable[i].filename, _bundleDirCache[freeSlot].bundleTable[i].filename, sizeof(_bundleDirCache[freeSlot].indexTable[i].filename));
+			_bundleDirCache[freeSlot].indexTable[i].index = i;
+		}
+		qsort(_bundleDirCache[freeSlot].indexTable, _bundleDirCache[freeSlot].numFiles,
+				sizeof(IndexNode), (int (*)(const void *, const void *))scumm_stricmp);
+		return freeSlot;
+	} else {
+		return fileId;
+	}
+}
+
+BundleMgr::BundleMgr(BundleDirCache *cache) {
+	_cache = cache;
+	_bundleTable = nullptr;
+	_compTable = nullptr;
+	_numFiles = 0;
+	_numCompItems = 0;
+	_lastBlockDecompressedSize = 0;
+	_curSampleId = -1;
+	_fileBundleId = -1;
+	_file = new Common::File();
+	_compInputBuff = nullptr;
+}
+
+BundleMgr::~BundleMgr() {
+	close();
+	delete _file;
+}
+
+Common::SeekableReadStream *BundleMgr::getFile(const char *filename, int32 &offset, int32 &size) {
+	BundleDirCache::IndexNode target;
+	Common::strlcpy(target.filename, filename, sizeof(target.filename));
+	BundleDirCache::IndexNode *found = (BundleDirCache::IndexNode *)bsearch(&target, _indexTable, _numFiles,
+			sizeof(BundleDirCache::IndexNode), (int (*)(const void *, const void *))scumm_stricmp);
+	if (found) {
+		_file->seek(_bundleTable[found->index].offset, SEEK_SET);
+		offset = _bundleTable[found->index].offset;
+		size = _bundleTable[found->index].size;
+		return _file;
+	}
+
+	return nullptr;
+}
+
+bool BundleMgr::open(const char *filename, bool &isCompressed, bool errorFlag) {
+	if (_file->isOpen())
+		return true;
+
+	// TODO
+	// if (g_scumm->openFile(*_file, filename) == false) {
+	// 	if (errorFlag) {
+	// 		error("BundleMgr::open() Can't open bundle file: %s", filename);
+	// 	} else {
+	// 		warning("BundleMgr::open() Can't open bundle file: %s", filename);
+	// 	}
+	// 	return false;
+	// }
+
+	int slot = _cache->matchFile(filename);
+	assert(slot != -1);
+	isCompressed = _cache->isSndDataExtComp(slot);
+	_numFiles = _cache->getNumFiles(slot);
+	assert(_numFiles);
+	_bundleTable = _cache->getTable(slot);
+	_indexTable = _cache->getIndexTable(slot);
+	assert(_bundleTable);
+	_compTableLoaded = false;
+	_isUncompressed = false;
+	_outputSize = 0;
+	_lastBlockDecompressedSize = 0;
+	_curDecompressedFilePos = 0;
+	_lastBlock = -1;
+
+	return true;
+}
+
+void BundleMgr::close() {
+	if (_file->isOpen()) {
+		_file->close();
+		_bundleTable = nullptr;
+		_numFiles = 0;
+		_numCompItems = 0;
+		_lastBlockDecompressedSize = 0;
+		_curDecompressedFilePos = 0;
+		_compTableLoaded = false;
+		_isUncompressed = false;
+		_lastBlock = -1;
+		_outputSize = 0;
+		_curSampleId = -1;
+		free(_compTable);
+		_compTable = nullptr;
+		free(_compInputBuff);
+		_compInputBuff = nullptr;
+	}
+}
+
+bool BundleMgr::loadCompTable(int32 index) {
+	_file->seek(_bundleTable[index].offset, SEEK_SET);
+	uint32 tag = _file->readUint32BE();
+
+	if (tag == MKTAG('i','M','U','S')) {
+		_isUncompressed = true;
+		return true;
+	}
+
+	_numCompItems = _file->readUint32BE();
+	assert(_numCompItems > 0);
+	_file->seek(4, SEEK_CUR);
+	_lastBlockDecompressedSize = _file->readUint32BE();
+	if (tag != MKTAG('C','O','M','P')) {
+		debug("BundleMgr::loadCompTable() Compressed sound %d (%s:%d) invalid (%s)", index, _file->getName(), _bundleTable[index].offset, tag2str(tag));
+		return false;
+	}
+
+	_compTable = (CompTable *)malloc(sizeof(CompTable) * _numCompItems);
+	assert(_compTable);
+	int32 maxSize = 0;
+	for (int i = 0; i < _numCompItems; i++) {
+		_compTable[i].offset = _file->readUint32BE();
+		_compTable[i].size = _file->readUint32BE();
+		_compTable[i].codec = _file->readUint32BE();
+		_file->seek(4, SEEK_CUR);
+		if (_compTable[i].size > maxSize)
+			maxSize = _compTable[i].size;
+	}
+	// CMI hack: one more byte at the end of input buffer
+	_compInputBuff = (byte *)malloc(maxSize + 1);
+	assert(_compInputBuff);
+
+	return true;
+}
+
+int32 BundleMgr::seekFile(int32 offset, int mode) {
+	// We don't actually seek the file, but instead try to find that the specified offset exists
+	// within the decompressed blocks, and save that offset in _curDecompressedFilePos
+	int result = 0;
+	switch (mode) {
+	case SEEK_END:
+		if (_isUncompressed) {
+			result = offset + _bundleTable[_curSampleId].size;
+		} else {
+			result = offset + ((_numCompItems - 1) * DIMUSE_BUN_CHUNK_SIZE) + _lastBlockDecompressedSize;
+		}
+		_curDecompressedFilePos = result;
+		break;
+	case SEEK_SET:
+	default:
+		if (_isUncompressed) {
+			result = offset;
+			_curDecompressedFilePos = result;
+		} else {
+			int destBlock = offset / DIMUSE_BUN_CHUNK_SIZE + (offset % DIMUSE_BUN_CHUNK_SIZE != 0);
+			if (destBlock <= _numCompItems) {
+				result = offset;
+				_curDecompressedFilePos = result;
+			}
+		}
+		break;
+	}
+	return result;
+}
+
+int32 BundleMgr::readFile(const char *name, int32 size, byte **comp_final, bool header_outside) {
+	int32 final_size = 0;
+
+	if (!_file->isOpen()) {
+		error("BundleMgr::readFile() File is not open");
+		return 0;
+	}
+
+	// Find the sound in the bundle
+	BundleDirCache::IndexNode target;
+	strncpy(target.filename, name, sizeof(target.filename));
+	target.filename[sizeof(target.filename) - 1] = '\0';
+	BundleDirCache::IndexNode *found = (BundleDirCache::IndexNode *)bsearch(&target, _indexTable, _numFiles,
+		sizeof(BundleDirCache::IndexNode), (int(*)(const void *, const void *))scumm_stricmp);
+
+	if (found) {
+		int32 i, finalSize, outputSize;
+		int skip, firstBlock, lastBlock;
+		int headerSize = 0;
+
+		assert(0 <= found->index && found->index < _numFiles);
+
+		if (_file->isOpen() == false) {
+			error("BundleMgr::readFile() File is not open");
+			return 0;
+		}
+
+		if (_curSampleId == -1)
+			_curSampleId = found->index;
+
+		assert(_curSampleId == found->index);
+
+		if (!_compTableLoaded) {
+			_compTableLoaded = loadCompTable(found->index);
+			if (!_compTableLoaded)
+				return 0;
+		}
+
+		if (_isUncompressed) {
+			_file->seek(_bundleTable[found->index].offset + _curDecompressedFilePos + headerSize, SEEK_SET);
+			*comp_final = (byte *)malloc(size);
+			assert(*comp_final);
+			_file->read(*comp_final, size);
+			_curDecompressedFilePos += size;
+			return size;
+		}
+
+		firstBlock = (_curDecompressedFilePos + headerSize) / DIMUSE_BUN_CHUNK_SIZE;
+		lastBlock = (_curDecompressedFilePos + headerSize + size - 1) / DIMUSE_BUN_CHUNK_SIZE;
+
+		// Clip last_block by the total number of blocks (= "comp items")
+		if ((lastBlock >= _numCompItems) && (_numCompItems > 0))
+			lastBlock = _numCompItems - 1;
+
+		int32 blocksFinalSize = DIMUSE_BUN_CHUNK_SIZE * (1 + lastBlock - firstBlock);
+		*comp_final = (byte *)malloc(blocksFinalSize);
+		assert(*comp_final);
+		finalSize = 0;
+
+		skip = (_curDecompressedFilePos + headerSize) % DIMUSE_BUN_CHUNK_SIZE; // Excess length after the last block
+
+		for (i = firstBlock; i <= lastBlock; i++) {
+			if (_lastBlock != i) {
+				// CMI hack: one more zero byte at the end of input buffer
+				_compInputBuff[_compTable[i].size] = 0;
+				_file->seek(_bundleTable[found->index].offset + _compTable[i].offset, SEEK_SET);
+				_file->read(_compInputBuff, _compTable[i].size);
+				_outputSize = BundleCodecs::decompressCodec(_compTable[i].codec, _compInputBuff, _compOutputBuff, _compTable[i].size);
+
+				if (_outputSize > DIMUSE_BUN_CHUNK_SIZE) {
+					error("_outputSize: %d", _outputSize);
+				}
+				_lastBlock = i;
+			}
+
+			outputSize = _outputSize;
+
+			if (header_outside) {
+				outputSize -= skip;
+			} else {
+				if ((headerSize != 0) && (skip >= headerSize))
+					outputSize -= skip;
+			}
+
+			if ((outputSize + skip) > DIMUSE_BUN_CHUNK_SIZE) // workaround
+				outputSize -= (outputSize + skip) - DIMUSE_BUN_CHUNK_SIZE;
+
+			if (outputSize > size)
+				outputSize = size;
+
+			assert(finalSize + outputSize <= blocksFinalSize);
+
+			memcpy(*comp_final + finalSize, _compOutputBuff + skip, outputSize);
+			finalSize += outputSize;
+
+			size -= outputSize;
+			assert(size >= 0);
+			if (size == 0)
+				break;
+
+			skip = 0;
+		}
+		_curDecompressedFilePos += finalSize;
+
+		return finalSize;
+	}
+
+	debug(2, "BundleMgr::readFile() Failed finding sound %s", name);
+	return final_size;
+}
+
+bool BundleMgr::isExtCompBun() {
+	bool isExtComp = false;
+	bool isExtComp1 = false, isExtComp2 = false, isExtComp3 = false, isExtComp4 = false;
+	this->open("voxdisk1.bun", isExtComp1); this->close();
+	this->open("voxdisk2.bun", isExtComp2); this->close();
+	this->open("musdisk1.bun", isExtComp3); this->close();
+	this->open("musdisk2.bun", isExtComp4); this->close();
+
+	isExtComp = isExtComp1 | isExtComp2 | isExtComp3 | isExtComp4;
+
+	return isExtComp;
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_bndmgr.h b/engines/grim/imuse/dimuse_bndmgr.h
new file mode 100644
index 00000000000..5e73c3534d4
--- /dev/null
+++ b/engines/grim/imuse/dimuse_bndmgr.h
@@ -0,0 +1,110 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef GRIM_IMUSE_BUNDLE_MGR_H
+#define GRIM_IMUSE_BUNDLE_MGR_H
+
+#include "common/scummsys.h"
+#include "common/debug.h"
+#include "common/file.h"
+#include "engines/grim/imuse/dimuse_defs.h"
+
+namespace Grim {
+
+class BundleDirCache {
+public:
+	struct AudioTable {
+		char filename[24];
+		int32 offset;
+		int32 size;
+	};
+
+	struct IndexNode {
+		char filename[24];
+		int32 index;
+	};
+
+private:
+
+	struct FileDirCache {
+		char fileName[20];
+		AudioTable *bundleTable;
+		int32 numFiles;
+		bool isCompressed;
+		IndexNode *indexTable;
+	} _bundleDirCache[4];
+
+public:
+	BundleDirCache();
+	~BundleDirCache();
+
+	int matchFile(const char *filename);
+	AudioTable *getTable(int slot);
+	IndexNode *getIndexTable(int slot);
+	int32 getNumFiles(int slot);
+	bool isSndDataExtComp(int slot);
+};
+
+class BundleMgr {
+
+private:
+	struct CompTable {
+		int32 offset;
+		int32 size;
+		int32 codec;
+	};
+
+	BundleDirCache *_cache;
+	BundleDirCache::AudioTable *_bundleTable;
+	BundleDirCache::IndexNode *_indexTable = nullptr;
+	CompTable *_compTable;
+
+	int _numFiles = 0;
+	int _numCompItems = 0;
+	int _lastBlockDecompressedSize = 0;
+	int _curSampleId = 0;
+	int _curDecompressedFilePos = 0;
+	Common::File *_file;
+	bool _compTableLoaded = 0;
+	bool _isUncompressed = 0;
+	int _fileBundleId = 0;
+	byte _compOutputBuff[0x2000] = {};
+	byte *_compInputBuff = nullptr;
+	int _outputSize = 0;
+	int _lastBlock = 0;
+	bool loadCompTable(int32 index);
+
+public:
+
+	BundleMgr(BundleDirCache *_cache);
+	~BundleMgr();
+
+	bool open(const char *filename, bool &isCompressed, bool errorFlag = false);
+	void close();
+	Common::SeekableReadStream *getFile(const char *filename, int32 &offset, int32 &size);
+	int32 seekFile(int32 offset, int size);
+	int32 readFile(const char *name, int32 size, byte **compFinal, bool headerOutside);
+	bool isExtCompBun();
+};
+
+} // End of namespace Grim
+
+#endif
diff --git a/engines/grim/imuse/dimuse_cmds.cpp b/engines/grim/imuse/dimuse_cmds.cpp
new file mode 100644
index 00000000000..b4a322b4c7a
--- /dev/null
+++ b/engines/grim/imuse/dimuse_cmds.cpp
@@ -0,0 +1,259 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_engine.h"
+
+namespace Grim {
+
+// We have some uintptr arguments as commands 28, 29 and 30 actually require pointer arguments
+// Unfortunately this makes function calls for other command a little less pretty...
+int IMuseDigital::cmdsHandleCmd(int cmd, uint8 *ptr, int a, int b, int c, int d, int e,
+	int f, int g, int h, int i, int j, int k, int l, int m, int n) {
+
+	// Convert the character constant (single quotes '') to string
+	char marker[5];
+	if (cmd == 17 || cmd == 18 || cmd == 19) {
+		for (int index = 0; index < 4; index++) {
+#if defined SCUMM_BIG_ENDIAN
+			marker[index] = (b >> (8 * index)) & 0xff;
+#elif defined SCUMM_LITTLE_ENDIAN
+			marker[3 - index] = (b >> (8 * index)) & 0xff;
+#endif
+		}
+		marker[4] = '\0';
+	}
+
+	switch (cmd) {
+	case DIMUSE_C_INIT:
+		return cmdsInit();
+	case DIMUSE_C_PAUSE:
+		return cmdsPause();
+	case DIMUSE_C_RESUME:
+		return cmdsResume();
+	case DIMUSE_C_SET_GRP_VOL:
+		return _groupsHandler->setGroupVol(a, b);
+	case DIMUSE_C_START_SND:
+		cmdsStartSound(a, b);
+		break;
+	case DIMUSE_C_STOP_SND:
+		cmdsStopSound(a);
+		break;
+	case DIMUSE_C_STOP_ALL_SNDS:
+		cmdsStopAllSounds();
+		break;
+	case DIMUSE_C_GET_NEXT_SND:
+		return cmdsGetNextSound(a);
+	case DIMUSE_C_SET_PARAM:
+		cmdsSetParam(a, b, c);
+		break;
+	case DIMUSE_C_GET_PARAM:
+		return cmdsGetParam(a, b);
+	case DIMUSE_C_FADE_PARAM:
+		return _fadesHandler->fadeParam(a, b, c, d);
+	case DIMUSE_C_SET_HOOK:
+		return cmdsSetHook(a, b);
+	case DIMUSE_C_GET_HOOK:
+		return cmdsGetHook(a);
+	case DIMUSE_C_SET_TRIGGER:
+		return _triggersHandler->setTrigger(a, marker, c, d, e, f, g, h, i, j, k, l, m, n);
+	case DIMUSE_C_CHECK_TRIGGER:
+		return _triggersHandler->checkTrigger(a, marker, c);
+	case DIMUSE_C_CLEAR_TRIGGER:
+		return _triggersHandler->clearTrigger(a, marker, c);
+	case DIMUSE_C_DEFER_CMD:
+		return _triggersHandler->deferCommand(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
+	case DIMUSE_C_START_STREAM:
+		return waveStartStream(a, b, c);
+	case DIMUSE_C_SWITCH_STREAM:
+		return waveSwitchStream(a, b, c, d, e);
+	case DIMUSE_C_PROCESS_STREAMS:
+		return waveProcessStreams();
+	case DIMUSE_C_FEED_STREAM:
+		return waveFeedStream(a, ptr, c, d);
+	default:
+		debug(5, "IMuseDigital::cmdsHandleCmd(): bogus/unused opcode ignored (%d).", cmd);
+		return -1;
+	}
+
+	return 0;
+}
+
+int IMuseDigital::cmdsInit() {
+	_cmdsRunning60HzCount = 0;
+	_cmdsRunning10HzCount = 0;
+
+	if (_groupsHandler->init() || _fadesHandler->init() ||
+		_triggersHandler->init() || waveInit()) {
+		return -1;
+	}
+
+	_cmdsPauseCount = 0;
+	return 48;
+}
+
+int IMuseDigital::cmdsDeinit() {
+	waveTerminate();
+	waveOutDeinit();
+	_triggersHandler->deinit();
+	_fadesHandler->deinit();
+	_cmdsPauseCount = 0;
+	_cmdsRunning60HzCount = 0;
+	_cmdsRunning10HzCount = 0;
+
+	return 0;
+}
+
+int IMuseDigital::cmdsTerminate() {
+	return 0;
+}
+
+int IMuseDigital::cmdsPause() {
+	int result = 0;
+
+	if (_cmdsPauseCount == 0) {
+		result = wavePause();
+	}
+
+	if (!result) {
+		result = _cmdsPauseCount + 1;
+	}
+	_cmdsPauseCount++;
+
+	return result;
+}
+
+int IMuseDigital::cmdsResume() {
+	int result = 0;
+
+	if (_cmdsPauseCount == 1) {
+		result = waveResume();
+	}
+
+	if (_cmdsPauseCount != 0) {
+		_cmdsPauseCount--;
+	}
+
+	if (!result) {
+		result = _cmdsPauseCount;
+	}
+
+	return result;
+}
+
+void IMuseDigital::cmdsSaveLoad(Common::Serializer &ser) {
+	// Serialize in this order:
+	// - Open files
+	// - Fades
+	// - Triggers
+	// - Pass the control to waveSaveLoad and then tracksSaveLoad, which will serialize:
+	//     - Dispatches
+	//     - Tracks (with SYNCs, if the game is COMI)
+	// - State and sequence info
+	// - Attributes
+
+	_filesHandler->saveLoad(ser);
+	_fadesHandler->saveLoad(ser);
+	_triggersHandler->saveLoad(ser);
+	waveSaveLoad(ser);
+	ser.syncAsSint32LE(_curMusicState, VER(103));
+	ser.syncAsSint32LE(_curMusicSeq, VER(103));
+	ser.syncAsSint32LE(_nextSeqToPlay, VER(103));
+	ser.syncArray(_attributes, 188, Common::Serializer::Sint32LE, VER(103));
+}
+
+int IMuseDigital::cmdsStartSound(int soundId, int priority) {
+	uint8 *src = _filesHandler->getSoundAddrData(soundId);
+
+	if (src == nullptr) {
+		debug(5, "IMuseDigital::cmdsStartSound(): ERROR: resource address for sound %d is NULL", soundId);
+		return -1;
+	}
+
+	// Check for the "iMUS" header
+	if (READ_BE_UINT32(src) == MKTAG('i', 'M', 'U', 'S'))
+		return waveStartSound(soundId, priority);
+
+	return -1;
+}
+
+int IMuseDigital::cmdsStopSound(int soundId) {
+	int result = _filesHandler->getNextSound(soundId);
+
+	if (result != 2)
+		return -1;
+
+	return waveStopSound(soundId);
+}
+
+int IMuseDigital::cmdsStopAllSounds() {
+	return _triggersHandler->clearAllTriggers() | waveStopAllSounds();
+}
+
+int IMuseDigital::cmdsGetNextSound(int soundId) {
+	return waveGetNextSound(soundId);
+}
+
+int IMuseDigital::cmdsSetParam(int soundId, int subCmd, int value) {
+	int result = _filesHandler->getNextSound(soundId);
+
+	if (result != 2)
+		return -1;
+
+	return waveSetParam(soundId, subCmd, value);
+}
+
+int IMuseDigital::cmdsGetParam(int soundId, int subCmd) {
+	int result = _filesHandler->getNextSound(soundId);
+
+	if (subCmd != 0) {
+		if (subCmd == DIMUSE_P_TRIGS_SNDS) {
+			return _triggersHandler->countPendingSounds(soundId);
+		}
+
+		if (result == 2) {
+			return waveGetParam(soundId, subCmd);
+		}
+
+		result = (subCmd == DIMUSE_P_SND_TRACK_NUM) - 1;
+	}
+
+	return result;
+}
+
+int IMuseDigital::cmdsSetHook(int soundId, int hookId) {
+	int result = _filesHandler->getNextSound(soundId);
+
+	if (result != 2)
+		return -1;
+
+	return waveSetHook(soundId, hookId);
+}
+
+int IMuseDigital::cmdsGetHook(int soundId) {
+	int result = _filesHandler->getNextSound(soundId);
+
+	if (result != 2)
+		return -1;
+
+	return waveGetHook(soundId);
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_codecs.cpp b/engines/grim/imuse/dimuse_codecs.cpp
new file mode 100644
index 00000000000..2121e9e5cfa
--- /dev/null
+++ b/engines/grim/imuse/dimuse_codecs.cpp
@@ -0,0 +1,643 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "common/scummsys.h"
+#include "common/endian.h"
+#include "common/util.h"
+#include "engines/grim/imuse/dimuse_codecs.h"
+
+#include "audio/decoders/adpcm_intern.h"
+
+namespace Grim {
+
+namespace BundleCodecs {
+
+/*
+ * The "IMC" codec below (see cases 13 & 15 in decompressCodec) is actually a
+ * variant of the IMA codec, see also
+ *   <https://multimedia.cx/simpleaudio.html>
+ *
+ * It is somewhat different, though: the standard ADPCM codecs use a fixed
+ * size for their data packets (4 bits), while the codec implemented here
+ * varies the size of each "packet" between 2 and 7 bits.
+ */
+
+static byte *_destImcTable = nullptr;
+static uint32 *_destImcTable2 = nullptr;
+
+// This table is the "big brother" of Audio::ADPCMStream::_stepAdjustTable.
+static const byte imxOtherTable[6][64] = {
+	{
+		0xFF,
+		4
+	},
+
+	{
+		0xFF, 0xFF,
+		   2,    8
+	},
+
+	{
+		0xFF, 0xFF, 0xFF, 0xFF,
+		   1,    2,    4,    6
+	},
+
+	{
+		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+		   1,    2,    4,    6,    8,   12,   16,   32
+	},
+
+	{
+		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+		   1,    2,    4,    6,    8,   10,   12,   14,
+		  16,   18,   20,   22,   24,   26,   28,   32
+	},
+
+	{
+		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+		   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
+	}
+};
+
+void releaseImcTables() {
+	free(_destImcTable);
+	_destImcTable = nullptr;
+	free(_destImcTable2);
+	_destImcTable2 = nullptr;
+}
+
+void initializeImcTables() {
+	int pos;
+
+	if (!_destImcTable) _destImcTable = (byte *)calloc(89, sizeof(byte));
+	if (!_destImcTable2) _destImcTable2 = (uint32 *)calloc(89 * 64, sizeof(uint32));
+
+	for (pos = 0; pos <= 88; ++pos) {
+		byte put = 1;
+		int32 tableValue = ((Audio::Ima_ADPCMStream::_imaTable[pos] * 4) / 7) / 2;
+		while (tableValue != 0) {
+			tableValue /= 2;
+			put++;
+		}
+		if (put < 3) {
+			put = 3;
+		}
+		if (put > 8) {
+			put = 8;
+		}
+		_destImcTable[pos] = put - 1;
+	}
+
+	for (int n = 0; n < 64; n++) {
+		for (pos = 0; pos <= 88; ++pos) {
+			int32 count = 32;
+			int32 put = 0;
+			int32 tableValue = Audio::Ima_ADPCMStream::_imaTable[pos];
+			do {
+				if ((count & n) != 0) {
+					put += tableValue;
+				}
+				count /= 2;
+				tableValue /= 2;
+			} while (count != 0);
+			_destImcTable2[n + pos * 64] = put;
+		}
+	}
+}
+
+#define NextBit                            \
+	do {                                   \
+		bit = mask & 1;                    \
+		mask >>= 1;                        \
+		if (!--bitsleft) {                 \
+			mask = READ_LE_UINT16(srcptr); \
+			srcptr += 2;                   \
+			bitsleft = 16;                 \
+		}                                  \
+	} while (0)
+
+static int32 compDecode(byte *src, byte *dst) {
+	byte *result, *srcptr = src, *dstptr = dst;
+	int data, size, bit, bitsleft = 16, mask = READ_LE_UINT16(srcptr);
+	srcptr += 2;
+
+	for (;;) {
+		NextBit;
+		if (bit) {
+			*dstptr++ = *srcptr++;
+		} else {
+			NextBit;
+			if (!bit) {
+				NextBit;
+				size = bit << 1;
+				NextBit;
+				size = (size | bit) + 3;
+				data = *srcptr++ | 0xffffff00;
+			} else {
+				data = *srcptr++;
+				size = *srcptr++;
+
+				data |= 0xfffff000 + ((size & 0xf0) << 4);
+				size = (size & 0x0f) + 3;
+
+				if (size == 3)
+					if (((*srcptr++) + 1) == 1)
+						return dstptr - dst;
+			}
+			result = dstptr + data;
+			while (size--)
+				*dstptr++ = *result++;
+		}
+	}
+}
+#undef NextBit
+
+int32 decompressADPCM(byte *compInput, byte *compOutput, int channels) {
+	byte *src;
+
+	// Decoder for the IMA ADPCM variants used in COMI.
+	// Contrary to regular IMA ADPCM, this codec uses a variable
+	// bitsize for the encoded data.
+
+	const int MAX_CHANNELS = 2;
+	int32 outputSamplesLeft;
+	int32 destPos;
+	int16 firstWord;
+	byte initialTablePos[MAX_CHANNELS] = {0, 0};
+	//int32 initialimcTableEntry[MAX_CHANNELS] = {7, 7};
+	int32 initialOutputWord[MAX_CHANNELS] = {0, 0};
+	int32 totalBitOffset, curTablePos, outputWord;
+	byte *dst;
+	int i;
+
+	// We only support mono and stereo
+	assert(channels == 1 || channels == 2);
+
+	src = compInput;
+	dst = compOutput;
+	outputSamplesLeft = 0x1000;
+
+	// Every data packet contains 0x2000 bytes of audio data
+	// when extracted. In order to encode bigger data sets,
+	// one has to split the data into multiple blocks.
+	//
+	// Every block starts with a 2 byte word. If that word is
+	// non-zero, it indicates the size of a block of raw audio
+	// data (not encoded) following it. That data we simply copy
+	// to the output buffer and then proceed by decoding the
+	// remaining data.
+	//
+	// If on the other hand the word is zero, then what follows
+	// are 7*channels bytes containing seed data for the decoder.
+	firstWord = READ_BE_UINT16(src);
+	src += 2;
+	if (firstWord != 0) {
+		// Copy raw data
+		memcpy(dst, src, firstWord);
+		dst += firstWord;
+		src += firstWord;
+		assert((firstWord & 1) == 0);
+		outputSamplesLeft -= firstWord / 2;
+	} else {
+		// Read the seed values for the decoder.
+		for (i = 0; i < channels; i++) {
+			initialTablePos[i] = *src;
+			src += 1;
+			//initialimcTableEntry[i] = READ_BE_UINT32(src);
+			src += 4;
+			initialOutputWord[i] = READ_BE_UINT32(src);
+			src += 4;
+		}
+	}
+
+	totalBitOffset = 0;
+	// The channels are encoded separately.
+	for (int chan = 0; chan < channels; chan++) {
+		// Read initial state (this makes it possible for the data stream
+		// to be split & spread across multiple data chunks.
+		curTablePos = initialTablePos[chan];
+		//imcTableEntry = initialimcTableEntry[chan];
+		outputWord = initialOutputWord[chan];
+
+		// We need to interleave the channels in the output; we achieve
+		// that by using a variables dest offset:
+		destPos = chan * 2;
+
+		const int bound = (channels == 1)
+							? outputSamplesLeft
+							: ((chan == 0)
+								? (outputSamplesLeft+1) / 2
+								: outputSamplesLeft / 2);
+		for (i = 0; i < bound; ++i) {
+			// Determine the size (in bits) of the next data packet
+			const int32 curTableEntryBitCount = _destImcTable[curTablePos];
+			assert(2 <= curTableEntryBitCount && curTableEntryBitCount <= 7);
+
+			// Read the next data packet
+			const byte *readPos = src + (totalBitOffset >> 3);
+			const uint16 readWord = (uint16)(READ_BE_UINT16(readPos) << (totalBitOffset & 7));
+			const byte packet = (byte)(readWord >> (16 - curTableEntryBitCount));
+
+			// Advance read position to the next data packet
+			totalBitOffset += curTableEntryBitCount;
+
+			// Decode the data packet into a delta value for the output signal.
+			const byte signBitMask = (1 << (curTableEntryBitCount - 1));
+			const byte dataBitMask = (signBitMask - 1);
+			const byte data = (packet & dataBitMask);
+
+			const int32 tmpA = (data << (7 - curTableEntryBitCount));
+			const int32 imcTableEntry = Audio::Ima_ADPCMStream::_imaTable[curTablePos] >> (curTableEntryBitCount - 1);
+			int32 delta = imcTableEntry + _destImcTable2[tmpA + (curTablePos * 64)];
+
+			// The topmost bit in the data packet tells is a sign bit
+			if ((packet & signBitMask) != 0) {
+				delta = -delta;
+			}
+
+			// Accumulate the delta onto the output data
+			outputWord += delta;
+
+			// Clip outputWord to 16 bit signed, and write it into the destination stream
+			outputWord = CLIP<int32>(outputWord, -0x8000, 0x7fff);
+
+			// This is being written as-is (LE), without concerns regarding endianness:
+			// this is because the internal DiMUSE mixer handles the data in LE format,
+			// and we'll convert data to the appropriate format using the QueuingAudioStream flags
+			// when flushing the final audio data to the output stream (see IMuseDigital::waveOutWrite())
+			WRITE_UINT16(dst + destPos, outputWord);
+
+			destPos += channels << 1;
+
+			// Adjust the curTablePos
+			curTablePos += (int8)imxOtherTable[curTableEntryBitCount - 2][data];
+			curTablePos = CLIP<int32>(curTablePos, 0, ARRAYSIZE(Audio::Ima_ADPCMStream::_imaTable) - 1);
+		}
+	}
+
+	return 0x2000;
+}
+
+int32 decompressCodec(int32 codec, byte *compInput, byte *compOutput, int32 inputSize) {
+	int32 outputSize;
+	int32 offset1, offset2, offset3, length, k, c, s, j, r, t, z;
+	byte *src, *t_table, *p, *ptr;
+	byte t_tmp1, t_tmp2;
+
+	switch (codec) {
+	case 0:
+		memcpy(compOutput, compInput, inputSize);
+		outputSize = inputSize;
+		break;
+
+	case 1:
+		outputSize = compDecode(compInput, compOutput);
+		break;
+
+	case 2:
+		outputSize = compDecode(compInput, compOutput);
+		p = compOutput;
+		for (z = 1; z < outputSize; z++)
+			p[z] += p[z - 1];
+		break;
+
+	case 3:
+		outputSize = compDecode(compInput, compOutput);
+		p = compOutput;
+		for (z = 2; z < outputSize; z++)
+			p[z] += p[z - 1];
+		for (z = 1; z < outputSize; z++)
+			p[z] += p[z - 1];
+		break;
+
+	case 4:
+		outputSize = compDecode(compInput, compOutput);
+		p = compOutput;
+		for (z = 2; z < outputSize; z++)
+			p[z] += p[z - 1];
+		for (z = 1; z < outputSize; z++)
+			p[z] += p[z - 1];
+
+		t_table = (byte *)calloc(outputSize, 1);
+		assert(t_table);
+
+		src = compOutput;
+		length = (outputSize << 3) / 12;
+		k = 0;
+		if (length > 0) {
+			c = -12;
+			s = 0;
+			j = 0;
+			do {
+				ptr = src + length + (k >> 1);
+				t_tmp2 = src[j];
+				if (k & 1) {
+					r = c >> 3;
+					t_table[r + 2] = ((t_tmp2 & 0x0f) << 4) | (ptr[1] >> 4);
+					t_table[r + 1] = (t_tmp2 & 0xf0) | (t_table[r + 1]);
+				} else {
+					r = s >> 3;
+					t_table[r + 0] = ((t_tmp2 & 0x0f) << 4) | (ptr[0] & 0x0f);
+					t_table[r + 1] = t_tmp2 >> 4;
+				}
+				s += 12;
+				c += 12;
+				k++;
+				j++;
+			} while (k < length);
+		}
+		offset1 = ((length - 1) * 3) >> 1;
+		t_table[offset1 + 1] = (t_table[offset1 + 1]) | (src[length - 1] & 0xf0);
+		memcpy(src, t_table, outputSize);
+		free(t_table);
+		break;
+
+	case 5:
+		outputSize = compDecode(compInput, compOutput);
+		p = compOutput;
+		for (z = 2; z < outputSize; z++)
+			p[z] += p[z - 1];
+		for (z = 1; z < outputSize; z++)
+			p[z] += p[z - 1];
+
+		t_table = (byte *)malloc(outputSize);
+		assert(t_table);
+
+		src = compOutput;
+		length = (outputSize << 3) / 12;
+		k = 1;
+		c = 0;
+		s = 12;
+		t_table[0] = src[length] >> 4;
+		t = length + k;
+		j = 1;
+		if (t > k) {
+			do {
+				t_tmp1 = *(src + length + (k >> 1));
+				t_tmp2 = src[j - 1];
+				if (k & 1) {
+					r = c >> 3;
+					t_table[r + 0] = (t_tmp2 & 0xf0) | t_table[r];
+					t_table[r + 1] = ((t_tmp2 & 0x0f) << 4) | (t_tmp1 & 0x0f);
+				} else {
+					r = s >> 3;
+					t_table[r + 0] = t_tmp2 >> 4;
+					t_table[r - 1] = ((t_tmp2 & 0x0f) << 4) | (t_tmp1 >> 4);
+				}
+				s += 12;
+				c += 12;
+				k++;
+				j++;
+			} while (k < t);
+		}
+		memcpy(src, t_table, outputSize);
+		free(t_table);
+		break;
+
+	case 6:
+		outputSize = compDecode(compInput, compOutput);
+		p = compOutput;
+		for (z = 2; z < outputSize; z++)
+			p[z] += p[z - 1];
+		for (z = 1; z < outputSize; z++)
+			p[z] += p[z - 1];
+
+		t_table = (byte *)malloc(outputSize);
+		assert(t_table);
+
+		src = compOutput;
+		length = (outputSize << 3) / 12;
+		k = 0;
+		c = 0;
+		j = 0;
+		s = -12;
+		t_table[0] = src[outputSize - 1];
+		t_table[outputSize - 1] = src[length - 1];
+		t = length - 1;
+		if (t > 0) {
+			do {
+				t_tmp1 = *(src + length + (k >> 1));
+				t_tmp2 = src[j];
+				if (k & 1) {
+					r = s >> 3;
+					t_table[r + 2] = (t_tmp2 & 0xf0) | t_table[r + 2];
+					t_table[r + 3] = ((t_tmp2 & 0x0f) << 4) | (t_tmp1 >> 4);
+				} else {
+					r = c >> 3;
+					t_table[r + 2] = t_tmp2 >> 4;
+					t_table[r + 1] = ((t_tmp2 & 0x0f) << 4) | (t_tmp1 & 0x0f);
+				}
+				s += 12;
+				c += 12;
+				k++;
+				j++;
+			} while (k < t);
+		}
+		memcpy(src, t_table, outputSize);
+		free(t_table);
+		break;
+
+	case 10:
+		outputSize = compDecode(compInput, compOutput);
+		p = compOutput;
+		for (z = 2; z < outputSize; z++)
+			p[z] += p[z - 1];
+		for (z = 1; z < outputSize; z++)
+			p[z] += p[z - 1];
+
+		t_table = (byte *)malloc(outputSize);
+		assert(t_table);
+		memcpy(t_table, p, outputSize);
+
+		offset1 = outputSize / 3;
+		offset2 = offset1 << 1;
+		offset3 = offset2;
+		src = compOutput;
+
+		while (offset1--) {
+			offset2 -= 2;
+			offset3--;
+			t_table[offset2 + 0] = src[offset1];
+			t_table[offset2 + 1] = src[offset3];
+		}
+
+		src = compOutput;
+		length = (outputSize << 3) / 12;
+		k = 0;
+		if (length > 0) {
+			c = -12;
+			s = 0;
+			do {
+				j = length + (k >> 1);
+				t_tmp1 = t_table[k];
+				if (k & 1) {
+					r = c >> 3;
+					t_tmp2 = t_table[j + 1];
+					src[r + 2] = ((t_tmp1 & 0x0f) << 4) | (t_tmp2 >> 4);
+					src[r + 1] = (src[r + 1]) | (t_tmp1 & 0xf0);
+				} else {
+					r = s >> 3;
+					t_tmp2 = t_table[j];
+					src[r + 0] = ((t_tmp1 & 0x0f) << 4) | (t_tmp2 & 0x0f);
+					src[r + 1] = t_tmp1 >> 4;
+				}
+				s += 12;
+				c += 12;
+				k++;
+			} while (k < length);
+		}
+		offset1 = ((length - 1) * 3) >> 1;
+		src[offset1 + 1] = (t_table[length] & 0xf0) | src[offset1 + 1];
+		free(t_table);
+		break;
+
+	case 11:
+		outputSize = compDecode(compInput, compOutput);
+		p = compOutput;
+		for (z = 2; z < outputSize; z++)
+			p[z] += p[z - 1];
+		for (z = 1; z < outputSize; z++)
+			p[z] += p[z - 1];
+
+		t_table = (byte *)malloc(outputSize);
+		assert(t_table);
+		memcpy(t_table, p, outputSize);
+
+		offset1 = outputSize / 3;
+		offset2 = offset1 << 1;
+		offset3 = offset2;
+		src = compOutput;
+
+		while (offset1--) {
+			offset2 -= 2;
+			offset3--;
+			t_table[offset2 + 0] = src[offset1];
+			t_table[offset2 + 1] = src[offset3];
+		}
+
+		src = compOutput;
+		length = (outputSize << 3) / 12;
+		k = 1;
+		c = 0;
+		s = 12;
+		t_tmp1 = t_table[length] >> 4;
+		src[0] = t_tmp1;
+		t = length + k;
+		if (t > k) {
+			do {
+				j = length + (k >> 1);
+				t_tmp1 = t_table[k - 1];
+				t_tmp2 = t_table[j];
+				if (k & 1) {
+					r = c >> 3;
+					src[r + 0] = (src[r]) | (t_tmp1 & 0xf0);
+					src[r + 1] = ((t_tmp1 & 0x0f) << 4) | (t_tmp2 & 0x0f);
+				} else {
+					r = s >> 3;
+					src[r + 0] = t_tmp1 >> 4;
+					src[r - 1] = ((t_tmp1 & 0x0f) << 4) | (t_tmp2 >> 4);
+				}
+				s += 12;
+				c += 12;
+				k++;
+			} while (k < t);
+		}
+		free(t_table);
+		break;
+
+	case 12:
+		outputSize = compDecode(compInput, compOutput);
+		p = compOutput;
+		for (z = 2; z < outputSize; z++)
+			p[z] += p[z - 1];
+		for (z = 1; z < outputSize; z++)
+			p[z] += p[z - 1];
+
+		t_table = (byte *)malloc(outputSize);
+		assert(t_table);
+		memcpy(t_table, p, outputSize);
+
+		offset1 = outputSize / 3;
+		offset2 = offset1 << 1;
+		offset3 = offset2;
+		src = compOutput;
+
+		while (offset1--) {
+			offset2 -= 2;
+			offset3--;
+			t_table[offset2 + 0] = src[offset1];
+			t_table[offset2 + 1] = src[offset3];
+		}
+
+		src = compOutput;
+		length = (outputSize << 3) / 12;
+		k = 0;
+		c = 0;
+		s = -12;
+		src[0] = t_table[outputSize - 1];
+		src[outputSize - 1] = t_table[length - 1];
+		t = length - 1;
+		if (t > 0) {
+			do {
+				j = length + (k >> 1);
+				t_tmp1 = t_table[k];
+				t_tmp2 = t_table[j];
+				if (k & 1) {
+					r = s >> 3;
+					src[r + 2] = (src[r + 2]) | (t_tmp1 & 0xf0);
+					src[r + 3] = ((t_tmp1 & 0x0f) << 4) | (t_tmp2 >> 4);
+				} else {
+					r = c >> 3;
+					src[r + 2] = t_tmp1 >> 4;
+					src[r + 1] = ((t_tmp1 & 0x0f) << 4) | (t_tmp2 & 0x0f);
+				}
+				s += 12;
+				c += 12;
+				k++;
+			} while (k < t);
+		}
+		free(t_table);
+		break;
+
+	case 13:
+	case 15:
+		outputSize = decompressADPCM(compInput, compOutput, (codec == 13) ? 1 : 2);
+		break;
+
+	default:
+		error("BundleCodecs::decompressCodec() Unknown codec %d", (int)codec);
+		outputSize = 0;
+		break;
+	}
+
+	return outputSize;
+}
+
+} // End of namespace BundleCodecs
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_codecs.h b/engines/grim/imuse/dimuse_codecs.h
new file mode 100644
index 00000000000..b53167b89db
--- /dev/null
+++ b/engines/grim/imuse/dimuse_codecs.h
@@ -0,0 +1,40 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef GRIM_IMUSE_CODECS_H
+#define GRIM_IMUSE_CODECS_H
+
+#include "common/scummsys.h"
+
+namespace Grim {
+
+namespace BundleCodecs {
+
+int32 decompressCodec(int32 codec, byte *compInput, byte *compOutput, int32 inputSize);
+
+void initializeImcTables();
+void releaseImcTables();
+
+} // End of namespace BundleCodecs
+
+} // End of namespace Grim
+
+#endif
diff --git a/engines/grim/imuse/dimuse_defs.h b/engines/grim/imuse/dimuse_defs.h
new file mode 100644
index 00000000000..37027c5a41b
--- /dev/null
+++ b/engines/grim/imuse/dimuse_defs.h
@@ -0,0 +1,276 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef GRIM_IMUSE_DEFS_H
+#define GRIM_IMUSE_DEFS_H
+
+namespace Grim {
+
+#define DIMUSE_MAX_GROUPS      16
+#define DIMUSE_MAX_FADES       16
+#define DIMUSE_MAX_TRIGGERS    8
+#define DIMUSE_MAX_DEFERS      8
+#define DIMUSE_MAX_TRACKS      8
+#define DIMUSE_MAX_MAP_SIZE    2048
+#define DIMUSE_MAX_DISPATCHES  8
+#define DIMUSE_MAX_STREAMZONES 50
+#define DIMUSE_MAX_FADE_VOLUME 8323072
+#define DIMUSE_MAX_STREAMS     3
+
+#define DIMUSE_LARGE_FADES    1
+#define DIMUSE_SMALL_FADES    4
+#define DIMUSE_LARGE_FADE_DIM 350000
+#define DIMUSE_SMALL_FADE_DIM 44100
+
+#define DIMUSE_BASE_SAMPLERATE 22050
+#define DIMUSE_BASE_FEEDSIZE   512
+#define DIMUSE_NUM_WAVE_BUFS   8
+#define DIMUSE_SMUSH_SOUNDID   12345678
+
+enum {
+	kTalkSoundID = 10000
+};
+
+#define DIMUSE_BUN_CHUNK_SIZE  0x2000
+#define DIMUSE_GROUP_SFX       1
+#define DIMUSE_GROUP_SPEECH    2
+#define DIMUSE_GROUP_MUSIC     3
+#define DIMUSE_GROUP_MUSICEFF  4
+#define DIMUSE_BUFFER_SPEECH   1
+#define DIMUSE_BUFFER_MUSIC    2
+#define DIMUSE_BUFFER_SFX      3
+
+#define DIMUSE_TIMER_BASE_RATE_HZ       50
+#define DIMUSE_TIMER_BASE_RATE_USEC     20000  // 1000000 / 50Hz
+#define DIMUSE_TIMER_GAIN_RED_RATE_USEC 100000 // 1000000 / 10Hz
+#define DIMUSE_TIMER_FADES_RATE_USEC    16667  // 1000000 / 60Hz
+
+// Parameters IDs
+#define DIMUSE_P_BOGUS_ID       0x0
+#define DIMUSE_P_SND_TRACK_NUM  0x100
+#define DIMUSE_P_TRIGS_SNDS     0x200
+#define DIMUSE_P_MARKER         0x300
+#define DIMUSE_P_GROUP          0x400
+#define DIMUSE_P_PRIORITY       0x500
+#define DIMUSE_P_VOLUME         0x600
+#define DIMUSE_P_PAN            0x700
+#define DIMUSE_P_DETUNE         0x800
+#define DIMUSE_P_TRANSPOSE      0x900
+#define DIMUSE_P_MAILBOX        0xA00
+#define DIMUSE_P_UNKNOWN        0xF00
+#define DIMUSE_P_SND_HAS_STREAM 0x1800
+#define DIMUSE_P_STREAM_BUFID   0x1900
+#define DIMUSE_P_SND_POS_IN_MS  0x1A00
+
+// Soundkludge command IDs
+#define DIMUSE_C_KLUDGE_SET_STATE        0x1000
+#define DIMUSE_C_KLUDGE_SET_SEQUENCE     0x1001
+#define DIMUSE_C_KLUDGE_SET_CUE_POINT    0x1002
+#define DIMUSE_C_KLUDGE_SET_ATTRIBUTE    0x1003
+#define DIMUSE_C_KLUDGE_SET_SFX_VOLUME   0x2000
+#define DIMUSE_C_KLUDGE_SET_VOICE_VOLUME 0x2001
+#define DIMUSE_C_KLUDGE_SET_MUSIC_VOLUME 0x2002
+#define DIMUSE_C_KLUDGE_STOP_ALL_SNDS    10
+#define DIMUSE_C_KLUDGE_SET_PARAM        12
+#define DIMUSE_C_KLUDGE_FADE_PARAM       14
+#define DIMUSE_C_KLUDGE_START_STREAM     25
+#define DIMUSE_C_KLUDGE_SWITCH_STREAM    26
+
+// Script command IDs
+#define DIMUSE_C_SCRIPT_INIT          0
+#define DIMUSE_C_SCRIPT_TERMINATE     1
+#define DIMUSE_C_SCRIPT_SAVE          2
+#define DIMUSE_C_SCRIPT_RESTORE       3
+#define DIMUSE_C_SCRIPT_REFRESH       4
+#define DIMUSE_C_SCRIPT_SET_STATE     5
+#define DIMUSE_C_SCRIPT_SET_SEQUENCE  6
+#define DIMUSE_C_SCRIPT_CUE_POINT     7
+#define DIMUSE_C_SCRIPT_SET_ATTRIBUTE 8
+
+// Internal command IDs
+#define DIMUSE_C_INIT             0
+#define DIMUSE_C_PAUSE            3
+#define DIMUSE_C_RESUME           4
+#define DIMUSE_C_SET_GRP_VOL      7
+#define DIMUSE_C_START_SND        8
+#define DIMUSE_C_STOP_SND         9
+#define DIMUSE_C_STOP_ALL_SNDS    10
+#define DIMUSE_C_GET_NEXT_SND     11
+#define DIMUSE_C_SET_PARAM        12
+#define DIMUSE_C_GET_PARAM        13
+#define DIMUSE_C_FADE_PARAM       14
+#define DIMUSE_C_SET_HOOK         15
+#define DIMUSE_C_GET_HOOK         16
+#define DIMUSE_C_SET_TRIGGER      17
+#define DIMUSE_C_CHECK_TRIGGER    18
+#define DIMUSE_C_CLEAR_TRIGGER    19
+#define DIMUSE_C_DEFER_CMD        20
+#define DIMUSE_C_START_STREAM     25
+#define DIMUSE_C_SWITCH_STREAM    26
+#define DIMUSE_C_PROCESS_STREAMS  27
+#define DIMUSE_C_FEED_STREAM      29
+
+// Trigger callback command ID
+#define DIMUSE_C_SCRIPT_CALLBACK  0
+
+class IMuseDigital;
+
+struct IMuseDigiDispatch;
+struct IMuseDigiTrack;
+struct IMuseDigiStreamZone;
+
+typedef struct {
+	int sound;
+	char text[256];
+	int opcode;
+	int a;
+	int b;
+	int c;
+	int d;
+	int e;
+	int f;
+	int g;
+	int h;
+	int i;
+	int j;
+	int clearLater;
+} IMuseDigiTrigger;
+
+typedef struct {
+	int counter;
+	int opcode;
+	int a;
+	int b;
+	int c;
+	int d;
+	int e;
+	int f;
+	int g;
+	int h;
+	int i;
+	int j;
+} IMuseDigiDefer;
+
+typedef struct {
+	int status;
+	int sound;
+	int param;
+	int currentVal;
+	int counter;
+	int length;
+	int slope;
+	int slopeMod;
+	int modOvfloCounter;
+	int nudge;
+} IMuseDigiFade;
+
+struct IMuseDigiTrack {
+	int index;
+	IMuseDigiTrack *prev;
+	IMuseDigiTrack *next;
+	IMuseDigiDispatch *dispatchPtr;
+	int soundId;
+	int marker;
+	int group;
+	int priority;
+	int vol;
+	int effVol;
+	int pan;
+	int detune;
+	int transpose;
+	int pitchShift;
+	int mailbox;
+	int jumpHook;
+	int32 syncSize_0;
+	byte *syncPtr_0;
+	int32 syncSize_1;
+	byte *syncPtr_1;
+	int32 syncSize_2;
+	byte *syncPtr_2;
+	int32 syncSize_3;
+	byte *syncPtr_3;
+};
+
+struct IMuseDigiStreamZone {
+	IMuseDigiStreamZone *prev;
+	IMuseDigiStreamZone *next;
+	int useFlag;
+	int32 offset;
+	int32 size;
+	int fadeFlag;
+};
+
+typedef struct {
+	int soundId;
+	int32 curOffset;
+	int32 endOffset;
+	int bufId;
+	uint8 *buf;
+	int32 bufFreeSize;
+	int32 loadSize;
+	int32 criticalSize;
+	int32 maxRead;
+	int32 loadIndex;
+	int32 readIndex;
+	int paused;
+} IMuseDigiStream;
+
+typedef struct {
+	uint8 *buffer;
+	int32 bufSize;
+	int32 loadSize;
+	int32 criticalSize;
+} IMuseDigiSndBuffer;
+
+struct IMuseDigiDispatch {
+	IMuseDigiTrack *trackPtr;
+	int wordSize;
+	int sampleRate;
+	int channelCount;
+	int32 currentOffset;
+	int32 audioRemaining;
+	int32 map[DIMUSE_MAX_MAP_SIZE];
+	IMuseDigiStream *streamPtr;
+	int streamBufID;
+	IMuseDigiStreamZone *streamZoneList;
+	int streamErrFlag;
+	uint8 *fadeBuf;
+	int32 fadeOffset;
+	int32 fadeRemaining;
+	int fadeWordSize;
+	int fadeSampleRate;
+	int fadeChannelCount;
+	int fadeSyncFlag;
+	int32 fadeSyncDelta;
+	int fadeVol;
+	int fadeSlope;
+};
+
+typedef struct {
+	int bytesPerSample;
+	int numChannels;
+	uint8 *mixBuf;
+	int mixBufSize;
+	int sizeSampleKB;
+} waveOutParamsStruct;
+
+} // End of namespace Grim
+#endif
diff --git a/engines/grim/imuse/dimuse_dispatch.cpp b/engines/grim/imuse/dimuse_dispatch.cpp
new file mode 100644
index 00000000000..6044890d6a4
--- /dev/null
+++ b/engines/grim/imuse/dimuse_dispatch.cpp
@@ -0,0 +1,1407 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/dimuse_defs.h"
+
+namespace Grim {
+
+int IMuseDigital::dispatchInit() {
+	_dispatchBuffer = (uint8 *)malloc(DIMUSE_SMALL_FADES * DIMUSE_SMALL_FADE_DIM + DIMUSE_LARGE_FADE_DIM * DIMUSE_LARGE_FADES);
+
+	if (_dispatchBuffer) {
+		_dispatchLargeFadeBufs = _dispatchBuffer;
+		_dispatchSmallFadeBufs = _dispatchBuffer + (DIMUSE_LARGE_FADE_DIM * DIMUSE_LARGE_FADES);
+
+		for (int i = 0; i < DIMUSE_LARGE_FADES; i++) {
+			_dispatchLargeFadeFlags[i] = 0;
+		}
+
+		for (int i = 0; i < DIMUSE_SMALL_FADES; i++) {
+			_dispatchSmallFadeFlags[i] = 0;
+		}
+
+		for (int i = 0; i < DIMUSE_MAX_STREAMZONES; i++) {
+			_streamZones[i].useFlag = 0;
+			_streamZones[i].fadeFlag = 0;
+			_streamZones[i].prev = nullptr;
+			_streamZones[i].next = nullptr;
+			_streamZones[i].size = 0;
+			_streamZones[i].offset = 0;
+		}
+
+		for (int i = 0; i < DIMUSE_MAX_DISPATCHES; i++) {
+			_dispatches[i].trackPtr = nullptr;
+			_dispatches[i].wordSize = 0;
+			_dispatches[i].sampleRate = 0;
+			_dispatches[i].channelCount = 0;
+			_dispatches[i].currentOffset = 0;
+			_dispatches[i].audioRemaining = 0;
+			memset(_dispatches[i].map, 0, sizeof(_dispatches[i].map));
+			_dispatches[i].streamPtr = nullptr;
+			_dispatches[i].streamBufID = 0;
+			_dispatches[i].streamZoneList = nullptr;
+			_dispatches[i].streamErrFlag = 0;
+			_dispatches[i].fadeBuf = nullptr;
+			_dispatches[i].fadeOffset = 0;
+			_dispatches[i].fadeRemaining = 0;
+			_dispatches[i].fadeWordSize = 0;
+			_dispatches[i].fadeSampleRate = 0;
+			_dispatches[i].fadeChannelCount	= 0;
+			_dispatches[i].fadeSyncFlag = 0;
+			_dispatches[i].fadeSyncDelta = 0;
+			_dispatches[i].fadeVol = 0;
+			_dispatches[i].fadeSlope = 0;
+		}
+
+	} else {
+		debug(5, "IMuseDigital::dispatchInit(): ERROR: couldn't allocate buffers\n");
+		return -1;
+	}
+
+	return 0;
+}
+
+IMuseDigiDispatch *IMuseDigital::dispatchGetDispatchByTrackId(int trackId) {
+	return &_dispatches[trackId];
+}
+
+void IMuseDigital::dispatchSaveLoad(Common::Serializer &ser) {
+
+	for (int l = 0; l < DIMUSE_MAX_DISPATCHES; l++) {
+		ser.syncAsSint32LE(_dispatches[l].wordSize, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].sampleRate, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].channelCount, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].currentOffset, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].audioRemaining, VER(103));
+		ser.syncArray(_dispatches[l].map, 2048, Common::Serializer::Sint32LE, VER(103));
+
+		// This is only needed to signal if the sound originally had a stream associated with it
+		int hasStream = 0;
+		if (ser.isSaving()) {
+			if (_dispatches[l].streamPtr)
+				hasStream = 1;
+			ser.syncAsSint32LE(hasStream, VER(103));
+		} else {
+			ser.syncAsSint32LE(hasStream, VER(103));
+			_dispatches[l].streamPtr = hasStream ? (IMuseDigiStream *)1 : nullptr;
+		}
+
+		ser.syncAsSint32LE(_dispatches[l].streamBufID, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].streamErrFlag, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].fadeOffset, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].fadeRemaining, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].fadeWordSize, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].fadeSampleRate, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].fadeChannelCount, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].fadeSyncFlag, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].fadeSyncDelta, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].fadeVol, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].fadeSlope, VER(103));
+	}
+
+	if (ser.isLoading()) {
+		for (int i = 0; i < DIMUSE_LARGE_FADES; i++) {
+			_dispatchLargeFadeFlags[i] = 0;
+		}
+
+		for (int i = 0; i < DIMUSE_SMALL_FADES; i++) {
+			_dispatchSmallFadeFlags[i] = 0;
+		}
+
+		for (int i = 0; i < DIMUSE_MAX_STREAMZONES; i++) {
+			_streamZones[i].useFlag = 0;
+		}
+	}
+}
+
+int IMuseDigital::dispatchRestoreStreamZones() {
+	IMuseDigiDispatch *curDispatchPtr;
+	IMuseDigiStreamZone *curStreamZone;
+	int32 sizeToFeed = 0x4000;
+
+	curDispatchPtr = _dispatches;
+	for (int i = 0; i < _trackCount; i++) {
+		curDispatchPtr = &_dispatches[i];
+		curDispatchPtr->fadeBuf = nullptr;
+
+		if (curDispatchPtr->trackPtr->soundId && curDispatchPtr->streamPtr) {
+			// Try allocating the stream
+			curDispatchPtr->streamPtr = streamerAllocateSound(curDispatchPtr->trackPtr->soundId, curDispatchPtr->streamBufID, sizeToFeed);
+
+			if (curDispatchPtr->streamPtr) {
+				streamerSetSoundToStreamFromOffset(curDispatchPtr->streamPtr, curDispatchPtr->trackPtr->soundId, curDispatchPtr->currentOffset);
+
+				if (curDispatchPtr->audioRemaining) {
+					// Try allocating the first streamZone of the dispatch
+					curStreamZone = dispatchAllocateStreamZone();
+					curDispatchPtr->streamZoneList = curStreamZone;
+
+					if (curStreamZone) {
+						curStreamZone->offset = curDispatchPtr->currentOffset;
+						curStreamZone->size = 0;
+						curStreamZone->fadeFlag = 0;
+					} else {
+						debug(5, "IMuseDigital::dispatchRestoreStreamZones(): unable to allocate streamZone during restore");
+					}
+				}
+			} else {
+				debug(5, "IMuseDigital::dispatchRestoreStreamZones(): unable to start stream during restore");
+			}
+		}
+	}
+	return 0;
+}
+
+int IMuseDigital::dispatchAllocateSound(IMuseDigiTrack *trackPtr, int groupId) {
+	IMuseDigiDispatch *trackDispatch;
+	int navigateMapResult;
+	int32 sizeToFeed = 0x4000;
+
+	trackDispatch = trackPtr->dispatchPtr;
+	trackDispatch->currentOffset = 0;
+	trackDispatch->audioRemaining = 0;
+	trackDispatch->fadeBuf = nullptr;
+
+	memset(trackDispatch->map, 0, sizeof(trackDispatch->map));
+
+	if (groupId) {
+		trackDispatch->streamPtr = streamerAllocateSound(trackPtr->soundId, groupId, sizeToFeed);
+		trackDispatch->streamBufID = groupId;
+
+		if (!trackDispatch->streamPtr) {
+			debug(5, "IMuseDigital::dispatchAllocateSound(): unable to allocate stream for sound %d", trackPtr->soundId);
+			return -1;
+		}
+
+		trackDispatch->streamZoneList = 0;
+		trackDispatch->streamErrFlag = 0;
+	} else {
+		trackDispatch->streamPtr = nullptr;
+	}
+
+	navigateMapResult = dispatchNavigateMap(trackDispatch);
+	if (navigateMapResult && navigateMapResult != -3) {
+		// At this point, something went wrong, so let's release the dispatch
+		debug(5, "IMuseDigital::dispatchAllocateSound(): problem starting sound (%d) in dispatch", trackPtr->soundId);
+		dispatchRelease(trackPtr);
+		return -1;
+	}
+
+	return 0;
+}
+
+int IMuseDigital::dispatchRelease(IMuseDigiTrack *trackPtr) {
+	IMuseDigiDispatch *dispatchToDeallocate;
+	IMuseDigiStreamZone *streamZoneList;
+
+	dispatchToDeallocate = trackPtr->dispatchPtr;
+
+	// Remove streamZones from list
+	if (dispatchToDeallocate->streamPtr) {
+		streamerClearSoundInStream(dispatchToDeallocate->streamPtr);
+
+		streamZoneList = dispatchToDeallocate->streamZoneList;
+		if (dispatchToDeallocate->streamZoneList) {
+			do {
+				streamZoneList->useFlag = 0;
+				removeStreamZoneFromList(&dispatchToDeallocate->streamZoneList, streamZoneList);
+				streamZoneList = dispatchToDeallocate->streamZoneList;
+			} while (dispatchToDeallocate->streamZoneList);
+		}
+	}
+
+	// Mark the fade corresponding to our fadeBuf as unused
+	if (dispatchToDeallocate->fadeBuf)
+		dispatchDeallocateFade(dispatchToDeallocate, "dispatchRelease");
+
+	return 0;
+}
+
+int IMuseDigital::dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeLength, int exitTriggerSyncFlag, int offsetFadeSyncFlag) {
+	int32 effFadeLen, effFadeSize, strZnSize;
+	int getMapResult, i;
+	IMuseDigiDispatch *curDispatch = _dispatches;
+
+	effFadeLen = fadeLength;
+
+	if (fadeLength > 2000)
+		effFadeLen = 2000;
+
+	for (i = 0; i < _trackCount; i++) {
+		curDispatch = &_dispatches[i];
+		if (oldSoundId && curDispatch->trackPtr->soundId == oldSoundId && curDispatch->streamPtr) {
+			break;
+		}
+	}
+
+	if (i >= _trackCount) {
+		debug(5, "IMuseDigital::dispatchSwitchStream(): couldn't find sound, index went past _trackCount (%d)", _trackCount);
+		return -1;
+	}
+
+	if (curDispatch->streamZoneList) {
+		if (!curDispatch->wordSize) {
+			debug(5, "IMuseDigital::dispatchSwitchStream(): found streamZoneList but NULL wordSize");
+			return -1;
+		}
+
+		if (curDispatch->fadeBuf) {
+			// Mark the fade corresponding to our fadeBuf as unused
+			dispatchDeallocateFade(curDispatch, "dispatchSwitchStream");
+		}
+
+		_dispatchFadeSize = dispatchGetFadeSize(curDispatch, effFadeLen);
+
+		strZnSize = curDispatch->streamZoneList->size;
+		if (strZnSize >= _dispatchFadeSize)
+			strZnSize = _dispatchFadeSize;
+		_dispatchFadeSize = strZnSize;
+
+		// Validate and adjust the fade dispatch size further;
+		// this should correctly align the dispatch size to avoid starting a fade without
+		// inverting the stereo image by mistake
+		dispatchValidateFadeSize(curDispatch, _dispatchFadeSize, "dispatchSwitchStream");
+
+		curDispatch->fadeBuf = dispatchAllocateFade(_dispatchFadeSize, "dispatchSwitchStream");
+
+		// If we were able to allocate a fade, set up a fade out for the old sound.
+		// We'll copy data from the stream buffer to the fade buffer
+		if (curDispatch->fadeBuf) {
+			curDispatch->fadeOffset = 0;
+			curDispatch->fadeRemaining = 0;
+			curDispatch->fadeWordSize = curDispatch->wordSize;
+			curDispatch->fadeSampleRate = curDispatch->sampleRate;
+			curDispatch->fadeChannelCount = curDispatch->channelCount;
+			curDispatch->fadeSyncFlag = exitTriggerSyncFlag | offsetFadeSyncFlag;
+			curDispatch->fadeSyncDelta = 0;
+			curDispatch->fadeVol = DIMUSE_MAX_FADE_VOLUME;
+			curDispatch->fadeSlope = 0;
+
+			while (curDispatch->fadeRemaining < _dispatchFadeSize) {
+				effFadeSize = _dispatchFadeSize - curDispatch->fadeRemaining;
+				if ((_dispatchFadeSize - curDispatch->fadeRemaining) >= 0x4000)
+					effFadeSize = 0x4000;
+
+				memcpy(&curDispatch->fadeBuf[curDispatch->fadeRemaining], streamerGetStreamBuffer(curDispatch->streamPtr, effFadeSize), effFadeSize);
+
+				curDispatch->fadeRemaining += effFadeSize;
+			}
+		} else {
+			debug(5, "IMuseDigital::dispatchSwitchStream(): WARNING: couldn't allocate fade buffer (from sound %d to sound %d)", oldSoundId, newSoundId);
+		}
+	}
+
+	// Clear fades and triggers for the old soundId
+	char emptyMarker[1] = "";
+	_fadesHandler->clearFadeStatus(curDispatch->trackPtr->soundId, -1);
+	_triggersHandler->clearTrigger(curDispatch->trackPtr->soundId, (char *)emptyMarker, -1);
+
+	// Setup the new soundId
+	curDispatch->trackPtr->soundId = newSoundId;
+
+	streamerSetReadIndex(curDispatch->streamPtr, streamerGetFreeBufferAmount(curDispatch->streamPtr));
+
+	if (offsetFadeSyncFlag && curDispatch->streamZoneList) {
+		// Start the soundId from an offset
+		streamerSetSoundToStreamFromOffset(curDispatch->streamPtr, newSoundId, curDispatch->currentOffset);
+		while (curDispatch->streamZoneList->next) {
+			curDispatch->streamZoneList->next->useFlag = 0;
+			removeStreamZoneFromList(&curDispatch->streamZoneList->next, curDispatch->streamZoneList->next);
+		}
+		curDispatch->streamZoneList->size = 0;
+
+		return 0;
+	} else {
+		// Start the soundId from the beginning
+		streamerSetSoundToStreamFromOffset(curDispatch->streamPtr, newSoundId, 0);
+
+		while (curDispatch->streamZoneList) {
+			curDispatch->streamZoneList->useFlag = 0;
+			removeStreamZoneFromList(&curDispatch->streamZoneList, curDispatch->streamZoneList);
+		}
+
+		curDispatch->currentOffset = 0;
+		curDispatch->audioRemaining = 0;
+		memset(curDispatch->map, 0, sizeof(curDispatch->map));
+
+		getMapResult = dispatchNavigateMap(curDispatch);
+		if (!getMapResult || getMapResult == -3) {
+			return 0;
+		} else {
+			debug(5, "IMuseDigital::dispatchSwitchStream(): problem switching stream in dispatch (from sound %d to sound %d)", oldSoundId, newSoundId);
+			tracksClear(curDispatch->trackPtr);
+			return -1;
+		}
+	}
+}
+
+void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedSize, int sampleRate) {
+	IMuseDigiDispatch *dispatchPtr;
+	int32 effFeedSize, effWordSize, effRemainingAudio, effRemainingFade, effSampleRate;
+	int32 inFrameCount, mixVolume, mixStartingPoint, elapsedFadeDelta;
+	int navigateMapResult;
+	uint8 *srcBuf, *soundAddrData;
+
+	dispatchPtr = trackPtr->dispatchPtr;
+	if (dispatchPtr->streamPtr && dispatchPtr->streamZoneList)
+		dispatchPredictStream(dispatchPtr);
+
+	// If a fade has previously been allocated
+	if (dispatchPtr->fadeBuf) {
+		inFrameCount = 8 * dispatchPtr->fadeRemaining / (dispatchPtr->fadeWordSize * dispatchPtr->fadeChannelCount);
+
+		effSampleRate = (trackPtr->pitchShift * dispatchPtr->fadeSampleRate) >> 8;
+
+		if (inFrameCount >= effSampleRate * feedSize / sampleRate) {
+			inFrameCount = effSampleRate * feedSize / sampleRate;
+			effFeedSize = feedSize;
+		} else {
+			effFeedSize = sampleRate * inFrameCount / effSampleRate;
+		}
+
+		if (dispatchPtr->fadeWordSize == 12 && dispatchPtr->fadeChannelCount == 1)
+			inFrameCount &= 0xFFFFFFFE;
+
+		// If the fade is still going on
+		if (inFrameCount) {
+			// Update the fade volume
+			effRemainingFade = ((dispatchPtr->fadeWordSize * dispatchPtr->fadeChannelCount) * inFrameCount) / 8;
+			mixVolume = dispatchUpdateFadeMixVolume(dispatchPtr, effRemainingFade);
+
+			// Send it all to the mixer
+			srcBuf = &dispatchPtr->fadeBuf[dispatchPtr->fadeOffset];
+
+			_internalMixer->mix(
+				srcBuf,
+				inFrameCount,
+				dispatchPtr->fadeWordSize,
+				dispatchPtr->fadeChannelCount,
+				effFeedSize,
+				0,
+				mixVolume,
+				trackPtr->pan);
+
+			dispatchPtr->fadeOffset += effRemainingFade;
+			dispatchPtr->fadeRemaining -= effRemainingFade;
+
+			// Deallocate fade if it ended
+			if (!dispatchPtr->fadeRemaining) {
+				dispatchDeallocateFade(dispatchPtr, "dispatchProcessDispatches");
+			}
+		} else {
+			debug(5, "IMuseDigital::dispatchProcessDispatches(): WARNING: fade for sound %d ends with incomplete frame (or odd 12-bit mono frame)", trackPtr->soundId);
+
+			// Fade ended, deallocate it
+			dispatchDeallocateFade(dispatchPtr, "dispatchProcessDispatches");
+		}
+
+		if (!dispatchPtr->fadeRemaining)
+			dispatchPtr->fadeBuf = nullptr;
+	}
+
+	// This index keeps track of the offset position until which we have
+	// filled the buffer; with each update it is incremented by the effective
+	// feed size.
+	mixStartingPoint = 0;
+
+	while (1) {
+		// If the current region is finished playing
+		// go check for any event on the map for the current offset
+		if (!dispatchPtr->audioRemaining) {
+			_dispatchFadeStartedFlag = 0;
+			navigateMapResult = dispatchNavigateMap(dispatchPtr);
+
+			if (navigateMapResult)
+				break;
+
+			if (_dispatchFadeStartedFlag) {
+				// We reached a JUMP, therefore we have to crossfade to
+				// the destination region: start a fade-out
+				effSampleRate = (trackPtr->pitchShift * dispatchPtr->fadeSampleRate) >> 8;
+
+				inFrameCount = 8 * dispatchPtr->fadeRemaining / (dispatchPtr->fadeWordSize * dispatchPtr->fadeChannelCount);
+				if (inFrameCount >= effSampleRate * feedSize / sampleRate) {
+					inFrameCount = effSampleRate * feedSize / sampleRate;
+					effFeedSize = feedSize;
+				} else {
+					effFeedSize = sampleRate * inFrameCount / effSampleRate;
+				}
+
+				if (dispatchPtr->fadeWordSize == 12 && dispatchPtr->fadeChannelCount == 1)
+					inFrameCount &= 0xFFFFFFFE;
+
+				if (!inFrameCount)
+					debug(5, "IMuseDigital::dispatchProcessDispatches(): WARNING: fade for sound %d ends with incomplete frame (or odd 12-bit mono frame)", trackPtr->soundId);
+
+				// Update the fade volume
+				effRemainingFade = (inFrameCount * dispatchPtr->fadeWordSize * dispatchPtr->fadeChannelCount) / 8;
+				mixVolume = dispatchUpdateFadeMixVolume(dispatchPtr, effRemainingFade);
+
+				// Send it all to the mixer
+				srcBuf = &dispatchPtr->fadeBuf[dispatchPtr->fadeOffset];
+
+				_internalMixer->mix(
+					srcBuf,
+					inFrameCount,
+					dispatchPtr->fadeWordSize,
+					dispatchPtr->fadeChannelCount,
+					effFeedSize,
+					mixStartingPoint,
+					mixVolume,
+					trackPtr->pan);
+
+				dispatchPtr->fadeOffset += effRemainingFade;
+				dispatchPtr->fadeRemaining -= effRemainingFade;
+
+				if (!dispatchPtr->fadeRemaining) {
+					// Fade ended, deallocate it
+					dispatchDeallocateFade(dispatchPtr, "dispatchProcessDispatches");
+				}
+			}
+		}
+
+		if (!feedSize)
+			return;
+
+		effSampleRate = (trackPtr->pitchShift * dispatchPtr->sampleRate) >> 8;
+
+		effWordSize = dispatchPtr->channelCount * dispatchPtr->wordSize;
+		inFrameCount = effSampleRate * feedSize / sampleRate;
+
+		if (inFrameCount <= (8 * dispatchPtr->audioRemaining / effWordSize)) {
+			effFeedSize = feedSize;
+		} else {
+			inFrameCount = 8 * dispatchPtr->audioRemaining / effWordSize;
+			effFeedSize = sampleRate * (8 * dispatchPtr->audioRemaining / effWordSize) / effSampleRate;
+		}
+
+		if (dispatchPtr->wordSize == 12 && dispatchPtr->channelCount == 1)
+			inFrameCount &= 0xFFFFFFFE;
+
+		if (!inFrameCount) {
+			if (dispatchPtr->wordSize == 12)
+				debug(5, "IMuseDigital::dispatchProcessDispatches(): WARNING: region in sound %d ends with incomplete frame (or odd 12-bit mono frame)", trackPtr->soundId);
+			tracksClear(trackPtr);
+			return;
+		}
+
+		// Play the audio of the current region
+		effRemainingAudio = (effWordSize * inFrameCount) / 8;
+
+		if (dispatchPtr->streamPtr) {
+			srcBuf = streamerGetStreamBuffer(dispatchPtr->streamPtr, effRemainingAudio);
+			if (!srcBuf) {
+				dispatchPtr->streamErrFlag = 1;
+				if (dispatchPtr->fadeBuf && dispatchPtr->fadeSyncFlag)
+					dispatchPtr->fadeSyncDelta += feedSize;
+
+				streamerQueryStream(
+					dispatchPtr->streamPtr,
+					_dispatchCurStreamBufSize,
+					_dispatchCurStreamCriticalSize,
+					_dispatchCurStreamFreeSpace,
+					_dispatchCurStreamPaused);
+
+				if (_dispatchCurStreamPaused) {
+					debug(5, "IMuseDigital::dispatchProcessDispatches(): WARNING: stopping starving paused stream for sound %d", dispatchPtr->trackPtr->soundId);
+					tracksClear(trackPtr);
+				}
+
+				return;
+			}
+			dispatchPtr->streamZoneList->offset += effRemainingAudio;
+			dispatchPtr->streamZoneList->size -= effRemainingAudio;
+			dispatchPtr->streamErrFlag = 0;
+		} else {
+			soundAddrData = _filesHandler->getSoundAddrData(trackPtr->soundId);
+			if (!soundAddrData) {
+				debug(5, "IMuseDigital::dispatchProcessDispatches(): ERROR: soundAddrData for sound %d is NULL", trackPtr->soundId);
+				// Try to gracefully play nothing instead of getting stuck on an infinite loop
+				dispatchPtr->currentOffset += effRemainingAudio;
+				dispatchPtr->audioRemaining -= effRemainingAudio;
+				return;
+			}
+
+			srcBuf = &soundAddrData[dispatchPtr->currentOffset];
+		}
+
+		if (dispatchPtr->fadeBuf) {
+			// If the fadeSyncFlag is active (e.g. we are crossfading
+			// to another version of the same music piece), do this... thing,
+			// and update the fadeSyncDelta
+			if (dispatchPtr->fadeSyncFlag) {
+				if (dispatchPtr->fadeSyncDelta) {
+					elapsedFadeDelta = effFeedSize;
+					if (effFeedSize >= dispatchPtr->fadeSyncDelta)
+						elapsedFadeDelta = dispatchPtr->fadeSyncDelta;
+
+					dispatchPtr->fadeSyncDelta -= elapsedFadeDelta;
+					effFeedSize -= elapsedFadeDelta;
+
+					effSampleRate = (trackPtr->pitchShift * dispatchPtr->sampleRate) >> 8;
+
+					inFrameCount = effFeedSize * effSampleRate / sampleRate;
+
+					if (dispatchPtr->wordSize == 12 && dispatchPtr->channelCount == 1)
+						inFrameCount &= 0xFFFFFFFE;
+
+					srcBuf = &srcBuf[effRemainingAudio - ((dispatchPtr->wordSize * inFrameCount * dispatchPtr->channelCount) / 8)];
+				}
+			}
+
+			// If there's still a fadeBuffer active in our dispatch
+			// we balance the volume of the considered track with
+			// the fade volume, effectively creating a crossfade
+			if (dispatchPtr->fadeBuf) {
+				// Fade-in
+				mixVolume = dispatchUpdateFadeSlope(dispatchPtr);
+			} else {
+				mixVolume = trackPtr->effVol;
+			}
+		} else {
+			mixVolume = trackPtr->effVol;
+		}
+
+		_internalMixer->mix(
+			srcBuf,
+			inFrameCount,
+			dispatchPtr->wordSize,
+			dispatchPtr->channelCount,
+			effFeedSize,
+			mixStartingPoint,
+			mixVolume,
+			trackPtr->pan);
+
+		mixStartingPoint += effFeedSize;
+		feedSize -= effFeedSize;
+
+		dispatchPtr->currentOffset += effRemainingAudio;
+		dispatchPtr->audioRemaining -= effRemainingAudio;
+	}
+
+	// Behavior of errors and STOP marker
+	if (navigateMapResult == -1)
+		tracksClear(trackPtr);
+
+	if (dispatchPtr->fadeBuf && dispatchPtr->fadeSyncFlag)
+		dispatchPtr->fadeSyncDelta += feedSize;
+}
+
+void IMuseDigital::dispatchPredictFirstStream() {
+	Common::StackLock lock(*_mutex);
+
+	for (int i = 0; i < _trackCount; i++) {
+		if (_dispatches[i].trackPtr->soundId && _dispatches[i].streamPtr && _dispatches[i].streamZoneList)
+			dispatchPredictStream(&_dispatches[i]);
+	}
+}
+
+int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
+	uint8 *mapCurEvent;
+	int32 blockTag, effFadeSize, elapsedFadeSize, regionOffset;
+	char *marker = NULL;
+
+	int getMapResult = dispatchGetMap(dispatchPtr);
+	if (getMapResult)
+		return getMapResult;
+
+	if (dispatchPtr->audioRemaining
+		|| (dispatchPtr->streamPtr && dispatchPtr->streamZoneList->offset != dispatchPtr->currentOffset)) {
+		debug(5, "IMuseDigital::dispatchNavigateMap(): ERROR: navigation error in dispatch");
+		return -1;
+	}
+
+	mapCurEvent = NULL;
+	while (1) {
+		mapCurEvent = dispatchGetNextMapEvent(dispatchPtr->map, dispatchPtr->currentOffset, mapCurEvent);
+
+		if (!mapCurEvent) {
+			debug(5, "IMuseDigital::dispatchNavigateMap(): ERROR: no more map events at offset %dx", dispatchPtr->currentOffset);
+			return -1;
+		}
+
+		blockTag = READ_UINT32(mapCurEvent);
+		switch (blockTag) {
+		case MKTAG('J', 'U', 'M', 'P'):
+			// Handle any event found at this offset
+			// Jump block (fixed size: 28 bytes)
+			// - The tag 'JUMP' (4 bytes)
+			// - Block size in bytes minus 8 (4 bytes)
+			// - Block offset (hook position) (4 bytes)
+			// - Jump destination offset (4 bytes)
+			// - Hook ID (4 bytes)
+			// - Fade time in ms (4 bytes)
+			if (!checkHookId(dispatchPtr->trackPtr->jumpHook, READ_UINT32(mapCurEvent + 16))) {
+				// This is the right hookId, let's jump
+				dispatchPtr->currentOffset = READ_UINT32(mapCurEvent + 12);
+				if (dispatchPtr->streamPtr) {
+					if (dispatchPtr->streamZoneList->size || !dispatchPtr->streamZoneList->next) {
+						debug(5, "IMuseDigital::dispatchNavigateMap(): next streamZone is unallocated, calling dispatchPrepareToJump()");
+						dispatchPrepareToJump(dispatchPtr, dispatchPtr->streamZoneList, mapCurEvent, 1);
+					}
+
+					debug(5, "IMuseDigital::dispatchNavigateMap(): \n"
+							 "\tJUMP found for sound %d with valid candidateHookId (%d), \n"
+							 "\tgoing to offset %d with a crossfade of %d ms",
+						  dispatchPtr->trackPtr->soundId, (int)READ_UINT32(mapCurEvent + 16),
+						  (int)READ_UINT32(mapCurEvent + 12), (int)READ_UINT32(mapCurEvent + 20));
+
+					dispatchPtr->streamZoneList->useFlag = 0;
+					removeStreamZoneFromList(&dispatchPtr->streamZoneList, dispatchPtr->streamZoneList);
+
+					if (dispatchPtr->streamZoneList->fadeFlag) {
+						if (dispatchPtr->fadeBuf) {
+							// Mark the fade corresponding to our fadeBuf as unused
+							dispatchDeallocateFade(dispatchPtr, "dispatchNavigateMap");
+						}
+
+						_dispatchJumpFadeSize = dispatchPtr->streamZoneList->size;
+						dispatchPtr->fadeBuf = dispatchAllocateFade(_dispatchJumpFadeSize, "dispatchNavigateMap");
+
+						// If the fade buffer is allocated
+						// set up the fade
+						if (dispatchPtr->fadeBuf) {
+							dispatchPtr->fadeWordSize = dispatchPtr->wordSize;
+							dispatchPtr->fadeSampleRate = dispatchPtr->sampleRate;
+							dispatchPtr->fadeChannelCount = dispatchPtr->channelCount;
+							dispatchPtr->fadeOffset = 0;
+							dispatchPtr->fadeRemaining = 0;
+							dispatchPtr->fadeSyncFlag = 0;
+							dispatchPtr->fadeSyncDelta = 0;
+							dispatchPtr->fadeVol = DIMUSE_MAX_FADE_VOLUME;
+							dispatchPtr->fadeSlope = 0;
+
+							// Clone the old sound in the fade buffer for just the duration of the fade
+							if (_dispatchJumpFadeSize) {
+								do {
+									effFadeSize = _dispatchJumpFadeSize - dispatchPtr->fadeRemaining;
+									if ((_dispatchJumpFadeSize - dispatchPtr->fadeRemaining) >= 0x4000)
+										effFadeSize = 0x4000;
+
+									memcpy(&dispatchPtr->fadeBuf[dispatchPtr->fadeRemaining],
+										   streamerGetStreamBuffer(dispatchPtr->streamPtr, effFadeSize),
+										   effFadeSize);
+
+									elapsedFadeSize = effFadeSize + dispatchPtr->fadeRemaining;
+									dispatchPtr->fadeRemaining = elapsedFadeSize;
+								} while (_dispatchJumpFadeSize > elapsedFadeSize);
+							}
+							_dispatchFadeStartedFlag = 1;
+						}
+						dispatchPtr->streamZoneList->useFlag = 0;
+						removeStreamZoneFromList(&dispatchPtr->streamZoneList, dispatchPtr->streamZoneList);
+					}
+				}
+				mapCurEvent = nullptr;
+			}
+
+			continue;
+		case MKTAG('S', 'Y', 'N', 'C'):
+		{
+			// SYNC block (fixed size: x bytes)
+			// - The tag 'SYNC' (4 bytes)
+			// - SYNC size in bytes (4 bytes)
+			// - SYNC data (variable length)
+
+			// It is possible to gather a total maximum of 4 SYNCs for a single track;
+			// this is not a problem however, as speech files only have one SYNC block,
+			// and the most we get is four (one for each character) in
+			// A Pirate I Was Meant To Be, in Part 3 of COMI
+
+			// Curiously we skip the first four bytes of data, ending up having the first
+			// four bytes of the next block in our syncPtr; but this is exactly what happens
+			// within the interpreter, so I'm not going to argue with it
+
+			int32 targetSyncSize = READ_UINT32(mapCurEvent + 4); // As per specifications above, we fetch the size
+			uint8 *mapEventStart = mapCurEvent + 4 + 4 + 4; // We skip the 'SYNC' tag, the size, and an additional 4-bytes dword
+
+			// Allocate space for the data block and fill it, 4 bytes at a time...
+			byte *syncData = (byte *)malloc(targetSyncSize);
+			uint32 *syncDwordPtr = (uint32 *)syncData;
+			uint32 *mapEventsDwordPtr = (uint32 *)mapEventStart;
+			if (syncData) {
+				for (int i = 0; i < (targetSyncSize >> 2); i++) {
+					WRITE_LE_UINT32(&syncDwordPtr[i], mapEventsDwordPtr[i]);
+				}
+			}
+
+			if (!dispatchPtr->trackPtr->syncPtr_0) {
+				dispatchPtr->trackPtr->syncPtr_0 = syncData;
+				dispatchPtr->trackPtr->syncSize_0 = targetSyncSize;
+
+			} else if (!dispatchPtr->trackPtr->syncPtr_1) {
+				dispatchPtr->trackPtr->syncPtr_1 = syncData;
+				dispatchPtr->trackPtr->syncSize_1 = targetSyncSize;
+
+			} else if (!dispatchPtr->trackPtr->syncPtr_2) {
+				dispatchPtr->trackPtr->syncPtr_2 = syncData;
+				dispatchPtr->trackPtr->syncSize_2 = targetSyncSize;
+
+			} else if (!dispatchPtr->trackPtr->syncPtr_3) {
+				dispatchPtr->trackPtr->syncPtr_3 = syncData;
+				dispatchPtr->trackPtr->syncSize_3 = targetSyncSize;
+			}
+
+			continue;
+		}
+		case MKTAG('F', 'R', 'M', 'T'):
+			// Format block (fixed size: 28 bytes)
+			// - The tag 'FRMT' (4 bytes)
+			// - Block size in bytes minus 8 (4 bytes)
+			// - Block offset (4 bytes)
+			// - Empty field (4 bytes) (which is set to 1 in Grim Fandango, I suspect this is the endianness)
+			// - Word size between 8, 12 and 16 (4 bytes)
+			// - Sample rate (4 bytes)
+			// - Number of channels (4 bytes)
+			dispatchPtr->wordSize = READ_UINT32(mapCurEvent + 16);
+			dispatchPtr->sampleRate = READ_UINT32(mapCurEvent + 20);
+			dispatchPtr->channelCount = READ_UINT32(mapCurEvent + 24);
+
+			continue;
+		case MKTAG('R', 'E', 'G', 'N'):
+			// Region block (fixed size: 16 bytes)
+			// - The tag 'REGN' (4 bytes)
+			// - Block size in bytes minus 8 (4 bytes)
+			// - Block offset (4 bytes)
+			// - Region length (4 bytes)
+			regionOffset = READ_UINT32(mapCurEvent + 8);
+			if (regionOffset == dispatchPtr->currentOffset) {
+				dispatchPtr->audioRemaining = READ_UINT32(mapCurEvent + 12);
+				return 0;
+			} else {
+				debug(5, "IMuseDigital::dispatchNavigateMap(): ERROR: region offset %d != currentOffset %d", regionOffset, dispatchPtr->currentOffset);
+				return -1;
+			}
+		case MKTAG('S', 'T', 'O', 'P'):
+			// Stop block (fixed size: 12 bytes)
+			// Contains:
+			// - The tag 'STOP' (4 bytes)
+			// - Block size in bytes minus 8 (4 bytes)
+			// - Block offset (4 bytes)
+			return -1;
+		case MKTAG('T', 'E', 'X', 'T'):
+			// Marker block (variable size)
+			// Contains:
+			// - The tag 'TEXT' (4 bytes)
+			// - Block size in bytes minus 8 (4 bytes)
+			// - Block offset (4 bytes)
+			// - A string of characters ending with '\0' (variable length)
+			marker = (char *)mapCurEvent + 12;
+			_triggersHandler->processTriggers(dispatchPtr->trackPtr->soundId, marker);
+			if (dispatchPtr->audioRemaining)
+				return 0;
+
+			continue;
+		default:
+			debug(5, "IMuseDigital::dispatchNavigateMap(): ERROR: Unrecognized map event at offset %dx", dispatchPtr->currentOffset);
+			break;
+		};
+	}
+	return -1;
+}
+
+int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
+	int32 *dstMap;
+	uint8 *rawMap, *copiedBuf, *soundAddrData;
+	int32 size;
+
+	dstMap = dispatchPtr->map;
+
+	// If there's no map, try to fetch it
+	if (dispatchPtr->map[0] != MKTAG('M', 'A', 'P', ' ')) {
+		if (dispatchPtr->currentOffset) {
+			debug(5, "IMuseDigital::dispatchNavigateMap(): found offset but no map");
+			return -1;
+		}
+
+		// If there's a streamPtr it means that this is a sound loaded
+		// from a bundle (either music or speech)
+		if (dispatchPtr->streamPtr) {
+			copiedBuf = (uint8 *)streamerGetStreamBufferAtOffset(dispatchPtr->streamPtr, 0, 0x10);
+
+			if (!copiedBuf) {
+				return -3;
+			}
+
+			if (READ_BE_UINT32(copiedBuf) == MKTAG('i', 'M', 'U', 'S') && READ_BE_UINT32(copiedBuf + 8) == MKTAG('M', 'A', 'P', ' ')) {
+				size = READ_BE_UINT32(copiedBuf + 12) + 24;
+				if (!streamerGetStreamBufferAtOffset(dispatchPtr->streamPtr, 0, size)) {
+					return -3;
+				}
+				rawMap = (uint8 *)streamerGetStreamBuffer(dispatchPtr->streamPtr, size);
+				if (!rawMap) {
+					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: stream read failed after view succeeded");
+					return -1;
+				}
+
+				dispatchPtr->currentOffset = size;
+				if (dispatchConvertMap(rawMap + 8, dstMap)) {
+					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: dispatchConvertMap() failed");
+					return -1;
+				}
+
+				if (dispatchPtr->map[2] != MKTAG('F', 'R', 'M', 'T')) {
+					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected 'FRMT' at start of map");
+					return -1;
+				}
+
+				if (dispatchPtr->map[4] != dispatchPtr->currentOffset) {
+					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected data to follow map");
+					return -1;
+				} else {
+					if (dispatchPtr->streamZoneList) {
+						debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected NULL streamZoneList");
+						return -1;
+					}
+
+					dispatchPtr->streamZoneList = dispatchAllocateStreamZone();
+					if (!dispatchPtr->streamZoneList) {
+						debug(5, "IMuseDigital::dispatchGetMap(): ERROR: couldn't allocate zone");
+						return -1;
+					}
+
+					dispatchPtr->streamZoneList->offset = dispatchPtr->currentOffset;
+					dispatchPtr->streamZoneList->size = streamerGetFreeBufferAmount(dispatchPtr->streamPtr);
+					dispatchPtr->streamZoneList->fadeFlag = 0;
+				}
+			} else {
+				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: unrecognized file format in stream buffer");
+				return -1;
+			}
+
+		} else {
+			// Otherwise, this is a SFX and we must load it using its resource pointer
+			soundAddrData = _filesHandler->getSoundAddrData(dispatchPtr->trackPtr->soundId);
+
+			if (!soundAddrData) {
+				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: couldn't get sound address");
+				return -1;
+			}
+
+			if (READ_BE_UINT32(soundAddrData) == MKTAG('i', 'M', 'U', 'S') && READ_BE_UINT32(soundAddrData + 8) == MKTAG('M', 'A', 'P', ' ')) {
+				dispatchPtr->currentOffset = READ_BE_UINT32(soundAddrData + 12) + 24;
+				if (dispatchConvertMap((soundAddrData + 8), dstMap)) {
+					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: dispatchConvertMap() failure");
+					return -1;
+				}
+
+				if (dispatchPtr->map[2] != MKTAG('F', 'R', 'M', 'T')) {
+					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected 'FRMT' at start of map");
+					return -1;
+				}
+
+				if (dispatchPtr->map[4] != dispatchPtr->currentOffset) {
+					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected data to follow map");
+					return -1;
+				}
+			} else {
+				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: unrecognized file format in stream buffer");
+				return -1;
+			}
+		}
+	}
+
+	return 0;
+}
+
+int IMuseDigital::dispatchConvertMap(uint8 *rawMap, int32 *destMap) {
+	int32 effMapSize;
+	uint8 *mapCurPos;
+	int32 blockName;
+	uint8 *blockSizePtr;
+	uint32 blockSizeMin8;
+	uint8 *firstChar;
+	uint8 *otherChars;
+	uint32 remainingFieldsNum;
+	int32 bytesUntilEndOfMap;
+	uint8 *endOfMapPtr;
+
+	if (READ_BE_UINT32(rawMap) == MKTAG('M', 'A', 'P', ' ')) {
+		bytesUntilEndOfMap = READ_BE_UINT32(rawMap + 4);
+		effMapSize = bytesUntilEndOfMap + 8;
+		if (effMapSize <= 0x2000) {
+			memcpy(destMap, rawMap, effMapSize);
+
+			// Fill (or rather, swap32) the fields:
+			// - The 4 bytes string 'MAP '
+			// - Size of the map
+			destMap[0] = READ_BE_UINT32(destMap);
+			destMap[1] = READ_BE_UINT32(destMap + 4);
+
+			mapCurPos = (uint8 *)destMap + 8;
+			endOfMapPtr = (uint8 *)destMap + effMapSize;
+
+			// Swap32 the rest of the map
+			while (mapCurPos < endOfMapPtr) {
+				// Swap32 the 4 characters block name
+				int32 swapped = READ_BE_UINT32(mapCurPos);
+				memcpy(mapCurPos, &swapped, 4);
+				blockName = swapped;
+
+				// Advance and Swap32 the block size (minus 8) field
+				blockSizePtr = mapCurPos + 4;
+				blockSizeMin8 = READ_BE_UINT32(blockSizePtr);
+				memcpy(blockSizePtr, &blockSizeMin8, 4);
+				mapCurPos = blockSizePtr + 4;
+
+				// Swapping32 a TEXT block is different:
+				// it also contains single characters, so we skip them
+				// since they're already good like this
+				if (blockName == MKTAG('T', 'E', 'X', 'T')) {
+					// Swap32 the block offset position
+					swapped = READ_BE_UINT32(mapCurPos);
+					memcpy(mapCurPos, &swapped, 4);
+
+					// Skip the single characters
+					firstChar = mapCurPos + 4;
+					mapCurPos += 5;
+					if (*firstChar) {
+						do {
+							otherChars = mapCurPos++;
+						} while (*otherChars);
+					}
+				} else if ((blockSizeMin8 & 0xFFFFFFFC) != 0) {
+					// Basically divide by 4 to retrieve the number
+					// of fields to swap
+					remainingFieldsNum = blockSizeMin8 >> 2;
+
+					// ...and swap them of course
+					do {
+						swapped = READ_BE_UINT32(mapCurPos);
+						memcpy(mapCurPos, &swapped, 4);
+						mapCurPos += 4;
+						--remainingFieldsNum;
+					} while (remainingFieldsNum);
+				}
+			}
+
+			// Just a sanity check to see if we've parsed the whole map
+			if ((uint8 *)destMap + bytesUntilEndOfMap - mapCurPos == -8) {
+				return 0;
+			} else {
+				debug(5, "IMuseDigital::dispatchConvertMap(): ERROR: converted wrong number of bytes");
+				return -1;
+			}
+		} else {
+			debug(5, "IMuseDigital::dispatchConvertMap(): ERROR: map is too big (%d)", effMapSize);
+			return -1;
+		}
+	} else {
+		debug(5, "IMuseDigital::dispatchConvertMap(): ERROR: got bogus map");
+		return -1;
+	}
+
+	return 0;
+}
+
+uint8 *IMuseDigital::dispatchGetNextMapEvent(int32 *mapPtr, int32 soundOffset, uint8 *mapEvent) {
+	if (mapEvent) {
+		// Advance the map to the next block (READ_UINT32(mapEvent + 4) + 8 is the size of the block)
+		mapEvent = mapEvent + READ_UINT32(mapEvent + 4) + 8;
+
+		if ((uint8 *)&mapPtr[2] + mapPtr[1] > mapEvent) {
+			if ((int32)READ_UINT32(mapEvent + 8) != soundOffset) {
+				debug(5, "IMuseDigital::dispatchGetNextMapEvent(): ERROR: no more events at offset %d", soundOffset);
+				return nullptr;
+			}
+		} else {
+			debug(5, "IMuseDigital::dispatchGetNextMapEvent(): ERROR: map overrun");
+			return nullptr;
+		}
+
+	} else {
+		// Init the current map position starting from the first block
+		// (cells 0 and 1 are the tag 'MAP ' and the map size respectively)
+		mapEvent = (uint8 *)&mapPtr[2];
+
+		// Search for the block with the same offset as ours
+		while ((int32)READ_UINT32(mapEvent + 8) != soundOffset) {
+			// Check if we've overrun the offset, to make sure
+			// that there actually is an event at our offset
+			mapEvent = mapEvent + READ_UINT32(mapEvent + 4) + 8;
+
+			if ((uint8 *)&mapPtr[2] + mapPtr[1] <= mapEvent) {
+				debug(5, "IMuseDigital::dispatchGetNextMapEvent(): ERROR: couldn't find event at offset %d", soundOffset);
+				return nullptr;
+			}
+		}
+	}
+
+	return mapEvent;
+}
+
+void IMuseDigital::dispatchPredictStream(IMuseDigiDispatch *dispatchPtr) {
+	IMuseDigiStreamZone *szTmp, *lastStreamInList, *curStrZn;
+	int32 cumulativeStreamOffset;
+	uint8 *jumpParameters;
+
+	if (!dispatchPtr->streamPtr || !dispatchPtr->streamZoneList) {
+		debug(5, "IMuseDigital::dispatchPredictStream(): ERROR: NULL streamId or streamZoneList");
+		return;
+	}
+
+	szTmp = dispatchPtr->streamZoneList;
+
+	// Get the offset which our stream is currently at
+	cumulativeStreamOffset = 0;
+	do {
+		cumulativeStreamOffset += szTmp->size;
+		lastStreamInList = szTmp;
+		szTmp = szTmp->next;
+	} while (szTmp);
+
+	lastStreamInList->size += streamerGetFreeBufferAmount(dispatchPtr->streamPtr) - cumulativeStreamOffset;
+	curStrZn = dispatchPtr->streamZoneList;
+
+	for (_dispatchBufferedHookId = dispatchPtr->trackPtr->jumpHook; curStrZn; curStrZn = curStrZn->next) {
+		if (!curStrZn->fadeFlag) {
+			jumpParameters = dispatchCheckForJump(dispatchPtr->map, curStrZn, _dispatchBufferedHookId);
+			if (jumpParameters) {
+				// If we've reached a JUMP and it's successful, allocate the streamZone of the destination
+				dispatchPrepareToJump(dispatchPtr, curStrZn, jumpParameters, 0);
+			} else {
+				// If we don't have to jump, just play the next streamZone available
+				dispatchStreamNextZone(dispatchPtr, curStrZn);
+			}
+		}
+	}
+}
+
+uint8 *IMuseDigital::dispatchCheckForJump(int32 *mapPtr, IMuseDigiStreamZone *strZnPtr, int &candidateHookId) {
+	uint8 *curMapPlace = (uint8 *)&mapPtr[2];
+	uint8 *endOfMap = (uint8 *)&mapPtr[2] + mapPtr[1];
+	int32 mapPlaceTag, jumpHookPos, jumpHookId, bytesUntilNextPlace;
+
+	while (curMapPlace < endOfMap) {
+		mapPlaceTag = READ_UINT32(curMapPlace);
+		bytesUntilNextPlace = READ_UINT32(curMapPlace + 4) + 8;
+
+		if (mapPlaceTag == MKTAG('J', 'U', 'M', 'P')) {
+			jumpHookPos = READ_UINT32(curMapPlace + 8);
+			jumpHookId = READ_UINT32(curMapPlace + 16);
+
+			if (jumpHookPos > strZnPtr->offset && jumpHookPos <= strZnPtr->size + strZnPtr->offset) {
+				if (!checkHookId(candidateHookId, jumpHookId))
+					return curMapPlace;
+			}
+		}
+		// Advance the map to the next place
+		curMapPlace = curMapPlace + bytesUntilNextPlace;
+	}
+
+	return nullptr;
+}
+
+void IMuseDigital::dispatchPrepareToJump(IMuseDigiDispatch *dispatchPtr, IMuseDigiStreamZone *strZnPtr, uint8 *jumpParams, int calledFromNavigateMap) {
+	int32 hookPosition, jumpDestination, fadeTime;
+	IMuseDigiStreamZone *nextStreamZone;
+	IMuseDigiStreamZone *zoneForJump = nullptr;
+	IMuseDigiStreamZone *zoneAfterJump;
+	uint32 streamOffset;
+	IMuseDigiStreamZone *zoneCycle;
+
+	// jumpParams format (assuming jumpParams is int32*):
+	// jumpParams[0]: four bytes which form the string 'JUMP'
+	// jumpParams[1]: block size in bytes minus 8 (16 for a JUMP block like this one; total == 24 bytes)
+	// jumpParams[2]: hook position
+	// jumpParams[3]: jump destination
+	// jumpParams[4]: hook ID
+	// jumpParams[5]: fade time in milliseconds
+
+	hookPosition = READ_UINT32(jumpParams + 8);
+	jumpDestination = READ_UINT32(jumpParams + 12);
+	fadeTime = READ_UINT32(jumpParams + 20);
+
+	// Edge cases handling
+	if (strZnPtr->size + strZnPtr->offset == hookPosition) {
+		nextStreamZone = strZnPtr->next;
+		if (nextStreamZone) {
+			if (nextStreamZone->fadeFlag) {
+				// Avoid jumping if the next stream zone is already fading
+				// and its ending position is our jump destination.
+				// Basically: cancel the jump if there's already a fade in progress
+				if (nextStreamZone->offset == hookPosition) {
+					if (nextStreamZone->next) {
+						if (nextStreamZone->next->offset == jumpDestination)
+							return;
+					}
+				}
+			} else {
+				// Avoid jumping if we're trying to jump to the next stream zone
+				if (nextStreamZone->offset == jumpDestination)
+					return;
+			}
+		}
+	}
+
+	// Maximum size of the dispatch for the fade (in bytes)
+	_dispatchSize = dispatchGetFadeSize(dispatchPtr, fadeTime);
+
+	// If this function is being called from dispatchPredictStream,
+	// avoid accepting an oversized dispatch
+	if (!calledFromNavigateMap) {
+		if (_dispatchSize > strZnPtr->size + strZnPtr->offset - hookPosition)
+			return;
+	}
+
+	// Cap the dispatch size, if oversized
+	if (_dispatchSize > strZnPtr->size + strZnPtr->offset - hookPosition)
+		_dispatchSize = strZnPtr->size + strZnPtr->offset - hookPosition;
+
+	// This prevents starting a fade with an inverted stereo image
+	dispatchValidateFadeSize(dispatchPtr, _dispatchSize, "dispatchPrepareToJump");
+
+	if (dispatchPtr->fadeRemaining)
+		_dispatchSize = 0;
+
+	// Try allocating the two streamZones needed for the jump
+	if (_dispatchSize) {
+		zoneForJump = dispatchAllocateStreamZone();
+		if (!zoneForJump) {
+			debug(5, "IMuseDigital::dispatchPrepareToJump(): ERROR: couldn't allocate streamZone");
+			return;
+		}
+	}
+
+	zoneAfterJump = dispatchAllocateStreamZone();
+	if (!zoneAfterJump) {
+		debug(5, "IMuseDigital::dispatchPrepareToJump(): ERROR: couldn't allocate streamZone");
+		return;
+	}
+
+	strZnPtr->size = hookPosition - strZnPtr->offset;
+	streamOffset = hookPosition - strZnPtr->offset + _dispatchSize;
+
+	// Go to the interested stream zone to calculate the stream offset,
+	// and schedule the sound to stream with that offset
+	zoneCycle = dispatchPtr->streamZoneList;
+	while (zoneCycle != strZnPtr) {
+		streamOffset += zoneCycle->size;
+		zoneCycle = zoneCycle->next;
+	}
+
+	streamerSetLoadIndex(dispatchPtr->streamPtr, streamOffset);
+
+	while (strZnPtr->next) {
+		strZnPtr->next->useFlag = 0;
+		removeStreamZoneFromList(&strZnPtr->next, strZnPtr->next);
+	}
+
+	streamerSetSoundToStreamFromOffset(dispatchPtr->streamPtr,
+		dispatchPtr->trackPtr->soundId, jumpDestination);
+
+	// Prepare the fading zone for the jump
+	// and also a subsequent empty dummy zone
+	if (_dispatchSize) {
+		strZnPtr->next = zoneForJump;
+		zoneForJump->prev = strZnPtr;
+		strZnPtr = zoneForJump;
+		zoneForJump->next = 0;
+		zoneForJump->offset = hookPosition;
+		zoneForJump->size = _dispatchSize;
+		zoneForJump->fadeFlag = 1;
+	}
+
+	strZnPtr->next = zoneAfterJump;
+	zoneAfterJump->prev = strZnPtr;
+	zoneAfterJump->next = nullptr;
+	zoneAfterJump->offset = jumpDestination;
+	zoneAfterJump->size = 0;
+	zoneAfterJump->fadeFlag = 0;
+}
+
+void IMuseDigital::dispatchStreamNextZone(IMuseDigiDispatch *dispatchPtr, IMuseDigiStreamZone *strZnPtr) {
+	int32 cumulativeStreamOffset;
+	IMuseDigiStreamZone *szTmp;
+
+	if (strZnPtr->next) {
+		cumulativeStreamOffset = strZnPtr->size;
+		szTmp = dispatchPtr->streamZoneList;
+		while (szTmp != strZnPtr) {
+			cumulativeStreamOffset += szTmp->size;
+			szTmp = szTmp->next;
+		}
+
+		// Set the stream load index of the sound to the new streamZone
+		streamerSetLoadIndex(dispatchPtr->streamPtr, cumulativeStreamOffset);
+
+		// Remove che previous streamZone from the list, we don't need it anymore
+		while (strZnPtr->next->prev) {
+			strZnPtr->next->prev->useFlag = 0;
+			removeStreamZoneFromList(&strZnPtr->next, strZnPtr->next->prev);
+		}
+
+		streamerSetSoundToStreamFromOffset(
+			dispatchPtr->streamPtr,
+			dispatchPtr->trackPtr->soundId,
+			strZnPtr->size + strZnPtr->offset);
+	}
+}
+
+IMuseDigiStreamZone *IMuseDigital::dispatchAllocateStreamZone() {
+	for (int i = 0; i < DIMUSE_MAX_STREAMZONES; i++) {
+		if (_streamZones[i].useFlag == 0) {
+			_streamZones[i].prev = 0;
+			_streamZones[i].next = 0;
+			_streamZones[i].useFlag = 1;
+			_streamZones[i].offset = 0;
+			_streamZones[i].size = 0;
+			_streamZones[i].fadeFlag = 0;
+
+			return &_streamZones[i];
+		}
+	}
+	debug(5, "IMuseDigital::dispatchAllocateStreamZone(): ERROR: out of streamZones");
+	return nullptr;
+}
+
+uint8 *IMuseDigital::dispatchAllocateFade(int32 &fadeSize, const char *function) {
+	uint8 *allocatedFadeBuf = nullptr;
+	if (fadeSize > DIMUSE_LARGE_FADE_DIM) {
+		debug(5, "IMuseDigital::dispatchAllocateFade(): WARNING: requested fade too large (%d) in %s()", fadeSize, function);
+		fadeSize = DIMUSE_LARGE_FADE_DIM;
+	}
+
+	if (fadeSize <= DIMUSE_SMALL_FADE_DIM) { // Small fade
+		for (int i = 0; i <= DIMUSE_SMALL_FADES; i++) {
+			if (i == DIMUSE_SMALL_FADES) {
+				debug(5, "IMuseDigital::dispatchAllocateFade(): couldn't allocate small fade buffer in %s()", function);
+				allocatedFadeBuf = nullptr;
+				break;
+			}
+
+			if (!_dispatchSmallFadeFlags[i]) {
+				_dispatchSmallFadeFlags[i] = 1;
+				allocatedFadeBuf = &_dispatchSmallFadeBufs[DIMUSE_SMALL_FADE_DIM * i];
+				break;
+			}
+		}
+	} else { // Large fade
+		for (int i = 0; i <= DIMUSE_LARGE_FADES; i++) {
+			if (i == DIMUSE_LARGE_FADES) {
+				debug(5, "IMuseDigital::dispatchAllocateFade(): couldn't allocate large fade buffer in %s()", function);
+				allocatedFadeBuf = nullptr;
+				break;
+			}
+
+			if (!_dispatchLargeFadeFlags[i]) {
+				_dispatchLargeFadeFlags[i] = 1;
+				allocatedFadeBuf = &_dispatchLargeFadeBufs[DIMUSE_LARGE_FADE_DIM * i];
+				break;
+			}
+		}
+
+		// Fallback to a small fade if large fades are unavailable
+		if (!allocatedFadeBuf) {
+			for (int i = 0; i <= DIMUSE_SMALL_FADES; i++) {
+				if (i == DIMUSE_SMALL_FADES) {
+					debug(5, "IMuseDigital::dispatchAllocateFade(): couldn't allocate small fade buffer in %s()", function);
+					allocatedFadeBuf = nullptr;
+					break;
+				}
+
+				if (!_dispatchSmallFadeFlags[i]) {
+					_dispatchSmallFadeFlags[i] = 1;
+					allocatedFadeBuf = &_dispatchSmallFadeBufs[DIMUSE_SMALL_FADE_DIM * i];
+					break;
+				}
+			}
+		}
+	}
+
+	return allocatedFadeBuf;
+}
+
+void IMuseDigital::dispatchDeallocateFade(IMuseDigiDispatch *dispatchPtr, const char *function) {
+	// This function flags the fade corresponding to our fadeBuf as unused
+
+	// First, check if our fade buffer is one of the large fade buffers
+	for (int i = 0; i < DIMUSE_LARGE_FADES; i++) {
+		if (_dispatchLargeFadeBufs + (DIMUSE_LARGE_FADE_DIM * i) == dispatchPtr->fadeBuf) { // Found it!
+			if (_dispatchLargeFadeFlags[i] == 0) {
+				debug(5, "IMuseDigital::dispatchDeallocateFade(): redundant large fade buf de-allocation in %s()", function);
+			}
+			_dispatchLargeFadeFlags[i] = 0;
+			return;
+		}
+	}
+
+	// If not, check between the small fade buffers
+	for (int j = 0; j < DIMUSE_SMALL_FADES; j++) {
+		if (_dispatchSmallFadeBufs + (DIMUSE_SMALL_FADE_DIM * j) == dispatchPtr->fadeBuf) { // Found it!
+			if (_dispatchSmallFadeFlags[j] == 0) {
+				debug(5, "IMuseDigital::dispatchDeallocateFade(): redundant small fade buf de-allocation in %s()", function);
+			}
+			_dispatchSmallFadeFlags[j] = 0;
+			return;
+		}
+	}
+
+	debug(5, "IMuseDigital::dispatchDeallocateFade(): couldn't find fade buf to de-allocate in %s()", function);
+}
+
+int IMuseDigital::dispatchGetFadeSize(IMuseDigiDispatch *dispatchPtr, int fadeLength) {
+	return (dispatchPtr->wordSize * dispatchPtr->channelCount * ((dispatchPtr->sampleRate * fadeLength / 1000) & 0xFFFFFFFE)) / 8;
+}
+
+void IMuseDigital::dispatchValidateFadeSize(IMuseDigiDispatch *dispatchPtr, int32 &dispatchSize, const char *function) {
+	int alignmentModDividend;
+	if (dispatchPtr->wordSize == 8) {
+		alignmentModDividend = dispatchPtr->channelCount * 1;
+	} else {
+		alignmentModDividend = dispatchPtr->channelCount * ((dispatchPtr->wordSize == 12) + 2);
+	}
+
+	if (alignmentModDividend) {
+		dispatchSize -= dispatchSize % alignmentModDividend;
+	} else {
+		debug(5, "IMuseDigital::dispatchValidateFadeSize(): WARNING: tried mod by 0 while validating fade size in %s(), ignored", function);
+	}
+}
+
+int IMuseDigital::dispatchUpdateFadeMixVolume(IMuseDigiDispatch *dispatchPtr, int32 remainingFade) {
+	int mixVolume = (((dispatchPtr->fadeVol / 65536) + 1) * dispatchPtr->trackPtr->effVol) / 128;
+	dispatchPtr->fadeVol += remainingFade * dispatchPtr->fadeSlope;
+
+	if (dispatchPtr->fadeVol < 0)
+		dispatchPtr->fadeVol = 0;
+	if (dispatchPtr->fadeVol > DIMUSE_MAX_FADE_VOLUME)
+		dispatchPtr->fadeVol = DIMUSE_MAX_FADE_VOLUME;
+
+	return mixVolume;
+}
+
+int IMuseDigital::dispatchUpdateFadeSlope(IMuseDigiDispatch *dispatchPtr) {
+	int32 updatedVolume, effRemainingFade;
+
+	updatedVolume = (dispatchPtr->trackPtr->effVol * (128 - (dispatchPtr->fadeVol / 65536))) / 128;
+	if (!dispatchPtr->fadeSlope) {
+		effRemainingFade = dispatchPtr->fadeRemaining;
+		if (effRemainingFade <= 1)
+			effRemainingFade = 2;
+		dispatchPtr->fadeSlope = -(DIMUSE_MAX_FADE_VOLUME / effRemainingFade);
+	}
+
+	return updatedVolume;
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_engine.cpp b/engines/grim/imuse/dimuse_engine.cpp
new file mode 100644
index 00000000000..6138ad7acae
--- /dev/null
+++ b/engines/grim/imuse/dimuse_engine.cpp
@@ -0,0 +1,766 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "common/system.h"
+#include "common/timer.h"
+
+#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/dimuse_defs.h"
+#include "engines/grim/imuse/dimuse_bndmgr.h"
+#include "engines/grim/imuse/dimuse_sndmgr.h"
+#include "engines/grim/imuse/dimuse_tables.h"
+
+#include "audio/audiostream.h"
+#include "audio/mixer.h"
+
+namespace Grim {
+
+void IMuseDigital::timer_handler(void *refCon) {
+	IMuseDigital *diMUSE = (IMuseDigital *)refCon;
+	diMUSE->callback();
+}
+
+IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode)
+	: _mixer(mixer), _mutex(mutex) {
+	assert(mixer);
+
+	// 50 Hz rate for the callback
+	_callbackFps = DIMUSE_TIMER_BASE_RATE_HZ;
+	_usecPerInt = DIMUSE_TIMER_BASE_RATE_USEC;
+
+	_lowLatencyMode = lowLatencyMode;
+	_internalSampleRate = sampleRate;
+	_internalFeedSize = (int)(DIMUSE_BASE_FEEDSIZE * ((float)_internalSampleRate / DIMUSE_BASE_SAMPLERATE));
+
+	if (_lowLatencyMode) {
+		_internalFeedSize *= 2;
+	}
+
+	_curMixerMusicVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType);
+	_curMixerSpeechVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType);
+	_curMixerSFXVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType);
+	_currentSpeechVolume = 0;
+	_currentSpeechFrequency = 0;
+	_currentSpeechPan = 0;
+
+	_waveOutXorTrigger = 0;
+	_waveOutWriteIndex = 0;
+	_waveOutDisableWrite = 0;
+	_waveOutPreferredFeedSize = 0;
+
+	_dispatchFadeSize = 0;
+
+	_stopSequenceFlag = 0;
+	_scriptInitializedFlag = 0;
+	_callbackInterruptFlag = 0;
+	_spooledMusicEnabled = true;
+
+	_isEngineDisabled = false;
+	_checkForUnderrun = false;
+	_underrunCooldown = 0;
+
+	_emptyMarker[0] = '\0';
+	_internalMixer = new IMuseDigiInternalMixer(mixer, _internalSampleRate, _lowLatencyMode);
+	_groupsHandler = new IMuseDigiGroupsHandler(this, mutex);
+	_fadesHandler = new IMuseDigiFadesHandler(this, mutex);
+	_triggersHandler = new IMuseDigiTriggersHandler(this, mutex);
+	_filesHandler = new IMuseDigiFilesHandler(this);
+
+	diMUSEInitialize();
+	diMUSEInitializeScript();
+	_filesHandler->allocSoundBuffer(DIMUSE_BUFFER_SPEECH, 176000, 44000, 88000);
+	_filesHandler->allocSoundBuffer(DIMUSE_BUFFER_MUSIC, 528000, 44000, 352000);
+
+	_filesHandler->allocSoundBuffer(DIMUSE_BUFFER_SFX, 198000, 0, 0);
+
+	if (_mixer->getOutputBufSize() != 0) {
+		// Let's find the optimal value for the maximum number of streams which can stay in the queue at once;
+		// (A number which is too low can lead to buffer underrun, while the higher the number is, the higher is the audio latency)
+		_maxQueuedStreams = (int)ceil((_mixer->getOutputBufSize() / _waveOutPreferredFeedSize) / ((float)_mixer->getOutputRate() / _internalSampleRate));
+
+		// This mixer's optimal output sample rate for this audio engine is one which is a multiple of 22050Hz;
+		// if we're dealing with one which is a multiple of 48000Hz, compensate the number of queued streams...
+		if (_mixer->getOutputRate() % _internalSampleRate) {
+			_maxQueuedStreams++;
+		}
+
+		// The lower optimal bound is always 4, except if we're operating in low latency mode
+		_maxQueuedStreams = MAX(_mixer->getOutputBufSize() <= 1024 ? 3 : 4, _maxQueuedStreams);
+	} else {
+		debug(5, "IMuseDigital::IMuseDigital(): WARNING: output audio buffer size not specified for this platform, defaulting _maxQueuedStreams to 4");
+		_maxQueuedStreams = 4;
+	}
+
+	// This value has been calculated in a way that is a good compromise
+	// between the absence of underruns and the lowest latency achievable.
+	// Of course this is never perfect, given the vast number of platforms
+	// we support, so the value might eventually be corrected by our custom
+	// adaptive buffer underrun correction routine.
+	_nominalBufferCount = _maxQueuedStreams;
+	_underrunCooldown = _maxQueuedStreams;
+
+	g_system->getTimerManager()->installTimerProc(timer_handler, 1000000 / _callbackFps, this, "IMuseDigital");
+}
+
+IMuseDigital::~IMuseDigital() {
+	g_system->getTimerManager()->removeTimerProc(timer_handler);
+	_filesHandler->deallocSoundBuffer(DIMUSE_BUFFER_SPEECH);
+	_filesHandler->deallocSoundBuffer(DIMUSE_BUFFER_MUSIC);
+	_filesHandler->deallocSoundBuffer(DIMUSE_BUFFER_SFX);
+	cmdsDeinit();
+	diMUSETerminate();
+	delete _internalMixer;
+	delete _groupsHandler;
+	delete _fadesHandler;
+	delete _triggersHandler;
+	delete _filesHandler;
+
+	// Deinit the Dispatch module
+	free(_dispatchBuffer);
+	_dispatchBuffer = nullptr;
+
+	// Deinit the WaveOut module
+	free(_waveOutOutputBuffer);
+	_waveOutOutputBuffer = nullptr;
+
+	free(_waveOutLowLatencyOutputBuffer);
+	_waveOutLowLatencyOutputBuffer = nullptr;
+}
+
+int IMuseDigital::roundRobinSetBufferCount() {
+	int minStreams = MAX<int>(_nominalBufferCount - 5, 1);
+	int maxStreams = _nominalBufferCount + 5;
+	_maxQueuedStreams++;
+
+	if (_maxQueuedStreams > maxStreams) {
+		_maxQueuedStreams = minStreams;
+	}
+
+	return _maxQueuedStreams;
+}
+
+void IMuseDigital::adaptBufferCount() {
+	_maxQueuedStreams++;
+	_nominalBufferCount = _maxQueuedStreams;
+}
+
+void IMuseDigital::stopSound(int sound) {
+	diMUSEStopSound(sound);
+}
+
+void IMuseDigital::stopAllSounds() {
+	diMUSEStopAllSounds();
+}
+
+int IMuseDigital::isSoundRunning(int soundId) {
+	return diMUSEGetParam(soundId, DIMUSE_P_SND_TRACK_NUM) > 0;
+}
+
+void IMuseDigital::callback() {
+	if (_cmdsPauseCount)
+		return;
+
+	if (!_callbackInterruptFlag) {
+		_callbackInterruptFlag = 1;
+		diMUSEHeartbeat();
+		_callbackInterruptFlag = 0;
+	}
+}
+
+void IMuseDigital::diMUSEHeartbeat() {
+	// This is what happens:
+	// - Usual audio stuff like fetching and playing sound (and everything
+	//   within waveOutCallback()) happens at a base 50Hz rate;
+	// - Triggers and fades handling happens at a (somewhat hacky) 60Hz rate;
+	// - Music gain reduction happens at a 10Hz rate.
+
+	int soundId, foundGroupId, musicTargetVolume, musicEffVol, musicVol, tempVol, tempEffVol, factor, step;
+
+	waveOutCallback();
+
+	// TODO
+	// if (!_vm->isUsingOriginalGUI()) {
+	// 	// Update volumes
+	//
+	// 	if (_curMixerMusicVolume != _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType)) {
+	// 		_curMixerMusicVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType);
+	// 		diMUSESetMusicGroupVol(CLIP(_mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType) / 2, 0, 127));
+	// 	}
+	//
+	// 	if (_curMixerSpeechVolume != _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType)) {
+	// 		_curMixerSpeechVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType);
+	// 		diMUSESetVoiceGroupVol(CLIP(_mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType) / 2, 0, 127));
+	// 	}
+	//
+	// 	if (_curMixerSFXVolume != _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType)) {
+	// 		_curMixerSFXVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType);
+	// 		diMUSESetSFXGroupVol(CLIP(_mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType) / 2, 0, 127));
+	// 	}
+	// }
+
+	// Handle fades and triggers
+
+	_cmdsRunning60HzCount += _usecPerInt;
+	while (_cmdsRunning60HzCount >= DIMUSE_TIMER_FADES_RATE_USEC) {
+		_cmdsRunning60HzCount -= DIMUSE_TIMER_FADES_RATE_USEC;
+		_fadesHandler->loop();
+		_triggersHandler->loop();
+	}
+
+	_cmdsRunning10HzCount += _usecPerInt;
+	if (_cmdsRunning10HzCount < DIMUSE_TIMER_GAIN_RED_RATE_USEC)
+		return;
+
+	do {
+		// SPEECH GAIN REDUCTION 10Hz
+		_cmdsRunning10HzCount -= DIMUSE_TIMER_GAIN_RED_RATE_USEC;
+		soundId = 0;
+		musicTargetVolume = _groupsHandler->setGroupVol(DIMUSE_GROUP_MUSIC, -1);
+		while (1) { // Check all tracks to see if there's a speech file playing
+			soundId = waveGetNextSound(soundId);
+			if (!soundId)
+				break;
+
+			foundGroupId = -1;
+			if (_filesHandler->getNextSound(soundId) == 2) {
+				foundGroupId = waveGetParam(soundId, DIMUSE_P_GROUP); // Check the groupId of this sound
+			}
+
+			if (foundGroupId == DIMUSE_GROUP_SPEECH) {
+				// Remember: when a speech file stops playing this block stops
+				// being executed, so musicTargetVolume returns back to its original value
+				factor = 80;
+				musicTargetVolume = (musicTargetVolume * factor) / 128;
+				break;
+			}
+		}
+
+		musicEffVol = _groupsHandler->setGroupVol(DIMUSE_GROUP_MUSICEFF, -1); // MUSIC EFFECTIVE VOLUME GROUP (used for gain reduction)
+		musicVol = _groupsHandler->setGroupVol(DIMUSE_GROUP_MUSIC, -1); // MUSIC VOLUME SUBGROUP (keeps track of original music volume)
+
+		if (musicEffVol < musicTargetVolume) { // If there is gain reduction already going on...
+			tempEffVol = musicEffVol + 3;
+			if (tempEffVol < musicTargetVolume) {
+				if (musicVol <= tempEffVol) {
+					musicVol = tempEffVol;
+				}
+			} else if (musicVol <= musicTargetVolume) { // Bring up the music volume immediately when speech stops playing
+				musicVol = musicTargetVolume;
+			}
+			_groupsHandler->setGroupVol(DIMUSE_GROUP_MUSICEFF, musicVol);
+		} else if (musicEffVol > musicTargetVolume) {
+			// Bring music volume down to target volume with a -18 step
+		    // if there's speech playing or else, just cap it to the target if it's out of range
+			step = 18;
+			tempVol = musicEffVol - step;
+			if (tempVol <= musicTargetVolume) {
+				if (musicVol >= musicTargetVolume) {
+					musicVol = musicTargetVolume;
+				}
+			} else {
+				if (musicVol >= tempVol) {
+					musicVol = tempVol;
+				}
+			}
+			_groupsHandler->setGroupVol(DIMUSE_GROUP_MUSICEFF, musicVol);
+		}
+
+	} while (_cmdsRunning10HzCount >= DIMUSE_TIMER_GAIN_RED_RATE_USEC);
+}
+
+void IMuseDigital::setPriority(int soundId, int priority) {
+	diMUSESetParam(soundId, DIMUSE_P_PRIORITY, priority);
+}
+
+void IMuseDigital::setVolume(int soundId, int volume) {
+	diMUSESetParam(soundId, DIMUSE_P_VOLUME, volume);
+	if (soundId == kTalkSoundID)
+		_currentSpeechVolume = volume;
+}
+
+void IMuseDigital::setPan(int soundId, int pan) {
+	diMUSESetParam(soundId, DIMUSE_P_PAN, pan);
+	if (soundId == kTalkSoundID)
+		_currentSpeechPan = pan;
+}
+
+void IMuseDigital::setFrequency(int soundId, int frequency) {
+	diMUSESetParam(soundId, DIMUSE_P_TRANSPOSE, frequency);
+	if (soundId == kTalkSoundID)
+		_currentSpeechFrequency = frequency;
+}
+
+int IMuseDigital::getCurSpeechVolume() const {
+	return _currentSpeechVolume;
+}
+
+int IMuseDigital::getCurSpeechPan() const {
+	return _currentSpeechPan;
+}
+
+int IMuseDigital::getCurSpeechFrequency() const {
+	return _currentSpeechFrequency;
+}
+
+void IMuseDigital::flushTracks() {
+	_filesHandler->flushSounds();
+}
+
+// This is used in order to avoid crash everything
+// if a compressed audio resource file is found
+void IMuseDigital::disableEngine() {
+	_isEngineDisabled = true;
+}
+
+bool IMuseDigital::isEngineDisabled() {
+	return _isEngineDisabled;
+}
+
+int32 IMuseDigital::getCurMusicPosInMs() {
+	int soundId, curSoundId;
+
+	curSoundId = 0;
+	soundId = 0;
+	while (1) {
+		curSoundId = diMUSEGetNextSound(curSoundId);
+		if (!curSoundId)
+			break;
+
+		if (diMUSEGetParam(curSoundId, DIMUSE_P_SND_HAS_STREAM) && diMUSEGetParam(curSoundId, DIMUSE_P_STREAM_BUFID) == DIMUSE_BUFFER_MUSIC) {
+			soundId = curSoundId;
+			return diMUSEGetParam(soundId, DIMUSE_P_SND_POS_IN_MS);
+		}
+	}
+
+	return diMUSEGetParam(soundId, DIMUSE_P_SND_POS_IN_MS);
+}
+
+int32 IMuseDigital::getCurVoiceLipSyncWidth() {
+	int32 width, height;
+	getSpeechLipSyncInfo(width, height);
+	return width;
+}
+
+int32 IMuseDigital::getCurVoiceLipSyncHeight() {
+	int32 width, height;
+	getSpeechLipSyncInfo(width, height);
+	return height;
+}
+
+int32 IMuseDigital::getCurMusicLipSyncWidth(int syncId) {
+	int32 width, height;
+	getMusicLipSyncInfo(syncId, width, height);
+	return width;
+}
+
+int32 IMuseDigital::getCurMusicLipSyncHeight(int syncId) {
+	int32 width, height;
+	getMusicLipSyncInfo(syncId, width, height);
+	return height;
+}
+
+void IMuseDigital::getSpeechLipSyncInfo(int32 &width, int32 &height) {
+	int curSpeechPosInMs;
+
+	width = 0;
+	height = 0;
+
+	if (diMUSEGetParam(kTalkSoundID, DIMUSE_P_SND_TRACK_NUM) > 0) {
+		curSpeechPosInMs = diMUSEGetParam(kTalkSoundID, DIMUSE_P_SND_POS_IN_MS);
+		// TODO
+		// diMUSELipSync(kTalkSoundID, 0, _vm->VAR(_vm->VAR_SYNC) + curSpeechPosInMs + 50, width, height);
+	}
+}
+
+void IMuseDigital::getMusicLipSyncInfo(int syncId, int32 &width, int32 &height) {
+	int soundId;
+	int speechSoundId;
+	int curSpeechPosInMs;
+
+	soundId = 0;
+	speechSoundId = 0;
+	width = 0;
+	height = 0;
+	while (1) {
+		soundId = diMUSEGetNextSound(soundId);
+		if (!soundId)
+			break;
+		if (diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM)) {
+			if (diMUSEGetParam(soundId, DIMUSE_P_STREAM_BUFID) == DIMUSE_BUFFER_MUSIC) {
+				speechSoundId = soundId;
+				break;
+			}
+		}
+	}
+
+	if (speechSoundId) {
+		curSpeechPosInMs = diMUSEGetParam(speechSoundId, DIMUSE_P_SND_POS_IN_MS);
+		// TODO
+		// diMUSELipSync(speechSoundId, syncId, _vm->VAR(_vm->VAR_SYNC) + curSpeechPosInMs + 50, width, height);
+	}
+}
+
+int32 IMuseDigital::getSoundElapsedTimeInMs(int soundId) {
+	if (diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM)) {
+		return diMUSEGetParam(soundId, DIMUSE_P_SND_POS_IN_MS);
+	}
+	return 0;
+}
+
+void IMuseDigital::pause(bool p) {
+	if (p) {
+		debug(5, "IMuseDigital::pause(): pausing...");
+		diMUSEPause();
+	} else {
+		debug(5, "IMuseDigital::pause(): resuming...");
+		diMUSEResume();
+	}
+}
+
+void IMuseDigital::floodMusicBuffer() {
+	while (!isMusicStreamIdle()) {
+		diMUSEProcessStreams();
+	}
+}
+
+void IMuseDigital::fillStreamsWhileMusicCritical(int fillTimesAfter) {
+	while (isMusicCritical()) {
+		diMUSEProcessStreams();
+	}
+
+	for (int i = 0; i < fillTimesAfter; i++) {
+		diMUSEProcessStreams();
+	}
+}
+
+bool IMuseDigital::isMusicStreamIdle() {
+	int32 bufSize, criticalSize, freeSpace;
+	int paused;
+	IMuseDigiSndBuffer *bufInfo = _filesHandler->getBufInfo(DIMUSE_BUFFER_MUSIC);
+
+	if (!queryNextSoundFile(bufSize, criticalSize, freeSpace, paused))
+		return true;
+	return (paused > 0) || (bufSize - bufInfo->loadSize < freeSpace);
+}
+
+bool IMuseDigital::isMusicCritical() {
+	int32 bufSize, criticalSize, freeSpace;
+	int paused;
+
+	if (!queryNextSoundFile(bufSize, criticalSize, freeSpace, paused))
+		return false;
+	return (paused == 0) && freeSpace <= criticalSize;
+}
+
+bool IMuseDigital::queryNextSoundFile(int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
+	int soundId;
+	soundId = diMUSEGetNextSound(0);
+	while (soundId) {
+		if (diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM) &&
+			(diMUSEGetParam(soundId, DIMUSE_P_GROUP) == DIMUSE_GROUP_MUSIC || diMUSEGetParam(soundId, DIMUSE_P_GROUP) == DIMUSE_GROUP_MUSICEFF)) {
+			diMUSEQueryStream(soundId, bufSize, criticalSize, freeSpace, paused);
+			return true;
+		}
+		soundId = diMUSEGetNextSound(soundId);
+	}
+	return false;
+}
+
+int IMuseDigital::getSampleRate() {
+	return _internalSampleRate;
+}
+
+int IMuseDigital::getFeedSize() {
+	return _internalFeedSize;
+}
+
+int IMuseDigital::diMUSETerminate() {
+	if (_scriptInitializedFlag) {
+		diMUSEStopAllSounds();
+		_filesHandler->closeAllSounds();
+	}
+
+	return 0;
+}
+
+int IMuseDigital::diMUSEInitialize() {
+	return cmdsHandleCmd(DIMUSE_C_INIT);
+}
+
+int IMuseDigital::diMUSEPause() {
+	return cmdsHandleCmd(DIMUSE_C_PAUSE);
+}
+
+int IMuseDigital::diMUSEResume() {
+	return cmdsHandleCmd(DIMUSE_C_RESUME);
+}
+
+void IMuseDigital::diMUSESaveLoad(Common::Serializer &ser) {
+	cmdsSaveLoad(ser);
+}
+
+int IMuseDigital::diMUSESetGroupVol(int groupId, int volume) {
+	return cmdsHandleCmd(DIMUSE_C_SET_GRP_VOL, nullptr, groupId, volume);
+}
+
+int IMuseDigital::diMUSEStartSound(int soundId, int priority) {
+	return cmdsHandleCmd(DIMUSE_C_START_SND, nullptr, soundId, priority);
+}
+
+int IMuseDigital::diMUSEStopSound(int soundId) {
+	debug(5, "IMuseDigital::diMUSEStopSound(): %d", soundId);
+	return cmdsHandleCmd(DIMUSE_C_STOP_SND, nullptr, soundId);
+}
+
+int IMuseDigital::diMUSEStopAllSounds() {
+	debug(5, "IMuseDigital::diMUSEStopAllSounds()");
+	return cmdsHandleCmd(DIMUSE_C_STOP_ALL_SNDS);
+}
+
+int IMuseDigital::diMUSEGetNextSound(int soundId) {
+	return cmdsHandleCmd(DIMUSE_C_GET_NEXT_SND, nullptr, soundId);
+}
+
+int IMuseDigital::diMUSESetParam(int soundId, int paramId, int value) {
+	return cmdsHandleCmd(DIMUSE_C_SET_PARAM, nullptr, soundId, paramId, value);
+}
+
+int IMuseDigital::diMUSEGetParam(int soundId, int paramId) {
+	return cmdsHandleCmd(DIMUSE_C_GET_PARAM, nullptr, soundId, paramId);
+}
+
+int IMuseDigital::diMUSEFadeParam(int soundId, int opcode, int destValue, int fadeLength) {
+	return cmdsHandleCmd(DIMUSE_C_FADE_PARAM, nullptr, soundId, opcode, destValue, fadeLength);
+}
+
+int IMuseDigital::diMUSESetHook(int soundId, int hookId) {
+	return cmdsHandleCmd(DIMUSE_C_SET_HOOK, nullptr, soundId, hookId);
+}
+
+int IMuseDigital::diMUSESetTrigger(int soundId, int marker, int opcode, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
+	return cmdsHandleCmd(DIMUSE_C_SET_TRIGGER, nullptr, soundId, marker, opcode, d, e, f, g, h, i, j, k, l, m, n);
+}
+
+int IMuseDigital::diMUSEStartStream(int soundId, int priority, int bufferId) {
+	return cmdsHandleCmd(DIMUSE_C_START_STREAM, nullptr, soundId, priority, bufferId);
+}
+
+int IMuseDigital::diMUSESwitchStream(int oldSoundId, int newSoundId, int fadeDelay, int fadeSyncFlag2, int fadeSyncFlag1) {
+	return cmdsHandleCmd(DIMUSE_C_SWITCH_STREAM, nullptr, oldSoundId, newSoundId, fadeDelay, fadeSyncFlag2, fadeSyncFlag1);
+}
+
+int IMuseDigital::diMUSEProcessStreams() {
+	return cmdsHandleCmd(DIMUSE_C_PROCESS_STREAMS);
+}
+
+int IMuseDigital::diMUSEQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
+	return waveQueryStream(soundId, bufSize, criticalSize, freeSpace, paused);
+}
+
+int IMuseDigital::diMUSEFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused) {
+	return cmdsHandleCmd(DIMUSE_C_FEED_STREAM, srcBuf, soundId, -1, sizeToFeed, paused);
+}
+
+int IMuseDigital::diMUSELipSync(int soundId, int syncId, int msPos, int32 &width, int32 &height) {
+	return waveLipSync(soundId, syncId, msPos, width, height);
+}
+
+int IMuseDigital::diMUSEGetMusicGroupVol() {
+	// TODO
+	// if (_vm->isUsingOriginalGUI()) {
+	// 	return diMUSESetGroupVol(DIMUSE_GROUP_MUSIC, -1);
+	// }
+	//
+	// return _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType) / 2;
+	return diMUSESetGroupVol(DIMUSE_GROUP_MUSIC, -1);
+}
+
+int IMuseDigital::diMUSEGetSFXGroupVol() {
+	// TODO
+	// if (_vm->isUsingOriginalGUI()) {
+	// 	return diMUSESetGroupVol(DIMUSE_GROUP_SFX, -1);
+	// }
+	//
+	// return _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType) / 2;
+	return diMUSESetGroupVol(DIMUSE_GROUP_SFX, -1);
+}
+
+int IMuseDigital::diMUSEGetVoiceGroupVol() {
+	// TODO
+	// if (_vm->isUsingOriginalGUI()) {
+	// 	return diMUSESetGroupVol(DIMUSE_GROUP_SPEECH, -1);
+	// }
+	//
+	// return _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType) / 2;
+	return diMUSESetGroupVol(DIMUSE_GROUP_SPEECH, -1);
+}
+
+int IMuseDigital::diMUSESetMusicGroupVol(int volume) {
+	debug(5, "IMuseDigital::diMUSESetMusicGroupVol(): %d", volume);
+	return diMUSESetGroupVol(DIMUSE_GROUP_MUSIC, volume);
+}
+
+int IMuseDigital::diMUSESetSFXGroupVol(int volume) {
+	debug(5, "IMuseDigital::diMUSESetSFXGroupVol(): %d", volume);
+	return diMUSESetGroupVol(DIMUSE_GROUP_SFX, volume);
+}
+
+int IMuseDigital::diMUSESetVoiceGroupVol(int volume) {
+	debug(5, "IMuseDigital::diMUSESetVoiceGroupVol(): %d", volume);
+	return diMUSESetGroupVol(DIMUSE_GROUP_SPEECH, volume);
+}
+
+void IMuseDigital::diMUSEUpdateGroupVolumes() {
+	waveUpdateGroupVolumes();
+}
+
+int IMuseDigital::diMUSEInitializeScript() {
+	return scriptParse(DIMUSE_C_SCRIPT_INIT, -1, -1);
+}
+
+void IMuseDigital::diMUSERefreshScript() {
+	scriptParse(DIMUSE_C_SCRIPT_REFRESH, -1, -1);
+}
+
+int IMuseDigital::diMUSESetState(int soundId) {
+	return scriptParse(DIMUSE_C_SCRIPT_SET_STATE, soundId, -1);
+}
+
+int IMuseDigital::diMUSESetSequence(int soundId) {
+	return scriptParse(DIMUSE_C_SCRIPT_SET_SEQUENCE, soundId, -1);
+}
+
+int IMuseDigital::diMUSESetCuePoint(int cueId) {
+	return scriptParse(DIMUSE_C_SCRIPT_CUE_POINT, cueId, -1);
+}
+
+int IMuseDigital::diMUSESetAttribute(int attrIndex, int attrVal) {
+	return scriptParse(DIMUSE_C_SCRIPT_SET_ATTRIBUTE, attrIndex, attrVal);
+}
+
+void IMuseDigital::diMUSEEnableSpooledMusic() {
+	_spooledMusicEnabled = true;
+}
+
+void IMuseDigital::diMUSEDisableSpooledMusic() {
+	_spooledMusicEnabled = true;
+	diMUSESetState(0);
+	diMUSESetSequence(0);
+	_spooledMusicEnabled = false;
+}
+
+// Debugger utility functions
+
+// TODO
+#if 0
+void IMuseDigital::listStates() {
+	_vm->getDebugger()->debugPrintf("+---------------------------------+\n");
+	_vm->getDebugger()->debugPrintf("| stateId |         name          |\n");
+	_vm->getDebugger()->debugPrintf("+---------+-----------------------+\n");
+	if (_vm->_game.id == GID_CMI) {
+		if (_vm->_game.features & GF_DEMO) {
+			for (int i = 0; _comiDemoStateMusicTable[i].soundId != -1; i++) {
+				_vm->getDebugger()->debugPrintf("|  %4d   | %20s  |\n", _comiDemoStateMusicTable[i].soundId, _comiDemoStateMusicTable[i].name);
+			}
+		} else {
+			for (int i = 0; _comiStateMusicTable[i].soundId != -1; i++) {
+				_vm->getDebugger()->debugPrintf("|  %4d   | %20s  |\n", _comiStateMusicTable[i].soundId, _comiStateMusicTable[i].name);
+			}
+		}
+	} else if (_vm->_game.id == GID_DIG) {
+		for (int i = 0; _digStateMusicTable[i].soundId != -1; i++) {
+			_vm->getDebugger()->debugPrintf("|  %4d   | %20s  |\n", _digStateMusicTable[i].soundId, _digStateMusicTable[i].name);
+		}
+	} else if (_vm->_game.id == GID_FT) {
+		for (int i = 0; _ftStateMusicTable[i].name[0]; i++) {
+			_vm->getDebugger()->debugPrintf("|  %4d   | %21s |\n", i, _ftStateMusicTable[i].name);
+		}
+	}
+	_vm->getDebugger()->debugPrintf("+---------+-----------------------+\n\n");
+}
+
+void IMuseDigital::listSeqs() {
+	_vm->getDebugger()->debugPrintf("+--------------------------------+\n");
+	_vm->getDebugger()->debugPrintf("|  seqId  |         name         |\n");
+	_vm->getDebugger()->debugPrintf("+---------+----------------------+\n");
+	if (_vm->_game.id == GID_CMI) {
+		for (int i = 0; _comiSeqMusicTable[i].soundId != -1; i++) {
+			_vm->getDebugger()->debugPrintf("|  %4d   | %20s |\n", _comiSeqMusicTable[i].soundId, _comiSeqMusicTable[i].name);
+		}
+	} else if (_vm->_game.id == GID_DIG) {
+		for (int i = 0; _digSeqMusicTable[i].soundId != -1; i++) {
+			_vm->getDebugger()->debugPrintf("|  %4d   | %20s |\n", _digSeqMusicTable[i].soundId, _digSeqMusicTable[i].name);
+		}
+	} else if (_vm->_game.id == GID_FT) {
+		for (int i = 0; _ftSeqNames[i].name[0]; i++) {
+			_vm->getDebugger()->debugPrintf("|  %4d   | %20s |\n", i, _ftSeqNames[i].name);
+		}
+	}
+	_vm->getDebugger()->debugPrintf("+---------+----------------------+\n\n");
+}
+
+void IMuseDigital::listCues() {
+	int curId = -1;
+	if (_curMusicSeq) {
+		_vm->getDebugger()->debugPrintf("Available cues for current sequence:\n");
+		_vm->getDebugger()->debugPrintf("+---------------------------------------+\n");
+		_vm->getDebugger()->debugPrintf("|   cueName   | transitionType | volume |\n");
+		_vm->getDebugger()->debugPrintf("+-------------+----------------+--------+\n");
+		for (int i = 0; i < 4; i++) {
+			curId = ((_curMusicSeq - 1) * 4) + i;
+			_vm->getDebugger()->debugPrintf("|  %9s  |        %d       |  %3d   |\n",
+				_ftSeqMusicTable[curId].audioName, (int)_ftSeqMusicTable[curId].transitionType, (int)_ftSeqMusicTable[curId].volume);
+		}
+		_vm->getDebugger()->debugPrintf("+-------------+----------------+--------+\n\n");
+	} else {
+		_vm->getDebugger()->debugPrintf("Current sequence is NULL, no cues available.\n\n");
+	}
+}
+
+void IMuseDigital::listTracks() {
+	_vm->getDebugger()->debugPrintf("Virtual audio tracks currently playing:\n");
+	_vm->getDebugger()->debugPrintf("+-------------------------------------------------------------------------+\n");
+	_vm->getDebugger()->debugPrintf("| # | soundId | group | hasStream | vol/effVol/pan  | priority | jumpHook |\n");
+	_vm->getDebugger()->debugPrintf("+---+---------+-------+-----------+-----------------+----------+----------+\n");
+
+	for (int i = 0; i < _trackCount; i++) {
+		IMuseDigiTrack curTrack = _tracks[i];
+		if (curTrack.soundId != 0) {
+			_vm->getDebugger()->debugPrintf("| %1d |  %5d  |   %d   |     %d     |   %3d/%3d/%3d   |   %3d    |   %3d    |\n",
+				i, curTrack.soundId, curTrack.group, diMUSEGetParam(curTrack.soundId, DIMUSE_P_SND_HAS_STREAM),
+				curTrack.vol, curTrack.effVol, curTrack.pan, curTrack.priority, curTrack.jumpHook);
+		} else {
+			_vm->getDebugger()->debugPrintf("| %1d |   ---   |  ---  |    ---    |   ---/---/---   |   ---    |   ---    |\n", i);
+		}
+	}
+	_vm->getDebugger()->debugPrintf("+---+---------+-------+-----------+-----------------+----------+----------+\n\n");
+}
+
+void IMuseDigital::listGroups() {
+	_vm->getDebugger()->debugPrintf("Volume groups:\n");
+	_vm->getDebugger()->debugPrintf("\tSFX:      %3d\n", _groupsHandler->getGroupVol(DIMUSE_GROUP_SFX));
+	_vm->getDebugger()->debugPrintf("\tSPEECH:   %3d\n", _groupsHandler->getGroupVol(DIMUSE_GROUP_SPEECH));
+	_vm->getDebugger()->debugPrintf("\tMUSIC:    %3d\n", _groupsHandler->getGroupVol(DIMUSE_GROUP_MUSIC));
+	_vm->getDebugger()->debugPrintf("\tMUSICEFF: %3d\n\n", _groupsHandler->getGroupVol(DIMUSE_GROUP_MUSICEFF));
+}
+#endif
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/dimuse_engine.h
new file mode 100644
index 00000000000..ed51b6ba51d
--- /dev/null
+++ b/engines/grim/imuse/dimuse_engine.h
@@ -0,0 +1,393 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef GRIM_IMUSE_ENGINE_H
+#define GRIM_IMUSE_ENGINE_H
+
+#include "common/scummsys.h"
+#include "common/debug.h"
+#include "common/mutex.h"
+#include "common/serializer.h"
+#include "common/textconsole.h"
+#include "common/util.h"
+
+#include "engines/grim/imuse/dimuse_defs.h"
+#include "engines/grim/imuse/dimuse_internalmixer.h"
+#include "engines/grim/imuse/dimuse_groups.h"
+#include "engines/grim/imuse/dimuse_fades.h"
+#include "engines/grim/imuse/dimuse_files.h"
+#include "engines/grim/imuse/dimuse_triggers.h"
+#include "engines/grim/imuse/dimuse_bndmgr.h"
+#include "engines/grim/imuse/dimuse_sndmgr.h"
+#include "engines/grim/imuse/dimuse_tables.h"
+
+#include "audio/mixer.h"
+#include "audio/decoders/raw.h"
+
+namespace Audio {
+class AudioStream;
+class Mixer;
+class QueuingAudioStream;
+}
+
+namespace Grim {
+
+struct imuseComiTable;
+struct IMuseDigiDispatch;
+struct IMuseDigiTrack;
+struct IMuseDigiStreamZone;
+
+class IMuseDigital {
+private:
+	Common::Mutex *_mutex;
+	Audio::Mixer *_mixer;
+
+	IMuseDigiInternalMixer *_internalMixer;
+	IMuseDigiGroupsHandler *_groupsHandler;
+	IMuseDigiFadesHandler *_fadesHandler;
+	IMuseDigiTriggersHandler *_triggersHandler;
+	IMuseDigiFilesHandler *_filesHandler;
+
+	int _callbackFps;
+	static void timer_handler(void *refConf);
+	void callback();
+
+	bool _isEngineDisabled;
+	bool _checkForUnderrun;
+	int _underrunCooldown;
+	bool _lowLatencyMode;
+
+	int _internalFeedSize;
+	int _internalSampleRate;
+
+	// These three are manipulated in the waveOut functions
+	uint8 *_outputAudioBuffer;
+	int _outputFeedSize;
+	int _outputSampleRate;
+
+	// Used in low latency mode only
+	uint8 *_outputLowLatencyAudioBuffers[DIMUSE_MAX_TRACKS];
+
+	int _maxQueuedStreams; // maximum number of streams which can be queued before they are played
+	int _nominalBufferCount;
+
+	int _currentSpeechVolume, _currentSpeechFrequency, _currentSpeechPan;
+	int _curMixerMusicVolume, _curMixerSpeechVolume, _curMixerSFXVolume;
+
+	int32 _attributes[188];	// internal attributes for each music file to store and check later
+	int32 _nextSeqToPlay;
+	int32 _curMusicState;
+	int32 _curMusicSeq;
+
+	int _stopSequenceFlag;
+	int _scriptInitializedFlag;
+	char _emptyMarker[1];
+	bool _spooledMusicEnabled;
+
+	int _usecPerInt; // Microseconds between each callback (will be set to 50 Hz)
+	int _callbackInterruptFlag;
+	void diMUSEHeartbeat();
+
+	void setComiMusicState(int stateId);
+	void setComiMusicSequence(int seqId);
+	void playComiMusic(const char *songName, const imuseComiTable *table, int attribPos, bool sequence);
+	bool isMusicStreamIdle();
+	bool isMusicCritical();
+
+	// Script
+	int scriptParse(int cmd, int a, int b);
+	int scriptInit();
+	int scriptTerminate();
+	void scriptRefresh();
+	void scriptSetState(int soundId);
+	void scriptSetSequence(int soundId);
+	void scriptSetCuePoint(int cueId);
+	int scriptSetAttribute(int attrIndex, int attrVal);
+
+	// CMDs
+	int _cmdsPauseCount;
+	int _cmdsRunning60HzCount;
+	int _cmdsRunning10HzCount;
+
+	int cmdsInit();
+	int cmdsDeinit();
+	int cmdsTerminate();
+	int cmdsPause();
+	int cmdsResume();
+	void cmdsSaveLoad(Common::Serializer &ser);
+	int cmdsStartSound(int soundId, int priority);
+	int cmdsStopSound(int soundId);
+	int cmdsStopAllSounds();
+	int cmdsGetNextSound(int soundId);
+	int cmdsSetParam(int soundId, int opcode, int value);
+	int cmdsGetParam(int soundId, int opcode);
+	int cmdsSetHook(int soundId, int hookId);
+	int cmdsGetHook(int soundId);
+
+	// Streamer
+	IMuseDigiStream _streams[DIMUSE_MAX_STREAMS];
+	IMuseDigiStream *_lastStreamLoaded;
+	int _streamerBailFlag;
+
+	int streamerInit();
+	IMuseDigiStream *streamerAllocateSound(int soundId, int bufId, int32 maxRead);
+	int streamerClearSoundInStream(IMuseDigiStream *streamPtr);
+	int streamerProcessStreams();
+	uint8 *streamerGetStreamBuffer(IMuseDigiStream *streamPtr, int size);
+	uint8 *streamerGetStreamBufferAtOffset(IMuseDigiStream *streamPtr, int32 offset, int size);
+	int streamerSetReadIndex(IMuseDigiStream *streamPtr, int offset);
+	int streamerSetLoadIndex(IMuseDigiStream *streamPtr, int offset);
+	int streamerGetFreeBufferAmount(IMuseDigiStream *streamPtr);
+	int streamerSetSoundToStreamFromOffset(IMuseDigiStream *streamPtr, int soundId, int32 offset);
+	void streamerQueryStream(IMuseDigiStream *streamPtr, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
+	int streamerFeedStream(IMuseDigiStream *streamPtr, uint8 *srcBuf, int32 sizeToFeed, int paused);
+	int streamerFetchData(IMuseDigiStream *streamPtr);
+
+	// Tracks
+	IMuseDigiTrack _tracks[DIMUSE_MAX_TRACKS];
+	IMuseDigiTrack *_trackList;
+
+	int _trackCount;
+	int _tracksPauseTimer;
+	int _tracksMicroSecsToFeed;
+
+	int tracksInit();
+	void tracksPause();
+	void tracksResume();
+	void tracksSaveLoad(Common::Serializer &ser);
+	void tracksSetGroupVol();
+	void tracksCallback();
+	void tracksLowLatencyCallback();
+	int tracksStartSound(int soundId, int tryPriority, int group);
+	int tracksStopSound(int soundId);
+	int tracksStopAllSounds();
+	int tracksGetNextSound(int soundId);
+	int tracksQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
+	int tracksFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused);
+	void tracksClear(IMuseDigiTrack *trackPtr);
+	int tracksSetParam(int soundId, int opcode, int value);
+	int tracksGetParam(int soundId, int opcode);
+	int tracksLipSync(int soundId, int syncId, int msPos, int32 &width, int32 &height);
+	int tracksSetHook(int soundId, int hookId);
+	int tracksGetHook(int soundId);
+	IMuseDigiTrack *tracksReserveTrack(int priority);
+	void tracksDeinit();
+
+	// Dispatch
+	IMuseDigiDispatch _dispatches[DIMUSE_MAX_DISPATCHES];
+	IMuseDigiStreamZone _streamZones[DIMUSE_MAX_STREAMZONES];
+	uint8 *_dispatchBuffer;
+	int32 _dispatchSize;
+	uint8 *_dispatchSmallFadeBufs;
+	uint8 *_dispatchLargeFadeBufs;
+	int32 _dispatchFadeSize;
+	int _dispatchLargeFadeFlags[DIMUSE_LARGE_FADES];
+	int _dispatchSmallFadeFlags[DIMUSE_SMALL_FADES];
+	int _dispatchFadeStartedFlag;
+	int _dispatchBufferedHookId;
+	int32 _dispatchJumpFadeSize;
+	int32 _dispatchCurStreamBufSize;
+	int32 _dispatchCurStreamCriticalSize;
+	int32 _dispatchCurStreamFreeSpace;
+	int _dispatchCurStreamPaused;
+
+	int dispatchInit();
+	IMuseDigiDispatch *dispatchGetDispatchByTrackId(int trackId);
+	void dispatchSaveLoad(Common::Serializer &ser);
+	int dispatchRestoreStreamZones();
+	int dispatchAllocateSound(IMuseDigiTrack *trackPtr, int groupId);
+	int dispatchRelease(IMuseDigiTrack *trackPtr);
+	int dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeLength, int exitTriggerSyncFlag, int offsetFadeSyncFlag);
+	void dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedSize, int sampleRate);
+	void dispatchPredictFirstStream();
+	int dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr);
+	int dispatchGetMap(IMuseDigiDispatch *dispatchPtr);
+	int dispatchConvertMap(uint8 *rawMap, int32 *destMap);
+	uint8 *dispatchGetNextMapEvent(int32 *mapPtr, int32 soundOffset, uint8 *mapEvent);
+	void dispatchPredictStream(IMuseDigiDispatch *dispatchPtr);
+	uint8 *dispatchCheckForJump(int32 *mapPtr, IMuseDigiStreamZone *strZnPtr, int &candidateHookId);
+	void dispatchPrepareToJump(IMuseDigiDispatch *dispatchPtr, IMuseDigiStreamZone *strZnPtr, uint8 *jumpParamsFromMap, int calledFromGetNextMapEvent);
+	void dispatchStreamNextZone(IMuseDigiDispatch *dispatchPtr, IMuseDigiStreamZone *strZnPtr);
+	IMuseDigiStreamZone *dispatchAllocateStreamZone();
+	uint8 *dispatchAllocateFade(int32 &fadeSize, const char *functionName);
+	void dispatchDeallocateFade(IMuseDigiDispatch *dispatchPtr, const char *functionName);
+	int dispatchGetFadeSize(IMuseDigiDispatch *dispatchPtr, int fadeLength);
+	void dispatchValidateFadeSize(IMuseDigiDispatch *dispatchPtr, int32 &dispatchSize, const char *functionName);
+	int dispatchUpdateFadeMixVolume(IMuseDigiDispatch *dispatchPtr, int32 remainingFade);
+	int dispatchUpdateFadeSlope(IMuseDigiDispatch *dispatchPtr);
+
+	// Wave (mainly a wrapper for Tracks functions)
+	int waveInit();
+	int waveTerminate();
+	int wavePause();
+	int waveResume();
+	void waveSaveLoad(Common::Serializer &ser);
+	void waveUpdateGroupVolumes();
+	int waveStartSound(int soundId, int priority);
+	int waveStopSound(int soundId);
+	int waveStopAllSounds();
+	int waveGetNextSound(int soundId);
+	int waveSetParam(int soundId, int opcode, int value);
+	int waveGetParam(int soundId, int opcode);
+	int waveSetHook(int soundId, int hookId);
+	int waveGetHook(int soundId);
+	int waveStartStream(int soundId, int priority, int groupId);
+	int waveSwitchStream(int oldSoundId, int newSoundId, int fadeLengthMs, int fadeSyncFlag2, int fadeSyncFlag1);
+	int waveProcessStreams();
+	int waveQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
+	int waveFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused);
+	int waveLipSync(int soundId, int syncId, int msPos, int32 &width, int32 &height);
+
+	// Waveapi
+	waveOutParamsStruct waveOutSettings;
+
+	int _waveOutSampleRate;
+	int _waveOutBytesPerSample;
+	int _waveOutNumChannels;
+	int _waveOutZeroLevel;
+	int _waveOutPreferredFeedSize;
+	uint8 *_waveOutMixBuffer;
+	uint8 *_waveOutOutputBuffer;
+
+	int _waveOutXorTrigger;
+	int _waveOutWriteIndex;
+	int _waveOutDisableWrite;
+
+	int waveOutInit(waveOutParamsStruct *waveOutSettings);
+	void waveOutWrite(uint8 **audioBuffer, int &feedSize, int &sampleRate);
+	int waveOutDeinit();
+	void waveOutCallback();
+	byte waveOutGetStreamFlags();
+
+	// Low latency mode
+	void waveOutLowLatencyWrite(uint8 **audioBuffer, int &feedSize, int &sampleRate, int idx);
+	void waveOutEmptyBuffer(int idx);
+
+	uint8 *_waveOutLowLatencyOutputBuffer;
+
+public:
+	IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode = false);
+	~IMuseDigital();
+
+	// Wrapper functions used by the main engine
+
+	void stopSound(int sound);
+	void stopAllSounds();
+	int isSoundRunning(int soundId);
+	void setPriority(int soundId, int priority);
+	void setVolume(int soundId, int volume);
+	void setPan(int soundId, int pan);
+	void setFrequency(int soundId, int frequency);
+	int  getCurSpeechVolume() const;
+	int  getCurSpeechPan() const;
+	int  getCurSpeechFrequency() const;
+	void pause(bool pause);
+	void flushTracks();
+	void disableEngine();
+	bool isEngineDisabled();
+	void floodMusicBuffer();
+	void fillStreamsWhileMusicCritical(int fillTimesAfter);
+	bool queryNextSoundFile(int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
+	int getSampleRate();
+	int getFeedSize();
+
+	int32 getCurMusicPosInMs();
+	int32 getCurVoiceLipSyncWidth();
+	int32 getCurVoiceLipSyncHeight();
+	int32 getCurMusicLipSyncWidth(int syncId);
+	int32 getCurMusicLipSyncHeight(int syncId);
+	void getSpeechLipSyncInfo(int32 &width, int32 &height);
+	void getMusicLipSyncInfo(int syncId, int32 &width, int32 &height);
+	int32 getSoundElapsedTimeInMs(int soundId);
+
+	// General engine functions
+	int diMUSETerminate();
+	int diMUSEInitialize();
+	int diMUSEPause();
+	int diMUSEResume();
+	void diMUSESaveLoad(Common::Serializer &ser);
+	int diMUSESetGroupVol(int groupId, int volume);
+	int diMUSEStartSound(int soundId, int priority);
+	int diMUSEStopSound(int soundId);
+	int diMUSEStopAllSounds();
+	int diMUSEGetNextSound(int soundId);
+	int diMUSESetParam(int soundId, int paramId, int value);
+	int diMUSEGetParam(int soundId, int paramId);
+	int diMUSEFadeParam(int soundId, int opcode, int destValue, int fadeLength);
+	int diMUSESetHook(int soundId, int hookId);
+
+	int diMUSESetTrigger(int soundId, int marker, int opcode,
+		int d = -1, int e = -1, int f = -1, int g = -1,
+		int h = -1, int i = -1, int j = -1, int k = -1,
+		int l = -1, int m = -1, int n = -1);
+
+	int diMUSEStartStream(int soundId, int priority, int groupId);
+	int diMUSESwitchStream(int oldSoundId, int newSoundId, int fadeDelay, int fadeSyncFlag2, int fadeSyncFlag1);
+	int diMUSEProcessStreams();
+	int diMUSEQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
+	int diMUSEFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused);
+	int diMUSELipSync(int soundId, int syncId, int msPos, int32 &width, int32 &height);
+	int diMUSEGetMusicGroupVol();
+	int diMUSEGetSFXGroupVol();
+	int diMUSEGetVoiceGroupVol();
+	int diMUSESetMusicGroupVol(int volume);
+	int diMUSESetSFXGroupVol(int volume);
+	int diMUSESetVoiceGroupVol(int volume);
+	void diMUSEUpdateGroupVolumes();
+	int diMUSEInitializeScript();
+	void diMUSERefreshScript();
+	int diMUSESetState(int soundId);
+	int diMUSESetSequence(int soundId);
+	int diMUSESetCuePoint(int cueId);
+	int diMUSESetAttribute(int attrIndex, int attrVal);
+	void diMUSEEnableSpooledMusic();
+	void diMUSEDisableSpooledMusic();
+
+	// Utils
+	int addTrackToList(IMuseDigiTrack **listPtr, IMuseDigiTrack *listPtr_Item);
+	int removeTrackFromList(IMuseDigiTrack **listPtr, IMuseDigiTrack *itemPtr);
+	int addStreamZoneToList(IMuseDigiStreamZone **listPtr, IMuseDigiStreamZone *listPtr_Item);
+	int removeStreamZoneFromList(IMuseDigiStreamZone **listPtr, IMuseDigiStreamZone *itemPtr);
+	int clampNumber(int value, int minValue, int maxValue);
+	int checkHookId(int &trackHookId, int sampleHookId);
+	int roundRobinSetBufferCount();
+	void adaptBufferCount();
+
+	// CMDs
+	int cmdsHandleCmd(int cmd, uint8 *ptr = nullptr,
+		int a = -1, int b = -1, int c = -1, int d = -1, int e = -1,
+		int f = -1, int g = -1, int h = -1, int i = -1, int j = -1,
+		int k = -1, int l = -1, int m = -1, int n = -1);
+
+	// Script
+	int scriptTriggerCallback(char *marker);
+
+	// Debugger utility functions
+	void listStates();
+	void listSeqs();
+	void listCues();
+	void listTracks();
+	void listGroups();
+};
+
+} // End of namespace Grim
+
+#endif
diff --git a/engines/grim/imuse/dimuse_fades.cpp b/engines/grim/imuse/dimuse_fades.cpp
new file mode 100644
index 00000000000..0c4aeb473f5
--- /dev/null
+++ b/engines/grim/imuse/dimuse_fades.cpp
@@ -0,0 +1,178 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/dimuse_fades.h"
+
+namespace Grim {
+
+IMuseDigiFadesHandler::IMuseDigiFadesHandler(IMuseDigital *engine, Common::Mutex *mutex) {
+	_engine = engine;
+	_mutex = mutex;
+}
+
+IMuseDigiFadesHandler::~IMuseDigiFadesHandler() {}
+
+int IMuseDigiFadesHandler::init() {
+	clearAllFades();
+	return 0;
+}
+
+int IMuseDigiFadesHandler::fadeParam(int soundId, int opcode, int destinationValue, int fadeLength) {
+	Common::StackLock lock(*_mutex);
+
+	if (!soundId || fadeLength < 0)
+		return -5;
+
+	if (opcode != DIMUSE_P_PRIORITY && opcode != DIMUSE_P_VOLUME && opcode != DIMUSE_P_PAN && opcode != DIMUSE_P_DETUNE && opcode != DIMUSE_P_UNKNOWN && opcode != 17)
+		return -5;
+
+	clearFadeStatus(soundId, opcode);
+
+	if (!fadeLength) {
+		debug(5, "IMuseDigiFadesHandler::fadeParam(): WARNING: allocated fade with zero length for sound %d", soundId);
+		if (opcode != DIMUSE_P_VOLUME || destinationValue) {
+			_engine->diMUSESetParam(soundId, opcode, destinationValue);
+		} else {
+			_engine->diMUSEStopSound(soundId);
+		}
+
+		return 0;
+	}
+
+	for (int l = 0; l < DIMUSE_MAX_FADES; l++) {
+		if (!_fades[l].status) {
+			_fades[l].sound = soundId;
+			_fades[l].param = opcode;
+			_fades[l].currentVal = _engine->diMUSEGetParam(soundId, opcode);
+			_fades[l].length = fadeLength;
+			_fades[l].counter = fadeLength;
+			_fades[l].slope = (destinationValue - _fades[l].currentVal) / fadeLength;
+			_fades[l].modOvfloCounter = 0;
+			_fades[l].status = 1;
+			_fadesOn = 1;
+
+			if ((destinationValue - _fades[l].currentVal) < 0) {
+				_fades[l].nudge = -1;
+				_fades[l].slopeMod = (-(destinationValue - _fades[l].currentVal) % fadeLength);
+			} else {
+				_fades[l].nudge = 1;
+				_fades[l].slopeMod = (destinationValue - _fades[l].currentVal) % fadeLength;
+			}
+
+			return 0;
+		}
+	}
+
+	debug(5, "IMuseDigiFadesHandler::fadeParam(): unable to allocate fade for sound %d", soundId);
+	return -6;
+}
+
+void IMuseDigiFadesHandler::clearFadeStatus(int soundId, int opcode) {
+	for (int l = 0; l < DIMUSE_MAX_FADES; l++) {
+		if (_fades[l].status
+			&& _fades[l].sound == soundId
+			&& (_fades[l].param == opcode || opcode == -1)) {
+			_fades[l].status = 0;
+		}
+	}
+}
+
+void IMuseDigiFadesHandler::loop() {
+	if (!_fadesOn)
+		return;
+
+	_fadesOn = 0;
+
+	for (int l = 0; l < DIMUSE_MAX_FADES; l++) {
+		if (_fades[l].status) {
+			_fadesOn = 1;
+			if (--_fades[l].counter == 0) {
+				_fades[l].status = 0;
+			}
+
+			int currentVolume = _fades[l].currentVal + _fades[l].slope;
+			int currentSlopeMod = _fades[l].modOvfloCounter + _fades[l].slopeMod;
+			_fades[l].modOvfloCounter += _fades[l].slopeMod;
+
+			if (_fades[l].length <= currentSlopeMod) {
+				_fades[l].modOvfloCounter = currentSlopeMod - _fades[l].length;
+				currentVolume += _fades[l].nudge;
+			}
+
+			if (_fades[l].currentVal != currentVolume) {
+				_fades[l].currentVal = currentVolume;
+
+				if (!(_fades[l].counter % 6)) {
+					debug(5, "IMuseDigiFadesHandler::loop(): running fade for sound %d with id %d, currently at volume %d", _fades[l].sound, l, currentVolume);
+					if ((_fades[l].param != DIMUSE_P_VOLUME) || currentVolume) {
+						_engine->diMUSESetParam(_fades[l].sound, _fades[l].param, currentVolume);
+					} else {
+						_engine->diMUSEStopSound(_fades[l].sound);
+					}
+				}
+			}
+		}
+	}
+}
+
+void IMuseDigiFadesHandler::deinit() {
+	clearAllFades();
+}
+
+void IMuseDigiFadesHandler::saveLoad(Common::Serializer &ser) {
+	for (int l = 0; l < DIMUSE_MAX_FADES; l++) {
+		ser.syncAsSint32LE(_fades[l].status, VER(103));
+		ser.syncAsSint32LE(_fades[l].sound, VER(103));
+		ser.syncAsSint32LE(_fades[l].param, VER(103));
+		ser.syncAsSint32LE(_fades[l].currentVal, VER(103));
+		ser.syncAsSint32LE(_fades[l].counter, VER(103));
+		ser.syncAsSint32LE(_fades[l].length, VER(103));
+		ser.syncAsSint32LE(_fades[l].slope, VER(103));
+		ser.syncAsSint32LE(_fades[l].slopeMod, VER(103));
+		ser.syncAsSint32LE(_fades[l].modOvfloCounter, VER(103));
+		ser.syncAsSint32LE(_fades[l].nudge, VER(103));
+	}
+
+	if (ser.isLoading())
+		_fadesOn = 1;
+}
+
+void IMuseDigiFadesHandler::clearAllFades() {
+	Common::StackLock lock(*_mutex);
+
+	for (int l = 0; l < DIMUSE_MAX_FADES; l++) {
+		_fades[l].status = 0;
+		_fades[l].sound = 0;
+		_fades[l].param = 0;
+		_fades[l].currentVal = 0;
+		_fades[l].counter = 0;
+		_fades[l].length = 0;
+		_fades[l].slope = 0;
+		_fades[l].slopeMod = 0;
+		_fades[l].modOvfloCounter = 0;
+		_fades[l].nudge = 0;
+	}
+
+	_fadesOn = 0;
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_fades.h b/engines/grim/imuse/dimuse_fades.h
new file mode 100644
index 00000000000..15458b3a5e9
--- /dev/null
+++ b/engines/grim/imuse/dimuse_fades.h
@@ -0,0 +1,54 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef GRIM_IMUSE_FADES_H
+#define GRIM_IMUSE_FADES_H
+
+#include "common/scummsys.h"
+#include "common/textconsole.h"
+#include "common/util.h"
+
+namespace Grim {
+
+class IMuseDigiFadesHandler {
+
+private:
+	IMuseDigital *_engine;
+	Common::Mutex *_mutex;
+	IMuseDigiFade _fades[DIMUSE_MAX_FADES] = {};
+	int _fadesOn = 0;
+
+	void clearAllFades();
+public:
+	IMuseDigiFadesHandler(IMuseDigital *engine, Common::Mutex *mutex);
+	~IMuseDigiFadesHandler();
+
+	int init();
+	void deinit();
+	void saveLoad(Common::Serializer &ser);
+	int fadeParam(int soundId, int opcode, int destinationValue, int fadeLength);
+	void clearFadeStatus(int soundId, int opcode);
+	void loop();
+
+};
+
+} // End of namespace Grim
+#endif
diff --git a/engines/grim/imuse/dimuse_files.cpp b/engines/grim/imuse/dimuse_files.cpp
new file mode 100644
index 00000000000..60db6b6f840
--- /dev/null
+++ b/engines/grim/imuse/dimuse_files.cpp
@@ -0,0 +1,314 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/dimuse_files.h"
+
+namespace Grim {
+
+IMuseDigiFilesHandler::IMuseDigiFilesHandler(IMuseDigital *engine) {
+	_engine = engine;
+	_sound = new ImuseDigiSndMgr();
+	assert(_sound);
+
+	for (int i = 0; i < 4; i++) {
+		IMuseDigiSndBuffer *selectedSoundBuf = &_soundBuffers[i];
+		selectedSoundBuf->buffer = nullptr;
+		selectedSoundBuf->bufSize = 0;
+		selectedSoundBuf->loadSize = 0;
+		selectedSoundBuf->criticalSize = 0;
+	}
+}
+
+IMuseDigiFilesHandler::~IMuseDigiFilesHandler() {
+	delete _sound;
+}
+
+void IMuseDigiFilesHandler::saveLoad(Common::Serializer &ser) {
+	int curSound = 0;
+	ImuseDigiSndMgr::SoundDesc *sounds = _sound->getSounds();
+
+	ser.syncArray(_currentSpeechFilename, 60, Common::Serializer::SByte, VER(103));
+	if (ser.isSaving()) {
+		for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
+			ser.syncAsSint32LE(sounds[l].soundId, VER(103));
+		}
+	}
+
+	if (ser.isLoading()) {
+		// Close prior sounds if we're reloading (needed for edge cases like the recipe book in COMI)
+		for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
+			_sound->closeSound(&sounds[l]);
+		}
+
+		for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
+			ser.syncAsSint32LE(curSound, VER(103));
+			if (curSound) {
+				openSound(curSound);
+				if (curSound != kTalkSoundID)
+					closeSound(curSound);
+			}
+		}
+	}
+}
+
+uint8 *IMuseDigiFilesHandler::getSoundAddrData(int soundId) {
+	if (_engine->isEngineDisabled())
+		return nullptr;
+
+	// This function is always used for SFX (tracks which do not
+	// have a stream pointer), hence the use of the resource address
+	if (soundId != 0) {
+		// TODO
+		// _vm->_res->lock(rtSound, soundId);
+		// byte *ptr = _vm->getResourceAddress(rtSound, soundId);
+		// if (!ptr) {
+		// 	_vm->_res->unlock(rtSound, soundId);
+		// 	return nullptr;
+		// }
+		// return ptr;
+	}
+	debug(5, "IMuseDigiFilesHandler::getSoundAddrData(): soundId is 0 or out of range");
+	return nullptr;
+}
+
+int IMuseDigiFilesHandler::getSoundAddrDataSize(int soundId, bool hasStream) {
+	if (_engine->isEngineDisabled())
+		return 0;
+
+	if (hasStream) {
+		ImuseDigiSndMgr::SoundDesc *s = _sound->findSoundById(soundId);
+		if (s) {
+			if (soundId != kTalkSoundID) {
+				return s->resSize;
+			}
+		}
+	} else {
+		// TODO
+		// return _vm->getResourceSize(rtSound, soundId);
+	}
+
+	return 0;
+}
+
+int IMuseDigiFilesHandler::getNextSound(int soundId) {
+	int foundSoundId = 0;
+	do {
+		foundSoundId = _engine->diMUSEGetNextSound(foundSoundId);
+		if (!foundSoundId)
+			return -1;
+	} while (foundSoundId != soundId);
+	return 2;
+}
+
+int IMuseDigiFilesHandler::seek(int soundId, int32 offset, int mode, int bufId) {
+	// This function and files_read() are used for sounds for which a stream is needed (speech
+	// and music), therefore they will always refer to sounds in a bundle file for DIG and COMI
+	// The seek'd position is in reference to the decompressed sound
+
+	if (_engine->isEngineDisabled())
+		return 0;
+
+	char fileName[60] = "";
+	getFilenameFromSoundId(soundId, fileName, sizeof(fileName));
+
+	ImuseDigiSndMgr::SoundDesc *s = _sound->findSoundById(soundId);
+	if (s) {
+		if (soundId != 0) {
+			return s->bundle->seekFile(offset, mode);
+		} else {
+			debug(5, "IMuseDigiFilesHandler::seek(): soundId is 0 or out of range");
+		}
+	} else {
+		debug(5, "IMuseDigiFilesHandler::seek(): can't find sound %d (%s); did you forget to open it?", soundId, fileName);
+	}
+
+	return 0;
+}
+
+int IMuseDigiFilesHandler::read(int soundId, uint8 *buf, int32 size, int bufId) {
+	// This function and files_seek() are used for sounds for which a stream is needed (speech
+	// and music), therefore they will always refer to sounds in a bundle file for DIG and COMI
+
+	if (_engine->isEngineDisabled())
+		return 0;
+
+	if (soundId != 0) {
+		uint8 *tmpBuf = nullptr;
+		int32 resultingSize;
+
+		char fileName[60] = "";
+		getFilenameFromSoundId(soundId, fileName, sizeof(fileName));
+
+		ImuseDigiSndMgr::SoundDesc *s = _sound->getSounds();
+		ImuseDigiSndMgr::SoundDesc *curSnd = nullptr;
+		for (int i = 0; i < MAX_IMUSE_SOUNDS; i++) {
+			curSnd = &s[i];
+			if (curSnd->inUse) {
+				if (curSnd->soundId == soundId) {
+					resultingSize = curSnd->bundle->readFile(fileName, size, &tmpBuf, true);
+
+					if (resultingSize != size)
+						debug(5, "IMuseDigiFilesHandler::read(): WARNING: tried to read %d bytes, got %d instead (soundId %d (%s))", size, resultingSize, soundId, fileName);
+
+					memcpy(buf, tmpBuf, resultingSize);
+					free(tmpBuf);
+					return resultingSize;
+				}
+			}
+		}
+
+		debug(5, "IMuseDigiFilesHandler::read(): can't find sound %d (%s); did you forget to open it?", soundId, fileName);
+
+	} else {
+		debug(5, "IMuseDigiFilesHandler::read(): soundId is 0 or out of range");
+	}
+
+	return 0;
+}
+
+IMuseDigiSndBuffer *IMuseDigiFilesHandler::getBufInfo(int bufId) {
+	if (bufId > 0 && bufId <= 4) {
+		return &_soundBuffers[bufId];
+	}
+
+	debug(5, "IMuseDigiFilesHandler::getBufInfo(): ERROR: invalid buffer id");
+	return nullptr;
+}
+
+int IMuseDigiFilesHandler::openSound(int soundId) {
+	if (_engine->isEngineDisabled())
+		return 1;
+
+	ImuseDigiSndMgr::SoundDesc *s = nullptr;
+	char fileName[60] = "";
+	getFilenameFromSoundId(soundId, fileName, sizeof(fileName));
+
+	int groupId = soundId == kTalkSoundID ? IMUSE_VOLGRP_VOICE : IMUSE_VOLGRP_MUSIC;
+	s = _sound->findSoundById(soundId);
+	if (!s)
+		s = _sound->openSound(soundId, fileName, IMUSE_BUNDLE, groupId, -1);
+	if (!s)
+		s = _sound->openSound(soundId, fileName, IMUSE_BUNDLE, groupId, 1);
+	if (!s)
+		s = _sound->openSound(soundId, fileName, IMUSE_BUNDLE, groupId, 2);
+	if (!s) {
+		debug(5, "IMuseDigiFilesHandler::openSound(): can't open sound %d (%s)", soundId, fileName);
+		return 1;
+	}
+
+	return 0;
+}
+
+void IMuseDigiFilesHandler::closeSound(int soundId) {
+	if (_engine->isEngineDisabled())
+		return;
+
+	_sound->scheduleSoundForDeallocation(soundId);
+}
+
+void IMuseDigiFilesHandler::closeAllSounds() {
+	ImuseDigiSndMgr::SoundDesc *s = _sound->getSounds();
+	for (int i = 0; i < MAX_IMUSE_SOUNDS; i++) {
+		if (s[i].inUse) {
+			closeSound(s[i].soundId);
+		}
+	}
+
+	_engine->flushTracks();
+}
+
+void IMuseDigiFilesHandler::getFilenameFromSoundId(int soundId, char *fileName, size_t size) {
+	int i = 0;
+
+	if (soundId == kTalkSoundID) {
+		Common::strlcpy(fileName, _currentSpeechFilename, size);
+		return;
+	}
+
+	if (soundId < 2000) {
+		while (_comiStateMusicTable[i].soundId != -1) {
+			if (_comiStateMusicTable[i].soundId == soundId) {
+				Common::strlcpy(fileName, _comiStateMusicTable[i].filename, size);
+				return;
+			}
+			i++;
+		}
+	} else {
+		while (_comiSeqMusicTable[i].soundId != -1) {
+			if (_comiSeqMusicTable[i].soundId == soundId) {
+				Common::strlcpy(fileName, _comiSeqMusicTable[i].filename, size);
+				return;
+			}
+			i++;
+		}
+	}
+}
+
+void IMuseDigiFilesHandler::allocSoundBuffer(int bufId, int32 size, int32 loadSize, int32 criticalSize) {
+	IMuseDigiSndBuffer *selectedSoundBuf;
+
+	selectedSoundBuf = &_soundBuffers[bufId];
+	selectedSoundBuf->buffer = (uint8 *)malloc(size);
+	selectedSoundBuf->bufSize = size;
+	selectedSoundBuf->loadSize = loadSize;
+	selectedSoundBuf->criticalSize = criticalSize;
+}
+
+void IMuseDigiFilesHandler::deallocSoundBuffer(int bufId) {
+	IMuseDigiSndBuffer *selectedSoundBuf;
+
+	selectedSoundBuf = &_soundBuffers[bufId];
+	free(selectedSoundBuf->buffer);
+	selectedSoundBuf->buffer = nullptr;
+}
+
+void IMuseDigiFilesHandler::flushSounds() {
+	if (_engine->isEngineDisabled())
+		return;
+
+	ImuseDigiSndMgr::SoundDesc *s = _sound->getSounds();
+	for (int i = 0; i < MAX_IMUSE_SOUNDS; i++) {
+		ImuseDigiSndMgr::SoundDesc *curSnd = &s[i];
+		if (curSnd && curSnd->inUse) {
+			if (curSnd->scheduledForDealloc)
+				if (!_engine->diMUSEGetParam(curSnd->soundId, DIMUSE_P_SND_TRACK_NUM) && !_engine->diMUSEGetParam(curSnd->soundId, DIMUSE_P_TRIGS_SNDS))
+					_sound->closeSound(curSnd);
+		}
+	}
+}
+
+int IMuseDigiFilesHandler::setCurrentSpeechFilename(const char *fileName) {
+	Common::strlcpy(_currentSpeechFilename, fileName, sizeof(_currentSpeechFilename));
+	if (openSound(kTalkSoundID))
+		return 1;
+
+	return 0;
+}
+
+void IMuseDigiFilesHandler::closeSoundImmediatelyById(int soundId) {
+	if (_engine->isEngineDisabled())
+		return;
+
+	_sound->closeSoundById(soundId);
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_files.h b/engines/grim/imuse/dimuse_files.h
new file mode 100644
index 00000000000..b6bbf73efcc
--- /dev/null
+++ b/engines/grim/imuse/dimuse_files.h
@@ -0,0 +1,65 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef GRIM_IMUSE_FILES_H
+#define GRIM_IMUSE_FILES_H
+
+#include "common/scummsys.h"
+#include "common/textconsole.h"
+#include "common/util.h"
+#include "engines/grim/imuse/dimuse_bndmgr.h"
+#include "engines/grim/imuse/dimuse_sndmgr.h"
+
+namespace Grim {
+
+class IMuseDigiFilesHandler {
+
+private:
+	IMuseDigital *_engine;
+	ImuseDigiSndMgr *_sound;
+	Common::Mutex _mutex;
+	IMuseDigiSndBuffer _soundBuffers[4];
+	char _currentSpeechFilename[60] = {};
+
+	void getFilenameFromSoundId(int soundId, char *fileName, size_t size);
+public:
+	IMuseDigiFilesHandler(IMuseDigital *engine);
+	~IMuseDigiFilesHandler();
+
+	uint8 *getSoundAddrData(int soundId);
+	int getSoundAddrDataSize(int soundId, bool hasStream);
+	int getNextSound(int soundId);
+	int seek(int soundId, int32 offset, int mode, int bufId);
+	int read(int soundId, uint8 *buf, int32 size, int bufId);
+	IMuseDigiSndBuffer *getBufInfo(int bufId);
+	int openSound(int soundId);
+	void closeSound(int soundId);
+	void closeAllSounds();
+	void allocSoundBuffer(int bufId, int32 size, int32 loadSize, int32 criticalSize);
+	void deallocSoundBuffer(int bufId);
+	void flushSounds();
+	int setCurrentSpeechFilename(const char *fileName);
+	void closeSoundImmediatelyById(int soundId);
+	void saveLoad(Common::Serializer &ser);
+};
+
+} // End of namespace Grim
+#endif
diff --git a/engines/grim/imuse/dimuse_groups.cpp b/engines/grim/imuse/dimuse_groups.cpp
new file mode 100644
index 00000000000..77e42de3fb3
--- /dev/null
+++ b/engines/grim/imuse/dimuse_groups.cpp
@@ -0,0 +1,84 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/dimuse_groups.h"
+
+namespace Grim {
+
+IMuseDigiGroupsHandler::IMuseDigiGroupsHandler(IMuseDigital *engine, Common::Mutex *mutex) {
+	_engine = engine;
+	_mutex = mutex;
+}
+
+IMuseDigiGroupsHandler::~IMuseDigiGroupsHandler() {}
+
+int IMuseDigiGroupsHandler::init() {
+	for (int i = 0; i < DIMUSE_MAX_GROUPS; i++) {
+		_effVols[i] = 127;
+		_vols[i] = 127;
+	}
+	return 0;
+}
+
+int IMuseDigiGroupsHandler::setGroupVol(int id, int volume) {
+	Common::StackLock lock(*_mutex);
+
+	int l;
+
+	if (id >= DIMUSE_MAX_GROUPS) {
+		return -5;
+	}
+
+	if (volume == -1) {
+		return _vols[id];
+	}
+
+	if (volume > 127)
+		return -5;
+
+	if (id) {
+		_vols[id] = volume;
+		_effVols[id] = (_vols[0] * (volume + 1)) / 128;
+	} else {
+		_effVols[0] = volume;
+		_vols[0] = volume;
+
+		for (l = 1; l < DIMUSE_MAX_GROUPS; l++) {
+			_effVols[l] = (volume * (_vols[l] + 1)) / 128;
+		}
+	}
+
+	_engine->diMUSEUpdateGroupVolumes();
+	return _vols[id];
+}
+
+int IMuseDigiGroupsHandler::getGroupVol(int id) {
+	Common::StackLock lock(*_mutex);
+
+	if (id >= DIMUSE_MAX_GROUPS) {
+		return -5;
+	}
+
+	return _effVols[id];
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_groups.h b/engines/grim/imuse/dimuse_groups.h
new file mode 100644
index 00000000000..512a0c82f58
--- /dev/null
+++ b/engines/grim/imuse/dimuse_groups.h
@@ -0,0 +1,50 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef GRIM_IMUSE_GROUPS_H
+#define GRIM_IMUSE_GROUPS_H
+
+#include "common/scummsys.h"
+#include "common/mutex.h"
+#include "common/serializer.h"
+#include "common/textconsole.h"
+#include "common/util.h"
+#include "engines/grim/imuse/dimuse_engine.h"
+
+namespace Grim {
+
+class IMuseDigiGroupsHandler {
+
+private:
+	IMuseDigital *_engine;
+	Common::Mutex *_mutex;
+	int _effVols[DIMUSE_MAX_GROUPS] = {};
+	int _vols[DIMUSE_MAX_GROUPS] = {};
+public:
+	IMuseDigiGroupsHandler(IMuseDigital *engine, Common::Mutex *mutex);
+	~IMuseDigiGroupsHandler();
+	int init();
+	int setGroupVol(int id, int volume);
+	int getGroupVol(int id);
+};
+
+} // End of namespace Grim
+#endif
diff --git a/engines/grim/imuse/dimuse_internalmixer.cpp b/engines/grim/imuse/dimuse_internalmixer.cpp
new file mode 100644
index 00000000000..b3985fc4239
--- /dev/null
+++ b/engines/grim/imuse/dimuse_internalmixer.cpp
@@ -0,0 +1,1298 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "common/scummsys.h"
+#include "common/mutex.h"
+#include "common/serializer.h"
+#include "common/textconsole.h"
+#include "common/util.h"
+
+#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/dimuse_internalmixer.h"
+
+namespace Grim {
+
+IMuseDigiInternalMixer::IMuseDigiInternalMixer(Audio::Mixer *mixer, int sampleRate, bool lowLatencyMode) {
+	_mixer = mixer;
+	_sampleRate = sampleRate;
+	_lowLatencyMode = lowLatencyMode;
+
+	// Mark all separate streams for low latency mode as available...
+	for (int i = 0; i < ARRAYSIZE(_separateStreams); i++) {
+		_separateStreams[i] = nullptr;
+	}
+
+	if (!_lowLatencyMode)
+		_stream = Audio::makeQueuingAudioStream(_sampleRate, _mixer->getOutputStereo());
+	else
+		_stream = nullptr;
+
+	_amp8Table = nullptr;
+}
+
+IMuseDigiInternalMixer::~IMuseDigiInternalMixer() {
+	free(_amp8Table);
+	_amp8Table = nullptr;
+}
+
+// Lookup table for a linear volume ramp (0 to 16) accounting for panning (-8 to 8)
+static const int8 _stereoVolumeTable[284] = {
+	0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
+	0,  0,  0,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,  2,  0,  0,  1,  1,  1,  1,  2,  2,  2,
+	2,  2,  3,  3,  3,  3,  3,  3,  0,  0,  1,  1,  2,  2,  2,  3,  3,  3,  3,  4,  4,  4,  4,  4,  4,  0,
+	0,  1,  1,  2,  2,  3,  3,  4,  4,  4,  4,  5,  5,  5,  5,  5,  0,  1,  1,  2,  2,  3,  3,  4,  4,  5,
+	5,  5,  6,  6,  6,  6,  6,  0,  1,  1,  2,  3,  3,  4,  4,  5,  5,  6,  6,  6,  7,  7,  7,  7,  0,  1,
+	2,  2,  3,  4,  4,  5,  6,  6,  7,  7,  7,  8,  8,  8,  8,  0,  1,  2,  3,  3,  4,  5,  6,  6,  7,  7,
+	8,  8,  9,  9,  9,  9,  0,  1,  2,  3,  4,  5,  6,  6,  7,  8,  8,  9,  9,  10, 10, 10, 10, 0,  1,  2,
+	3,  4,  5,  6,  7,  8,  9,  9,  10, 10, 11, 11, 11, 11, 0,  1,  2,  3,  5,  6,  7,  8,  8,  9,  10, 11,
+	11, 11, 12, 12, 12, 0,  1,  3,  4,  5,  6,  7,  8,  9,  10, 11, 11, 12, 12, 13, 13, 13, 0,  1,  3,  4,
+	5,  7,  8,  9,  10, 11, 12, 12, 13, 13, 14, 14, 14, 0,  1,  3,  4,  6,  7,  8,  10, 11, 12, 12, 13, 14,
+	14, 15, 15, 15, 0,  2,  3,  5,  6,  8,  9,  10, 11, 12, 13, 14, 15, 15, 16, 16, 16, 0,  0,  0
+};
+
+int IMuseDigiInternalMixer::init(int bytesPerSample, int numChannels, uint8 *mixBuf, int mixBufSize, int sizeSampleKB, int mixChannelsNum) {
+	int amplitudeValue;
+	int waveMixChannelsCount;
+	uint softLdenominator;
+	uint softLnumerator;
+	int softLcurValue;
+	int zeroCenterOffset;
+
+	_outWordSize = bytesPerSample;
+	_outChannelCount = numChannels;
+	_mixBufSize = mixBufSize;
+	_stereoReverseFlag = sizeSampleKB;
+	_mixBuf = mixBuf;
+
+	waveMixChannelsCount = mixChannelsNum;
+
+	// We're allocating:
+	// - The amplitude quantization table for 8-bit audio ((17 * 256) int16 == 2176 int32)
+	// - The amplitude quantization table for 12-bit/16-bit audio ((17 * 4096) int16 == 34816 int32)
+	// - The pseudologarithmic curve for volume fade ((8 * 4096) int16 == 16384 int32)
+	//
+	// For the first two tables 17 represents the volume range (0-16), while
+	// 256 and 4096 are respectively the dynamic range for 8-bit and 12-bit audio;
+	//
+	// Every table is initialized with int16 values, but stored as int32 and manipulated
+	// at different levels of granularity depending on the case (as uint32, uint16 or uint8).
+	// The latter is populated from the middle, inside-out; hence _softLMID.
+
+	int32 *tableMalloc = (int32 *)malloc(53376 * sizeof(int32));
+
+	_amp8Table = tableMalloc;          // Dim: 2176
+	_amp12Table = tableMalloc + 2176;  // Dim: 34816
+	_softLTable = tableMalloc + 36992; // Dim: 16384
+	_softLMID = tableMalloc + 45184;   // Mid table
+
+	if (tableMalloc) {
+		// Any unpopulated cell is expected to be set to 0
+		memset(tableMalloc, 0, 53376 * sizeof(int32));
+		zeroCenterOffset = 0;
+		for (int i = 0; i < 17; i++) {
+			amplitudeValue = -2048 * zeroCenterOffset;
+			for (int j = 0; j < 256; j++) {
+				((int16 *)&_amp8Table[i * 128])[j] = (int16)(amplitudeValue / 127);
+				amplitudeValue += 16 * zeroCenterOffset;
+			}
+
+			zeroCenterOffset += 8;
+			if (zeroCenterOffset == 8)
+				zeroCenterOffset = 7;
+		}
+
+		zeroCenterOffset = 0;
+		for (int i = 0; i < 17; i++) {
+			amplitudeValue = -2048 * zeroCenterOffset;
+			for (int j = 0; j < 4096; j++) {
+				((int16 *)&_amp12Table[i * 2048])[j] = (int16)(amplitudeValue / 127);
+				amplitudeValue += zeroCenterOffset;
+			}
+
+			zeroCenterOffset += 8;
+			if (zeroCenterOffset == 8)
+				zeroCenterOffset = 7;
+		}
+
+		if (_outWordSize == 8) {
+			if (waveMixChannelsCount * 1024 > 0) {
+				softLnumerator = 0;
+				softLdenominator = 2047 * waveMixChannelsCount;
+				for (int i = 0; i < waveMixChannelsCount * 2048; i++) {
+					softLcurValue = softLnumerator / softLdenominator + 1;
+					softLdenominator += waveMixChannelsCount - 1;
+					softLnumerator += 254 * waveMixChannelsCount;
+					softLcurValue /= 2;
+
+					((int8 *)_softLMID)[i] = (int8)softLcurValue + 128;
+					((int8 *)_softLMID)[-i] = 127 - (int8)softLcurValue;
+				}
+			}
+		} else if (waveMixChannelsCount * 2048 > 0) {
+			softLdenominator = 2047 * waveMixChannelsCount;
+			softLnumerator = 0;
+			for (int i = 0; i < waveMixChannelsCount * 2048; i++) {
+				softLcurValue = softLnumerator / softLdenominator + 1;
+				softLcurValue /= 2;
+				softLdenominator += waveMixChannelsCount - 1;
+				softLnumerator += 65534 * waveMixChannelsCount;
+				((int16 *)_softLMID)[i] = (int16)softLcurValue;
+				((int16 *)_softLMID)[-i - 1] = -1 - (int16)softLcurValue;
+			}
+		}
+
+		if (!_lowLatencyMode) {
+			_mixer->playStream(
+				Audio::Mixer::kPlainSoundType,
+				&_channelHandle,
+				_stream,
+				-1,
+				Audio::Mixer::kMaxChannelVolume);
+		}
+
+		return 0;
+	} else {
+		debug(5, "IMuseDigiInternalMixer::init(): ERROR: couldn't allocate mixer tables");
+		return -1;
+	}
+}
+
+int IMuseDigiInternalMixer::clearMixerBuffer() {
+	if (!_mixBuf)
+		return -1;
+
+	memset(_mixBuf, 0, _mixBufSize);
+
+	return 0;
+}
+
+void IMuseDigiInternalMixer::mix(uint8 *srcBuf, int32 inFrameCount, int wordSize, int channelCount, int feedSize, int32 mixBufStartIndex, int volume, int pan) {
+	int32 *ampTable;
+	int rightChannelVolume;
+	int leftChannelVolume;
+	int channelVolume;
+	int channelPan;
+
+	if (_mixBuf) {
+		if (srcBuf) {
+			if (inFrameCount) {
+				if (channelCount == 1 && _outChannelCount == 2) {
+					channelVolume = volume / 8;
+					if (volume)
+						++channelVolume;
+					if (channelVolume >= 17)
+						channelVolume = 16;
+					channelPan = (pan / 8) - 8;
+					if (pan > 64)
+						++channelPan;
+
+					channelPan = channelVolume == 0 ? 0 : channelPan;
+
+					// Linear volume quantization from the lookup table
+					rightChannelVolume = _stereoVolumeTable[17 * channelVolume + channelPan];
+					leftChannelVolume = _stereoVolumeTable[17 * channelVolume - channelPan];
+					if (wordSize == 8) {
+						mixBits8ConvertToStereo(
+							srcBuf,
+							inFrameCount,
+							feedSize,
+							mixBufStartIndex,
+							&_amp8Table[leftChannelVolume * 128],
+							&_amp8Table[rightChannelVolume * 128]);
+					} else if (wordSize == 12) {
+						mixBits12ConvertToStereo(
+							srcBuf,
+							inFrameCount,
+							feedSize,
+							mixBufStartIndex,
+							&_amp12Table[leftChannelVolume * 2048],
+							&_amp12Table[rightChannelVolume * 2048]);
+					} else {
+						mixBits16ConvertToStereo(
+							srcBuf,
+							inFrameCount,
+							feedSize,
+							mixBufStartIndex,
+							&_amp12Table[leftChannelVolume * 2048],
+							&_amp12Table[rightChannelVolume * 2048]);
+					}
+				} else {
+					channelVolume = volume / 8;
+					if (volume)
+						channelVolume++;
+					if (channelVolume >= 17)
+						channelVolume = 16;
+
+					if (wordSize == 8)
+						ampTable = &_amp8Table[channelVolume * 128];
+					else
+						ampTable = &_amp12Table[channelVolume * 2048];
+
+					if (_outChannelCount == 1) {
+						if (channelCount == 1) {
+							if (wordSize == 8) {
+								mixBits8Mono(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
+							} else if (wordSize == 12) {
+								mixBits12Mono(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
+							} else {
+								mixBits16Mono(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
+							}
+						} else if (wordSize == 8) {
+							mixBits8ConvertToMono(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
+						} else if (wordSize == 12) {
+							mixBits12ConvertToMono(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
+						} else {
+							mixBits16ConvertToMono(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
+						}
+					} else if (wordSize == 8) {
+						mixBits8Stereo(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
+					} else if (wordSize == 12) {
+						mixBits12Stereo(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
+					} else {
+						mixBits16Stereo(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
+					}
+				}
+			}
+		}
+	}
+}
+
+int IMuseDigiInternalMixer::loop(uint8 **destBuffer, int len) {
+	int16 *mixBuffer = (int16 *)_mixBuf;
+	uint8 *destBuffer_tmp = *destBuffer;
+
+	if (!_mixBuf || !destBuffer || !len)
+		return -1;
+
+	if (_outChannelCount == 2)
+		len *= 2;
+
+	if (!_stereoReverseFlag || _outChannelCount == 1) {
+		if (_outWordSize != 16) {
+			if (len) {
+				for (int i = 0; i < len; i++) {
+					destBuffer_tmp[i] = ((uint8 *)_softLMID)[mixBuffer[i]];
+				}
+			}
+		}
+
+		if (len) {
+			for (int i = 0; i < len; i++) {
+				((uint16 *)destBuffer_tmp)[i] = ((uint16 *)_softLMID)[mixBuffer[i]];
+			}
+		}
+	} else {
+		len /= 2;
+		if (_outWordSize == 16) {
+			if (len) {
+				for (int i = 0; i < len; i += 2) {
+					((uint16 *)destBuffer_tmp)[i]     = ((uint16 *)_softLMID)[mixBuffer[i + 1]];
+					((uint16 *)destBuffer_tmp)[i + 1] = ((uint16 *)_softLMID)[mixBuffer[i]];
+				}
+			}
+		}
+
+		if (len) {
+			for (int i = 0; i < len; i += 2) {
+				destBuffer_tmp[i] = ((uint8 *)_softLMID)[mixBuffer[i + 1]];
+				destBuffer_tmp[i + 1] = ((uint8 *)_softLMID)[mixBuffer[i]];
+			}
+		}
+	}
+	return 0;
+}
+
+void IMuseDigiInternalMixer::setCurrentMixerBuffer(uint8 *newBuf) {
+	// Used to swap mixer buffers in low latency mode
+	_mixBuf = newBuf;
+}
+
+void IMuseDigiInternalMixer::endStream(int idx) {
+	// We mark the stream as finished and then remove
+	// the reference: in this way, the stream will have time
+	// to flush the remaining sound data and will be disposed
+	// by the mixer, while we freed up a slot for a new stream.
+	if (_lowLatencyMode && idx != -1) {
+		_separateStreams[idx]->finish();
+		_separateStreams[idx] = nullptr;
+	}
+}
+
+Audio::QueuingAudioStream *IMuseDigiInternalMixer::getStream(int idx) {
+	if (!_lowLatencyMode || idx == -1) {
+		// Stream for the original mode
+		return _stream;
+	} else if (!_separateStreams[idx]) {
+		// New stream for a new sound
+		_separateStreams[idx] = Audio::makeQueuingAudioStream(_sampleRate, _mixer->getOutputStereo());
+
+		_mixer->playStream(
+			Audio::Mixer::kPlainSoundType,
+			&_separateChannelHandles[idx],
+			_separateStreams[idx],
+			-1,
+			Audio::Mixer::kMaxChannelVolume);
+
+		return _separateStreams[idx];
+	} else {
+		// On-going stream
+		return _separateStreams[idx];
+	}
+}
+
+void IMuseDigiInternalMixer::mixBits8Mono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
+	uint16 *mixBufCurCell;
+	uint8 *srcBuf_ptr;
+	int residualLength;
+
+	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
+	srcBuf_ptr = srcBuf;
+	if (inFrameCount == feedSize) {
+		if (feedSize) {
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[i] += *((uint16 *)ampTable + srcBuf_ptr[i]);
+			}
+		}
+	} else if (2 * inFrameCount == feedSize) {
+		if (inFrameCount - 1 != 0) {
+			for (int i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+				mixBufCurCell[1] += (*((int16 *)ampTable + srcBuf_ptr[0]) + *((int16 *)ampTable + srcBuf_ptr[1])) >> 1;
+				mixBufCurCell += 2;
+				srcBuf_ptr += 1;
+			}
+		}
+		mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+		mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+	} else if (2 * feedSize == inFrameCount) {
+		if (feedSize) {
+			for (int i = 0, j = 0; i < feedSize; i++, j += 2) {
+				mixBufCurCell[i] += *((uint16 *)ampTable + srcBuf_ptr[j]);
+			}
+		}
+	} else {
+		residualLength = -inFrameCount;
+		if (feedSize) {
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[i] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+				// Seek the next srcBuf element until there's excess length
+				for (residualLength += inFrameCount; residualLength >= 0; ++srcBuf_ptr)
+					residualLength -= feedSize;
+			}
+		}
+	}
+}
+
+void IMuseDigiInternalMixer::mixBits12Mono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
+	uint16 *mixBufCurCell;
+	uint8 *srcBuf_ptr;
+	int xorFlag;
+	int residualLength;
+	int term_1;
+	int term_2;
+
+	if ((inFrameCount & 1) != 0) {
+		inFrameCount &= 0xFFFFFFFE;
+		debug(5, "DiMUSE_InternalMixer::mixBits12Mono(): WARNING: odd inFrameCount with 12-bit data");
+	}
+
+	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
+	if (feedSize == inFrameCount) {
+		if (inFrameCount / 2) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < inFrameCount / 2; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+				mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+				srcBuf_ptr += 3;
+				mixBufCurCell += 2;
+			}
+		}
+	} else if (2 * inFrameCount == feedSize) {
+		srcBuf_ptr = srcBuf;
+		if ((inFrameCount / 2) - 1) {
+			for (int i = 0; i < (inFrameCount / 2) - 1; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+
+				mixBufCurCell[1] += (*((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
+									 *((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))) >> 1;
+
+				mixBufCurCell[2] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+
+				mixBufCurCell[3] += (*((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
+									 *((int16 *)ampTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
+
+				srcBuf_ptr += 3;
+				mixBufCurCell += 4;
+			}
+		}
+
+		mixBufCurCell[0] +=  *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+		mixBufCurCell[1] +=  (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
+			                + *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
+		mixBufCurCell[2] +=  *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[3] +=  *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+	} else if (2 * feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[i] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+				srcBuf_ptr += 3;
+			}
+		}
+	} else {
+		xorFlag = 0;
+		residualLength = -inFrameCount;
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				if (xorFlag) {
+					term_1 = (srcBuf_ptr[1] & 0xF0) << 4;
+					term_2 = srcBuf_ptr[2];
+				} else {
+					term_1 = (srcBuf_ptr[1] & 0xF) << 8;
+					term_2 = srcBuf_ptr[0];
+				}
+
+				mixBufCurCell[i] += *((uint16 *)ampTable + (term_2 | term_1));
+				residualLength += inFrameCount;
+				while (residualLength >= 0) {
+					residualLength -= feedSize;
+					xorFlag ^= 1u;
+					if (!xorFlag)
+						srcBuf_ptr += 3;
+				}
+			}
+		}
+	}
+}
+
+void IMuseDigiInternalMixer::mixBits16Mono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
+	uint16 *mixBufCurCell;
+	uint16 *srcBuf_ptr;
+	int residualLength;
+
+	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
+	if (feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = (uint16 *)srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[i] += *(uint16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[i] & (int16)0xFFF7) >> 3) + 4096);
+			}
+		}
+	} else if (2 * inFrameCount == feedSize) {
+		srcBuf_ptr = (uint16 *)srcBuf;
+		int i = 0;
+		if (inFrameCount - 1 != 0) {
+			for (i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += *(uint16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[i] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[1] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[i] & (int16)0xFFF7) >> 3) + 4096)
+							       + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[i + 1] & (int16) 0xFFF7) >> 3) + 4096)) >> 1;
+				mixBufCurCell += 2;
+			}
+		}
+		mixBufCurCell[0] += *(uint16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[i] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[1] += *(uint16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[i] & (int16)0xFFF7) >> 3) + 4096);
+	} else {
+		if (2 * feedSize == inFrameCount) {
+			if (feedSize) {
+				srcBuf_ptr = (uint16 *)srcBuf;
+				for (int i = 0; i < feedSize; i++) {
+					mixBufCurCell[i] += *(uint16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+					srcBuf_ptr += 2;
+				}
+			}
+		} else {
+			residualLength = -inFrameCount;
+
+			if (feedSize) {
+				srcBuf_ptr = (uint16 *)srcBuf;
+				for (int i = 0; i < feedSize; i++) {
+					mixBufCurCell[i] += *(uint16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+
+					for (residualLength += inFrameCount; residualLength >= 0; ++srcBuf_ptr)
+						residualLength -= feedSize;
+				}
+			}
+		}
+	}
+}
+
+void IMuseDigiInternalMixer::mixBits8ConvertToMono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
+	uint8 *srcBuf_ptr;
+	int residualLength;
+	uint16 *mixBufCurCell;
+
+	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
+	srcBuf_ptr = srcBuf;
+	if (inFrameCount == feedSize) {
+		if (feedSize) {
+			for (int i = 0, j = 0; i < feedSize; i++, j += 2) {
+				mixBufCurCell[i] += (2 * *((int16 *)ampTable + srcBuf_ptr[j])) >> 1;
+			}
+		}
+	} else if (2 * inFrameCount == feedSize) {
+		if (inFrameCount != 1) {
+			for (int i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[0])) >> 1;
+				int term_1 = (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[3])) >> 1;
+				int term_2 =  *((int16 *)ampTable + srcBuf_ptr[0]) + *((int16 *)ampTable + srcBuf_ptr[2]);
+				mixBufCurCell[1] += ((term_2 >> 1) + term_1) >> 1;
+
+				srcBuf_ptr += 2;
+				mixBufCurCell += 2;
+			}
+		}
+		mixBufCurCell[0] += (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[0])) >> 1;
+		mixBufCurCell[1] += (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[0])) >> 1;
+	} else if (2 * feedSize == inFrameCount) {
+		if (feedSize) {
+			for (int i = 0, j = 0; i < feedSize; i++, j += 4) {
+				mixBufCurCell[i] += (2 * *((int16 *)ampTable + srcBuf_ptr[j])) >> 1;
+			}
+		}
+	} else {
+		residualLength = -inFrameCount;
+		if (feedSize) {
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[i] += (*((int16 *)ampTable + srcBuf_ptr[0]) + *((int16 *)ampTable + srcBuf_ptr[1])) >> 1;
+				// Skip srcBuf elements until there's excess length
+				for (residualLength += inFrameCount; residualLength >= 0; srcBuf_ptr += 2)
+					residualLength -= feedSize;
+			}
+		}
+	}
+}
+
+void IMuseDigiInternalMixer::mixBits12ConvertToMono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
+	uint8 *srcBuf_ptr;
+	int residualLength;
+	uint16 *mixBufCurCell;
+	int term_1;
+	int term_2;
+
+	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
+	if (feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[i] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8))) +
+									 *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
+				srcBuf_ptr += 3;
+			}
+		}
+	} else if (2 * inFrameCount == feedSize) {
+		srcBuf_ptr = srcBuf;
+		if (inFrameCount - 1 != 0) {
+			for (int i = 0; i < inFrameCount - 1; i++) {
+				term_1 = *((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF0) << 8)));
+				term_2 = *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF)  << 4)));
+
+				mixBufCurCell[0] += (term_1 + term_2) >> 1;
+				mixBufCurCell[1] += (((term_1 + *((int16 *)ampTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1)
+								   + ((term_2 + *((int16 *)ampTable + (srcBuf_ptr[5] | ((srcBuf_ptr[4] & 0xF0) << 4)))) >> 1)) >> 1;
+
+				srcBuf_ptr += 3;
+				mixBufCurCell += 2;
+			}
+		}
+
+		mixBufCurCell[0] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
+						   + *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
+		mixBufCurCell[1] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
+						   + *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
+
+
+	} else if (2 * feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+
+			for (int i = 0; i < feedSize; i++) {
+
+				mixBufCurCell[i] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
+								   + *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
+
+				srcBuf_ptr += 6;
+			}
+		}
+	} else {
+		residualLength = -inFrameCount;
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[i] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
+								   + *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
+
+				for (residualLength += inFrameCount; residualLength >= 0; srcBuf_ptr += 3)
+					residualLength -= feedSize;
+			}
+		}
+	}
+}
+
+void IMuseDigiInternalMixer::mixBits16ConvertToMono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
+	uint16 *mixBufCurCell;
+	uint16 *srcBuf_ptr;
+	int residualLength;
+
+	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
+	if (feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = (uint16 *)srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[i] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)
+								   + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
+				srcBuf_ptr += 2;
+			}
+		}
+	} else if (2 * inFrameCount == feedSize) {
+		srcBuf_ptr = (uint16 *)srcBuf;
+		if (inFrameCount - 1 != 0) {
+			for (int i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)
+								   + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
+
+				mixBufCurCell[1] +=  (((*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)
+									+   *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[2] & (int16)0xFFF7) >> 3) + 4096)) >> 1)
+									+ ((*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)
+									+   *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[3] & (int16)0xFFF7) >> 3) + 4096)) >> 1)) >> 1;
+				mixBufCurCell += 2;
+				srcBuf_ptr += 2;
+			}
+		}
+
+		mixBufCurCell[0] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)
+						   + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
+		mixBufCurCell[1] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)
+						   + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
+	} else if (2 * feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = (uint16 *)srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[i] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)
+								   + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
+				srcBuf_ptr += 4;
+			}
+		}
+	} else {
+		residualLength = -inFrameCount;
+
+		if (feedSize) {
+			srcBuf_ptr = (uint16 *)srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[i] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)
+								   + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
+
+				for (residualLength += inFrameCount; residualLength >= 0; srcBuf_ptr += 2)
+					residualLength -= feedSize;
+			}
+		}
+	}
+}
+
+void IMuseDigiInternalMixer::mixBits8ConvertToStereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *leftAmpTable, int32 *rightAmpTable) {
+	uint16 *mixBufCurCell;
+	uint8 *srcBuf_ptr;
+	int residualLength;
+
+	mixBufCurCell = (uint16 *)(&_mixBuf[4 * mixBufStartIndex]);
+	if (feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
+				mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
+				mixBufCurCell += 2;
+			}
+		}
+	} else if (2 * inFrameCount == feedSize) {
+		srcBuf_ptr = srcBuf;
+		int i = 0;
+		if (inFrameCount - 1 != 0) {
+			for (i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
+				mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
+				mixBufCurCell[2] += (*((int16 *)leftAmpTable  + srcBuf_ptr[i]) + *((int16 *)leftAmpTable  + srcBuf_ptr[i + 1])) >> 1;
+				mixBufCurCell[3] += (*((int16 *)rightAmpTable + srcBuf_ptr[i]) + *((int16 *)rightAmpTable + srcBuf_ptr[i + 1])) >> 1;
+				mixBufCurCell += 4;
+			}
+		}
+		mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
+		mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
+		mixBufCurCell[2] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
+		mixBufCurCell[3] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
+	} else if (2 * feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[0]);
+				mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[0]);
+				mixBufCurCell += 2;
+				srcBuf_ptr += 2;
+			}
+		}
+	} else if (4 * inFrameCount == feedSize) {
+		srcBuf_ptr = srcBuf;
+		int i = 0;
+		if (inFrameCount - 1 != 0) {
+			for (i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
+				mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
+				mixBufCurCell[2] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
+				mixBufCurCell[3] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
+
+				mixBufCurCell[4] += (*((int16 *)leftAmpTable  + srcBuf_ptr[i]) + *((int16 *)leftAmpTable  + srcBuf_ptr[i + 1])) >> 1;
+				mixBufCurCell[5] += (*((int16 *)rightAmpTable + srcBuf_ptr[i]) + *((int16 *)rightAmpTable + srcBuf_ptr[i + 1])) >> 1;
+				mixBufCurCell[6] += (*((int16 *)leftAmpTable  + srcBuf_ptr[i]) + *((int16 *)leftAmpTable  + srcBuf_ptr[i + 1])) >> 1;
+				mixBufCurCell[7] += (*((int16 *)rightAmpTable + srcBuf_ptr[i]) + *((int16 *)rightAmpTable + srcBuf_ptr[i + 1])) >> 1;
+				mixBufCurCell += 8;
+			}
+		}
+		mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
+		mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
+		mixBufCurCell[2] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
+		mixBufCurCell[3] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
+
+		mixBufCurCell[4] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
+		mixBufCurCell[5] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
+		mixBufCurCell[6] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
+		mixBufCurCell[7] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
+	} else {
+		residualLength = -inFrameCount;
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[0]);
+				mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[0]);
+				mixBufCurCell += 2;
+
+				for (residualLength += inFrameCount; residualLength > 0; ++srcBuf_ptr)
+					residualLength -= feedSize;
+			}
+		}
+	}
+}
+
+void IMuseDigiInternalMixer::mixBits12ConvertToStereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *leftAmpTable, int32 *rightAmpTable) {
+	uint16 *mixBufCurCell;
+	uint8 *srcBuf_ptr;
+
+	int xorFlag;
+	int residualLength;
+
+	mixBufCurCell = (uint16 *)(&_mixBuf[4 * mixBufStartIndex]);
+	if (feedSize == inFrameCount) {
+		if (inFrameCount / 2) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < (inFrameCount / 2); i++) {
+				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+				mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+				mixBufCurCell[2] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+				mixBufCurCell[3] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+				srcBuf_ptr += 3;
+				mixBufCurCell += 4;
+			}
+		}
+	} else if (2 * inFrameCount == feedSize) {
+		srcBuf_ptr = srcBuf;
+		if ((inFrameCount / 2) - 1 != 0) {
+			for (int i = 0; i < (inFrameCount / 2) - 1; i++) {
+				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+				mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+
+				mixBufCurCell[2] += (*((int16 *)leftAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))
+								   + *((int16 *)leftAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))) >> 1;
+
+				mixBufCurCell[3] += (*((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))
+								   + *((int16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))) >> 1;
+
+				mixBufCurCell[4] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+				mixBufCurCell[5] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+
+				mixBufCurCell[6] += (*((int16 *)leftAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
+									 *((int16 *)leftAmpTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
+
+				mixBufCurCell[7] += (*((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
+									 *((int16 *)rightAmpTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
+
+				srcBuf_ptr += 3;
+				mixBufCurCell += 8;
+			}
+		}
+		mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+		mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+
+		mixBufCurCell[2] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
+						   + *((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
+
+		mixBufCurCell[3] += (*((int16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
+						   + *((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
+
+		mixBufCurCell[4] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[5] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[6] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[7] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+	} else if (2 * feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+				mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+				srcBuf_ptr += 3;
+				mixBufCurCell += 2;
+			}
+		}
+	} else if (4 * inFrameCount == feedSize) {
+		srcBuf_ptr = srcBuf;
+		if ((inFrameCount / 2) - 1 != 0) {
+			for (int i = 0; i < (inFrameCount / 2) - 1; i++) {
+				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+				mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+				mixBufCurCell[2] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+				mixBufCurCell[3] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+
+				mixBufCurCell[4] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) + *((int16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)))) >> 1;
+				mixBufCurCell[5] += (*((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) + *((int16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)))) >> 1;
+				mixBufCurCell[6] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) + *((int16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)))) >> 1;
+				mixBufCurCell[7] += (*((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) + *((int16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)))) >> 1;
+
+				mixBufCurCell[8]  += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+				mixBufCurCell[9]  += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+				mixBufCurCell[10] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+				mixBufCurCell[11] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+
+				mixBufCurCell[12] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
+									  *((int16 *)leftAmpTable  + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
+				mixBufCurCell[13] += (*((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
+									  *((int16 *)rightAmpTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
+				mixBufCurCell[14] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
+									  *((int16 *)leftAmpTable  + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
+				mixBufCurCell[15] += (*((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
+									  *((int16 *)rightAmpTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
+
+				srcBuf_ptr += 3;
+				mixBufCurCell += 16;
+			}
+		}
+		mixBufCurCell[0] += *((uint16 *)leftAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+		mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+		mixBufCurCell[2] += *((uint16 *)leftAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+		mixBufCurCell[3] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
+
+		mixBufCurCell[4] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8))) + *((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
+		mixBufCurCell[5] += (*((int16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8))) + *((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
+		mixBufCurCell[6] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8))) + *((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
+		mixBufCurCell[7] += (*((int16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8))) + *((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
+
+		mixBufCurCell[8] += *((uint16 *)leftAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[9] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[10] += *((uint16 *)leftAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[11] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+
+		mixBufCurCell[12] += *((uint16 *)leftAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[13] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[14] += *((uint16 *)leftAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[15] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+	} else {
+		xorFlag = 0;
+		residualLength = -inFrameCount;
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				if (xorFlag) {
+					mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | (srcBuf_ptr[1] & 0xF0) << 4));
+					mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | (srcBuf_ptr[1] & 0xF0) << 4));
+				} else {
+					mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | (srcBuf_ptr[1] & 0xF)  << 8));
+					mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | (srcBuf_ptr[1] & 0xF)  << 8));
+				}
+
+				residualLength += inFrameCount;
+				while (residualLength > 0) {
+					residualLength -= feedSize;
+					xorFlag ^= 1u;
+					if (!xorFlag)
+						srcBuf_ptr += 3;
+				}
+
+				mixBufCurCell += 2;
+			}
+		}
+	}
+}
+
+void IMuseDigiInternalMixer::mixBits16ConvertToStereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *leftAmpTable, int32 *rightAmpTable) {
+	uint16 *mixBufCurCell;
+	uint16 *srcBuf_tmp;
+	int residualLength;
+
+	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
+
+	if (feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_tmp = (uint16 *)srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell += 2;
+			}
+		}
+	} else if (2 * inFrameCount == feedSize) {
+		srcBuf_tmp = (uint16 *)srcBuf;
+		int i = 0;
+		if (inFrameCount - 1 != 0) {
+			for (i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+
+				mixBufCurCell[2] += (*(int16 *)((uint8 *)leftAmpTable + (((int16)srcBuf_tmp[i]     & (int16)0xFFF7) >> 3) + 4096)
+								   + *(int16 *)((uint8 *)leftAmpTable + (((int16)srcBuf_tmp[i + 1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
+
+				mixBufCurCell[3] += (*(int16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i]     & (int16)0xFFF7) >> 3) + 4096)
+								   + *(int16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i + 1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
+				mixBufCurCell += 4;
+			}
+		}
+		mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[2] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[3] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+	} else if (2 * feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_tmp = (uint16 *)srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[0] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[0] & (int16)0xFFF7) >> 3) + 4096);
+				srcBuf_tmp += 2;
+				mixBufCurCell += 2;
+			}
+		}
+	} else if (4 * inFrameCount == feedSize) {
+		srcBuf_tmp = (uint16 *)srcBuf;
+		int i = 0;
+		if (inFrameCount - 1 != 0) {
+			for (i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[2] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[3] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+
+				mixBufCurCell[4] += (*(int16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096) + *(int16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i + 1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
+				mixBufCurCell[5] += (*(int16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096) + *(int16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i + 1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
+				mixBufCurCell[6] += (*(int16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096) + *(int16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i + 1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
+				mixBufCurCell[7] += (*(int16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096) + *(int16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i + 1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
+				mixBufCurCell += 8;
+			}
+		}
+		mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[2] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[3] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+
+		mixBufCurCell[4] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[5] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[6] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[7] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
+	} else {
+		residualLength = -inFrameCount;
+		if (feedSize) {
+			srcBuf_tmp = (uint16 *)srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[0] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[0] & (int16)0xFFF7) >> 3) + 4096);
+
+				for (residualLength += inFrameCount; residualLength > 0; ++srcBuf_tmp)
+					residualLength -= feedSize;
+
+				mixBufCurCell += 2;
+			}
+		}
+	}
+}
+
+void IMuseDigiInternalMixer::mixBits8Stereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
+	uint16 *mixBufCurCell;
+	uint8 *srcBuf_ptr;
+	int residualLength;
+
+	mixBufCurCell = (uint16 *)(&_mixBuf[4 * mixBufStartIndex]);
+	if (feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+				mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
+				srcBuf_ptr += 2;
+				mixBufCurCell += 2;
+			}
+		}
+	} else if (2 * inFrameCount == feedSize) {
+		srcBuf_ptr = srcBuf;
+		if (inFrameCount - 1 != 0) {
+			for (int i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+				mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
+				mixBufCurCell[2] += (*((int16 *)ampTable + srcBuf_ptr[0]) + *((int16 *)ampTable + srcBuf_ptr[2])) >> 1;
+				mixBufCurCell[3] += (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[3])) >> 1;
+				mixBufCurCell += 4;
+				srcBuf_ptr += 2;
+			}
+		}
+		mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+		mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
+		mixBufCurCell[2] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+		mixBufCurCell[3] += *((uint16 *)ampTable + srcBuf_ptr[1]);
+	} else if (2 * feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+				mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
+				srcBuf_ptr += 4;
+				mixBufCurCell += 2;
+			}
+		}
+	} else if (4 * inFrameCount == feedSize) {
+		srcBuf_ptr = srcBuf;
+		if (inFrameCount - 1 != 0) {
+			for (int i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+				mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
+				mixBufCurCell[2] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+				mixBufCurCell[3] += *((uint16 *)ampTable + srcBuf_ptr[1]);
+
+				mixBufCurCell[4] += (*((int16 *)ampTable + srcBuf_ptr[0]) + *((int16 *)ampTable + srcBuf_ptr[2])) >> 1;
+				mixBufCurCell[5] += (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[3])) >> 1;
+				mixBufCurCell[6] += (*((int16 *)ampTable + srcBuf_ptr[0]) + *((int16 *)ampTable + srcBuf_ptr[2])) >> 1;
+				mixBufCurCell[7] += (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[3])) >> 1;
+
+				mixBufCurCell += 8;
+				srcBuf_ptr += 2;
+			}
+		}
+		mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+		mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
+		mixBufCurCell[2] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+		mixBufCurCell[3] += *((uint16 *)ampTable + srcBuf_ptr[1]);
+
+		mixBufCurCell[4] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+		mixBufCurCell[5] += *((uint16 *)ampTable + srcBuf_ptr[1]);
+		mixBufCurCell[6] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+		mixBufCurCell[7] += *((uint16 *)ampTable + srcBuf_ptr[1]);
+	} else {
+		residualLength = -inFrameCount;
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
+				mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
+				mixBufCurCell += 2;
+				for (residualLength += inFrameCount; residualLength >= 0; srcBuf_ptr += 2)
+					residualLength -= feedSize;
+			}
+		}
+	}
+}
+
+void IMuseDigiInternalMixer::mixBits12Stereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
+	uint16 *mixBufCurCell;
+	uint8 *srcBuf_ptr;
+	int residualLength;
+
+	mixBufCurCell = (uint16 *)(&_mixBuf[4 * mixBufStartIndex]);
+	if (feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+				mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+
+				srcBuf_ptr += 3;
+				mixBufCurCell += 2;
+			}
+		}
+	} else if (2 * inFrameCount == feedSize) {
+		srcBuf_ptr = srcBuf;
+		if (inFrameCount - 1 != 0) {
+			for (int i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+				mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+				mixBufCurCell[2] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
+								   + *((int16 *)ampTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
+				mixBufCurCell[3] += (*((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))
+								   + *((int16 *)ampTable + (srcBuf_ptr[5] | ((srcBuf_ptr[4] & 0xF0) << 4)))) >> 1;
+
+				srcBuf_ptr += 3;
+				mixBufCurCell += 4;
+			}
+		}
+		mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+		mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[2] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+		mixBufCurCell[3] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+	} else if (2 * feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+				mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+
+				srcBuf_ptr += 6;
+				mixBufCurCell += 2;
+			}
+		}
+	} else if (4 * inFrameCount == feedSize) {
+		srcBuf_ptr = srcBuf;
+		if (inFrameCount - 1 != 0) {
+			for (int i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+				mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+				mixBufCurCell[2] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+				mixBufCurCell[3] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+
+				mixBufCurCell[4] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8))) + *((int16 *)ampTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
+				mixBufCurCell[5] += (*((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) + *((int16 *)ampTable + (srcBuf_ptr[5] | ((srcBuf_ptr[4] & 0xF0) << 4)))) >> 1;
+				mixBufCurCell[6] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8))) + *((int16 *)ampTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
+				mixBufCurCell[7] += (*((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) + *((int16 *)ampTable + (srcBuf_ptr[5] | ((srcBuf_ptr[4] & 0xF0) << 4)))) >> 1;
+
+				srcBuf_ptr += 3;
+				mixBufCurCell += 8;
+			}
+		}
+		mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+		mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[2] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+		mixBufCurCell[3] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+
+		mixBufCurCell[4] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+		mixBufCurCell[5] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+		mixBufCurCell[6] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+		mixBufCurCell[7] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+	} else {
+		residualLength = -inFrameCount;
+		if (feedSize) {
+			srcBuf_ptr = srcBuf;
+
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
+				mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
+
+				mixBufCurCell += 2;
+				for (residualLength += inFrameCount; residualLength >= 0; srcBuf_ptr += 3)
+					residualLength -= feedSize;
+			}
+		}
+	}
+}
+
+void IMuseDigiInternalMixer::mixBits16Stereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
+	uint16 *mixBufCurCell;
+	uint16 *srcBuf_ptr;
+	int residualLength;
+
+	mixBufCurCell = (uint16 *)(&_mixBuf[4 * mixBufStartIndex]);
+	if (feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = (uint16 *)srcBuf;
+
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+				srcBuf_ptr += 2;
+				mixBufCurCell += 2;
+			}
+		}
+	} else if (2 * inFrameCount == feedSize) {
+		srcBuf_ptr = (uint16 *)srcBuf;
+
+		if (inFrameCount - 1 != 0) {
+			for (int i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[2] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[3] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+
+				mixBufCurCell += 4;
+				srcBuf_ptr += 2;
+			}
+		}
+		mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[2] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[3] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+
+	} else if (2 * feedSize == inFrameCount) {
+		if (feedSize) {
+			srcBuf_ptr = (uint16 *)srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + ((((int16)srcBuf_ptr[0] & (int16)0xFFF7)) >> 3) + 4096);
+				mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + ((((int16)srcBuf_ptr[1] & (int16)0xFFF7)) >> 3) + 4096);
+				mixBufCurCell += 2;
+				srcBuf_ptr += 4;
+			}
+		}
+	} else if (4 * inFrameCount == feedSize) {
+		srcBuf_ptr = (uint16 *)srcBuf;
+
+		if (inFrameCount - 1 != 0) {
+			for (int i = 0; i < inFrameCount - 1; i++) {
+				mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[2] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[3] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+
+				mixBufCurCell[4] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[5] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[6] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[7] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+
+				mixBufCurCell += 8;
+				srcBuf_ptr += 2;
+			}
+		}
+		mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[2] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[3] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+
+		mixBufCurCell[4] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[5] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[6] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+		mixBufCurCell[7] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+
+	} else {
+		residualLength = -inFrameCount;
+		if (feedSize) {
+			srcBuf_ptr = (uint16 *)srcBuf;
+			for (int i = 0; i < feedSize; i++) {
+				mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
+				mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
+
+				for (residualLength += inFrameCount; residualLength >= 0; srcBuf_ptr += 2)
+					residualLength -= feedSize;
+			}
+		}
+	}
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_internalmixer.h b/engines/grim/imuse/dimuse_internalmixer.h
new file mode 100644
index 00000000000..65c9da545f4
--- /dev/null
+++ b/engines/grim/imuse/dimuse_internalmixer.h
@@ -0,0 +1,99 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef GRIM_IMUSE_MIXER_H
+#define GRIM_IMUSE_MIXER_H
+
+#include "common/scummsys.h"
+#include "common/mutex.h"
+#include "common/serializer.h"
+#include "common/textconsole.h"
+#include "common/util.h"
+
+#include "engines/grim/imuse/dimuse_engine.h"
+#include "audio/mixer.h"
+#include "audio/audiostream.h"
+
+namespace Audio {
+class AudioStream;
+class Mixer;
+class QueuingAudioStream;
+}
+
+namespace Grim {
+
+class IMuseDigiInternalMixer {
+
+private:
+	int32 *_amp8Table = nullptr;
+	int32 *_amp12Table = nullptr;
+	int32 *_softLMID = nullptr;
+	int32 *_softLTable = nullptr;
+
+	uint8 *_mixBuf = nullptr;
+
+	Audio::Mixer *_mixer;
+	Audio::SoundHandle _channelHandle;
+	int _mixBufSize = 0;
+	int _outWordSize = 0;
+	int _outChannelCount = 0;
+	int _sampleRate = 0;
+	int _stereoReverseFlag = 0;
+	bool _lowLatencyMode = false;
+
+	void mixBits8Mono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
+	void mixBits12Mono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
+	void mixBits16Mono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
+
+	void mixBits8ConvertToMono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
+	void mixBits12ConvertToMono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
+	void mixBits16ConvertToMono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
+
+	void mixBits8ConvertToStereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *leftAmpTable, int32 *rightAmpTable);
+	void mixBits12ConvertToStereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *leftAmpTable, int32 *rightAmpTable);
+	void mixBits16ConvertToStereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *leftAmpTable, int32 *rightAmpTable);
+
+	void mixBits8Stereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
+	void mixBits12Stereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
+	void mixBits16Stereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
+
+public:
+	IMuseDigiInternalMixer(Audio::Mixer *mixer, int sampleRate, bool lowLatencyMode = false);
+	~IMuseDigiInternalMixer();
+	int  init(int bytesPerSample, int numChannels, uint8 *mixBuf, int mixBufSize, int sizeSampleKB, int mixChannelsNum);
+	int  clearMixerBuffer();
+
+	void mix(uint8 *srcBuf, int32 inFrameCount, int wordSize, int channelCount, int feedSize, int32 mixBufStartIndex, int volume, int pan);
+	int  loop(uint8 **destBuffer, int len);
+	Audio::QueuingAudioStream *_stream;
+
+	// For low latency audio
+	void setCurrentMixerBuffer(uint8 *newBuf);
+	void endStream(int idx);
+	Audio::QueuingAudioStream *getStream(int idx);
+
+	Audio::QueuingAudioStream *_separateStreams[DIMUSE_MAX_TRACKS];
+	Audio::SoundHandle _separateChannelHandles[DIMUSE_MAX_TRACKS];
+};
+
+} // End of namespace Grim
+
+#endif
diff --git a/engines/grim/imuse/dimuse_scripts.cpp b/engines/grim/imuse/dimuse_scripts.cpp
new file mode 100644
index 00000000000..ad59785eb91
--- /dev/null
+++ b/engines/grim/imuse/dimuse_scripts.cpp
@@ -0,0 +1,396 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_engine.h"
+
+namespace Grim {
+
+#define COMI_STATE_OFFSET 3
+
+int IMuseDigital::scriptParse(int cmd, int a, int b) {
+	if (_scriptInitializedFlag || !cmd) {
+		switch (cmd) {
+		case DIMUSE_C_SCRIPT_INIT:
+			if (_scriptInitializedFlag) {
+				debug(5, "IMuseDigital::scriptParse(): script module already initialized");
+				return -1;
+			} else {
+				_scriptInitializedFlag = 1;
+				return scriptInit();
+			}
+		case DIMUSE_C_SCRIPT_TERMINATE:
+			_scriptInitializedFlag = 0;
+			return scriptTerminate();
+		case DIMUSE_C_SCRIPT_SAVE:
+		case DIMUSE_C_SCRIPT_RESTORE:
+			break;
+		case DIMUSE_C_SCRIPT_REFRESH:
+			scriptRefresh();
+			return 0;
+		case DIMUSE_C_SCRIPT_SET_STATE:
+			scriptSetState(a);
+			return 0;
+		case DIMUSE_C_SCRIPT_SET_SEQUENCE:
+			scriptSetSequence(a);
+			return 0;
+		case DIMUSE_C_SCRIPT_CUE_POINT:
+			scriptSetCuePoint(a);
+			return 0;
+		case DIMUSE_C_SCRIPT_SET_ATTRIBUTE:
+			return scriptSetAttribute(a, b);
+		default:
+			debug(5, "IMuseDigital::scriptParse(): unrecognized opcode (%d)", cmd);
+			return -1;
+		}
+	} else {
+		debug(5, "IMuseDigital::scriptParse(): script module not initialized");
+		return -1;
+	}
+
+	return -1;
+}
+
+int IMuseDigital::scriptInit() {
+	_curMusicState = 0;
+	_curMusicSeq = 0;
+	_nextSeqToPlay = 0;
+	memset(_attributes, 0, sizeof(_attributes));
+	return 0;
+}
+
+int IMuseDigital::scriptTerminate() {
+	diMUSETerminate();
+
+	_curMusicState = 0;
+	_curMusicSeq = 0;
+	_nextSeqToPlay = 0;
+	memset(_attributes, 0, sizeof(_attributes));
+	return 0;
+}
+
+void IMuseDigital::scriptRefresh() {
+	int soundId;
+	int nextSound;
+
+	if (_stopSequenceFlag) {
+		scriptSetSequence(0);
+		_stopSequenceFlag = 0;
+	}
+
+	soundId = 0;
+
+	while (1) {
+		nextSound = diMUSEGetNextSound(soundId);
+		soundId = nextSound;
+
+		if (!nextSound)
+			break;
+
+		if (diMUSEGetParam(nextSound, DIMUSE_P_SND_HAS_STREAM) && diMUSEGetParam(soundId, DIMUSE_P_STREAM_BUFID) == DIMUSE_BUFFER_MUSIC) {
+			if (soundId)
+				return;
+			break;
+		}
+	}
+
+	if (_curMusicSeq)
+		scriptSetSequence(0);
+
+	flushTracks();
+}
+
+void IMuseDigital::scriptSetState(int soundId) {
+	setComiMusicState(soundId);
+}
+
+void IMuseDigital::scriptSetSequence(int soundId) {
+	setComiMusicSequence(soundId);
+}
+
+void IMuseDigital::scriptSetCuePoint(int cueId) {
+}
+
+int IMuseDigital::scriptSetAttribute(int attrIndex, int attrVal) {
+	return 0;
+}
+
+int IMuseDigital::scriptTriggerCallback(char *marker) {
+	if (marker[0] != '_') {
+		debug(5, "IMuseDigital::scriptTriggerCallback(): got marker != '_end', callback ignored");
+		return -1;
+	}
+	_stopSequenceFlag = 1;
+	return 0;
+}
+
+
+void IMuseDigital::setComiMusicState(int stateId) {
+	int l, num = -1;
+
+	if (stateId == 0)
+		stateId = 1000;
+
+	for (l = 0; _comiStateMusicTable[l].soundId != -1; l++) {
+		if ((_comiStateMusicTable[l].soundId == stateId)) {
+			debug(5, "IMuseDigital::setComiMusicState(): Set music state: %s, %s", _comiStateMusicTable[l].name, _comiStateMusicTable[l].filename);
+			num = l;
+			break;
+		}
+	}
+
+	if (num == -1)
+		return;
+
+	if (_curMusicState == num)
+		return;
+
+	if (_curMusicSeq == 0) {
+		if (num == 0)
+			playComiMusic(nullptr, &_comiStateMusicTable[0], num, false);
+		else
+			playComiMusic(_comiStateMusicTable[num].name, &_comiStateMusicTable[num], num, false);
+	}
+
+	_curMusicState = num;
+}
+
+void IMuseDigital::setComiMusicSequence(int seqId) {
+	int l, num = -1;
+
+	if (seqId == 0)
+		seqId = 2000;
+
+	for (l = 0; _comiSeqMusicTable[l].soundId != -1; l++) {
+		if ((_comiSeqMusicTable[l].soundId == seqId)) {
+			debug(5, "IMuseDigital::setComiMusicSequence(): Set music sequence: %s, %s", _comiSeqMusicTable[l].name, _comiSeqMusicTable[l].filename);
+			num = l;
+			break;
+		}
+	}
+
+	if (num == -1)
+		return;
+
+	if (_curMusicSeq == num)
+		return;
+
+	if (num != 0) {
+		if (_curMusicSeq && ((_comiSeqMusicTable[_curMusicSeq].transitionType == 4)
+			|| (_comiSeqMusicTable[_curMusicSeq].transitionType == 6))) {
+			_nextSeqToPlay = num;
+			return;
+		} else {
+			playComiMusic(_comiSeqMusicTable[num].name, &_comiSeqMusicTable[num], 0, true);
+			_nextSeqToPlay = 0;
+		}
+	} else {
+		if (_nextSeqToPlay != 0) {
+			playComiMusic(_comiSeqMusicTable[_nextSeqToPlay].name, &_comiSeqMusicTable[_nextSeqToPlay], 0, true);
+			num = _nextSeqToPlay;
+			_nextSeqToPlay = 0;
+		} else {
+			if (_curMusicState != 0) {
+				playComiMusic(_comiStateMusicTable[_curMusicState].name, &_comiStateMusicTable[_curMusicState], _curMusicState, true);
+			} else {
+				playComiMusic(nullptr, &_comiStateMusicTable[0], _curMusicState, true);
+			}
+			num = 0;
+		}
+	}
+
+	_curMusicSeq = num;
+}
+
+void IMuseDigital::playComiMusic(const char *songName, const imuseComiTable *table, int attribPos, bool sequence) {
+	int hookId = 0;
+	int fadeDelay = 0;
+
+	// This flag is not set in the original,
+	// but since we're not using DirectSound and this is pretty much timing related
+	// please see IMuseDigital::waveOutWrite() for more context...
+	Common::StackLock lock(*_mutex);
+	_waveOutXorTrigger = 1;
+
+	if ((songName != nullptr) && (attribPos != 0)) {
+		if (table->attribPos != 0)
+			attribPos = table->attribPos;
+		hookId = _attributes[COMI_STATE_OFFSET + attribPos];
+
+		if (table->hookId != 0) {
+			if ((hookId != 0) && (table->hookId > 1)) {
+				_attributes[COMI_STATE_OFFSET + attribPos] = 2;
+			} else {
+				_attributes[COMI_STATE_OFFSET + attribPos] = hookId + 1;
+				if (table->hookId < hookId + 1)
+					_attributes[COMI_STATE_OFFSET + attribPos] = 1;
+			}
+		}
+	}
+
+	int nextSoundId = 0;
+	while (1) {
+		nextSoundId = diMUSEGetNextSound(nextSoundId);
+		if (!nextSoundId)
+			break;
+
+		// If a sound is found (and its stream is active), fade it out if it's a music track
+		if (diMUSEGetParam(nextSoundId, DIMUSE_P_GROUP) == DIMUSE_GROUP_MUSICEFF && !diMUSEGetParam(nextSoundId, DIMUSE_P_SND_HAS_STREAM))
+			diMUSEFadeParam(nextSoundId, DIMUSE_P_VOLUME, 0, 120);
+	}
+
+	int oldSoundId = 0;
+	nextSoundId = 0;
+	while (1) {
+		nextSoundId = diMUSEGetNextSound(nextSoundId);
+		if (!nextSoundId)
+			break;
+
+		if (diMUSEGetParam(nextSoundId, DIMUSE_P_SND_HAS_STREAM) && (diMUSEGetParam(nextSoundId, DIMUSE_P_STREAM_BUFID) == DIMUSE_BUFFER_MUSIC)) {
+			oldSoundId = nextSoundId;
+			break;
+		}
+	}
+
+	if (!songName) {
+		if (oldSoundId)
+			diMUSEFadeParam(oldSoundId, DIMUSE_P_VOLUME, 0, 120);
+		return;
+	}
+
+	switch (table->transitionType) {
+	case 0:
+		debug(5, "IMuseDigital::playComiMusic(): NULL transition, ignored");
+		break;
+	case 1:
+		if (_filesHandler->openSound(table->soundId))
+			return;
+
+		if (table->soundId) {
+			if (diMUSEStartSound(table->soundId, 126))
+				debug(5, "IMuseDigital::playComiMusic(): transition 1, failed to start the sound (%d)", table->soundId);
+			diMUSESetParam(table->soundId, DIMUSE_P_VOLUME, 1);
+			diMUSEFadeParam(table->soundId, DIMUSE_P_VOLUME, 127, 120);
+			_filesHandler->closeSound(table->soundId);
+			diMUSESetParam(table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+		} else {
+			debug(5, "IMuseDigital::playComiMusic(): transition 1, empty soundId, ignored");
+		}
+		break;
+	case 2:
+	case 3:
+	case 4:
+	case 12:
+		if (_filesHandler->openSound(table->soundId))
+			return;
+
+		if (table->filename[0] == 0 || table->soundId == 0) {
+			if (oldSoundId)
+				diMUSEFadeParam(oldSoundId, DIMUSE_P_VOLUME, 0, 60);
+			break;
+		}
+
+		if (table->transitionType == 4) {
+			_stopSequenceFlag = 0;
+			diMUSESetTrigger(table->soundId, MKTAG('_', 'e', 'n', 'd'), DIMUSE_C_SCRIPT_CALLBACK);
+		}
+
+		if (oldSoundId) {
+			fadeDelay = table->fadeOutDelay;
+			if (!fadeDelay)
+				fadeDelay = 1000;
+			else
+				fadeDelay = (fadeDelay * 100) / 6; // Set dimuse_table fade out time to millisecond scale
+
+			if (table->transitionType == 2) {
+				diMUSESwitchStream(oldSoundId, table->soundId, fadeDelay, 0, 0);
+				diMUSESetParam(table->soundId, DIMUSE_P_VOLUME, 127);
+				diMUSESetParam(table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+				diMUSESetHook(table->soundId, table->hookId);
+				diMUSEProcessStreams();
+			} else if (oldSoundId != table->soundId) {
+				if ((!sequence) && (table->attribPos != 0) &&
+					(table->attribPos == _comiStateMusicTable[_curMusicState].attribPos)) {
+
+					debug(5, "IMuseDigital::playComiMusic(): Starting new sound (%s) with same attribute as old sound (%s)",
+						table->name, _comiStateMusicTable[_curMusicState].name);
+
+					diMUSESwitchStream(oldSoundId, table->soundId, fadeDelay, 0, 1);
+					diMUSESetParam(table->soundId, DIMUSE_P_VOLUME, 127);
+					diMUSESetParam(table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+					diMUSEProcessStreams();
+				} else {
+					switch (table->transitionType) {
+					case 12:
+						diMUSESetHook(oldSoundId, table->hookId);
+						diMUSESetTrigger(oldSoundId, MKTAG('e', 'x', 'i', 't'), DIMUSE_C_SWITCH_STREAM, oldSoundId, table->soundId, fadeDelay, 1, 0);
+						diMUSESetTrigger(oldSoundId, MKTAG('e', 'x', 'i', 't'), DIMUSE_C_SET_PARAM, table->soundId, DIMUSE_P_VOLUME, 127);
+						diMUSESetTrigger(oldSoundId, MKTAG('e', 'x', 'i', 't'), DIMUSE_C_SET_PARAM, table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+						diMUSESetTrigger(oldSoundId, MKTAG('e', 'x', 'i', 't'), DIMUSE_C_SET_HOOK, table->soundId, hookId);
+						diMUSEProcessStreams();
+						break;
+					default:
+						diMUSESwitchStream(oldSoundId, table->soundId, fadeDelay, 0, 0);
+						diMUSESetParam(table->soundId, DIMUSE_P_VOLUME, 127);
+						diMUSESetParam(table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+						diMUSESetHook(table->soundId, hookId);
+						diMUSEProcessStreams();
+						break;
+					}
+				}
+			}
+		} else {
+			if (diMUSEStartStream(table->soundId, 126, DIMUSE_BUFFER_MUSIC))
+				debug(5, "IMuseDigital::playComiMusic(): failed to start the stream for sound %d", table->soundId);
+			diMUSESetParam(table->soundId, DIMUSE_P_VOLUME, 127);
+			diMUSESetParam(table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+			diMUSESetHook(table->soundId, hookId);
+		}
+		_filesHandler->closeSound(table->soundId);
+		diMUSESetParam(table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+		break;
+	case 5:
+		debug(5, "IMuseDigital::playComiMusic(): no-op transition type (5), ignored");
+		break;
+	case 6:
+		_stopSequenceFlag = 0;
+		diMUSESetTrigger(DIMUSE_SMUSH_SOUNDID + DIMUSE_BUFFER_MUSIC, MKTAG('_', 'e', 'n', 'd'), DIMUSE_C_SCRIPT_CALLBACK);
+		break;
+	case 7:
+		if (oldSoundId)
+			diMUSEFadeParam(oldSoundId, DIMUSE_P_VOLUME, 0, 60);
+		break;
+	case 8:
+		if (oldSoundId)
+			diMUSESetHook(oldSoundId, table->hookId);
+		break;
+	case 9:
+		if (oldSoundId)
+			diMUSESetHook(oldSoundId, table->hookId);
+		_stopSequenceFlag = 0;
+		diMUSESetTrigger(oldSoundId, MKTAG('_', 'e', 'n', 'd'), DIMUSE_C_SCRIPT_CALLBACK);
+		break;
+	default:
+		debug(5, "IMuseDigital::playComiMusic(): bogus transition type, ignored");
+		break;
+	}
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_sndmgr.cpp b/engines/grim/imuse/dimuse_sndmgr.cpp
new file mode 100644
index 00000000000..51384537813
--- /dev/null
+++ b/engines/grim/imuse/dimuse_sndmgr.cpp
@@ -0,0 +1,275 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+
+#include "common/scummsys.h"
+
+#include "audio/audiostream.h"
+#include "audio/decoders/flac.h"
+#include "audio/decoders/voc.h"
+#include "audio/decoders/vorbis.h"
+#include "audio/decoders/mp3.h"
+
+#include "engines/grim/imuse/dimuse_bndmgr.h"
+#include "engines/grim/imuse/dimuse_codecs.h"
+#include "engines/grim/imuse/dimuse_sndmgr.h"
+
+namespace Grim {
+
+ImuseDigiSndMgr::ImuseDigiSndMgr() {
+	for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
+		memset(&_sounds[l], 0, sizeof(SoundDesc));
+	}
+	_disk = 0;
+	_cacheBundleDir = new BundleDirCache();
+	assert(_cacheBundleDir);
+	BundleCodecs::initializeImcTables();
+}
+
+ImuseDigiSndMgr::~ImuseDigiSndMgr() {
+	for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
+		closeSound(&_sounds[l]);
+	}
+
+	delete _cacheBundleDir;
+	BundleCodecs::releaseImcTables();
+}
+
+ImuseDigiSndMgr::SoundDesc *ImuseDigiSndMgr::allocSlot() {
+	for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
+		if (!_sounds[l].inUse) {
+			_sounds[l].inUse = true;
+			_sounds[l].scheduledForDealloc = false;
+			return &_sounds[l];
+		}
+	}
+
+	return nullptr;
+}
+
+bool ImuseDigiSndMgr::openMusicBundle(SoundDesc *sound, int &disk) {
+	bool result = false;
+	bool compressed = false;
+
+	sound->bundle = new BundleMgr(_cacheBundleDir);
+	assert(sound->bundle);
+
+	char musicfile[20];
+	// TODO
+	// if (disk == -1)
+	// 	disk = _vm->VAR(_vm->VAR_CURRENTDISK);
+	Common::sprintf_s(musicfile, "musdisk%d.bun", disk);
+//	if (_disk != _vm->VAR(_vm->VAR_CURRENTDISK)) {
+//		_vm->_DiMUSE_v1->parseScriptCmds(0x1000, 0, 0, 0, 0, 0, 0, 0);
+//		_vm->_DiMUSE_v1->parseScriptCmds(0x2000, 0, 0, 0, 0, 0, 0, 0);
+//		_vm->_DiMUSE_v1->stopAllSounds();
+//		sound->bundle->closeFile();
+//	}
+
+	result = sound->bundle->open(musicfile, compressed);
+
+	// FIXME: Shouldn't we only set _disk if result == true?
+	// TODO
+	// _disk = (byte)_vm->VAR(_vm->VAR_CURRENTDISK);
+
+	// TODO
+	// _vm->VAR(_vm->VAR_MUSIC_BUNDLE_LOADED) = result ? 1 : 0;
+
+	return result;
+}
+
+bool ImuseDigiSndMgr::openVoiceBundle(SoundDesc *sound, int &disk) {
+	bool result = false;
+	bool compressed = false;
+
+	sound->bundle = new BundleMgr(_cacheBundleDir);
+	assert(sound->bundle);
+
+	char voxfile[20];
+	// TODO
+	// if (disk == -1)
+	// 	disk = _vm->VAR(_vm->VAR_CURRENTDISK);
+	Common::sprintf_s(voxfile, "voxdisk%d.bun", disk);
+//	if (_disk != _vm->VAR(_vm->VAR_CURRENTDISK)) {
+//		_vm->_DiMUSE_v1->parseScriptCmds(0x1000, 0, 0, 0, 0, 0, 0, 0);
+//		_vm->_DiMUSE_v1->parseScriptCmds(0x2000, 0, 0, 0, 0, 0, 0, 0);
+//		_vm->_DiMUSE_v1->stopAllSounds();
+//		sound->bundle->closeFile();
+//	}
+
+	result = sound->bundle->open(voxfile, compressed);
+
+	// FIXME: Shouldn't we only set _disk if result == true?
+	// TODO
+	// _disk = (byte)_vm->VAR(_vm->VAR_CURRENTDISK);
+
+	// TODO
+	// _vm->VAR(_vm->VAR_VOICE_BUNDLE_LOADED) = result ? 1 : 0;
+
+	return result;
+}
+
+ImuseDigiSndMgr::SoundDesc *ImuseDigiSndMgr::openSound(int32 soundId, const char *soundName, int soundType, int volGroupId, int disk) {
+	assert(soundId >= 0);
+	assert(soundType);
+
+	SoundDesc *sound = allocSlot();
+	if (!sound) {
+		error("ImuseDigiSndMgr::openSound() can't alloc free sound slot");
+	}
+
+	const bool header_outside = true;
+	bool result = false;
+	byte *ptr = nullptr;
+
+	switch (soundType) {
+	case IMUSE_RESOURCE:
+		assert(soundName[0] == 0);	// Paranoia check
+
+		// TODO
+		// _vm->_res->lock(rtSound, soundId);
+		// ptr = _vm->getResourceAddress(rtSound, soundId);
+		// if (ptr == nullptr) {
+		// 	closeSound(sound);
+		// 	return nullptr;
+		// }
+		// sound->resPtr = ptr;
+		// sound->resSize = _vm->getResourceSize(rtSound, soundId) - 8;
+		break;
+	case IMUSE_BUNDLE:
+		if (volGroupId == IMUSE_VOLGRP_VOICE)
+			result = openVoiceBundle(sound, disk);
+		else if (volGroupId == IMUSE_VOLGRP_MUSIC)
+			result = openMusicBundle(sound, disk);
+		else
+			error("ImuseDigiSndMgr::openSound() Don't know how load sound: %d", soundId);
+		if (!result) {
+			closeSound(sound);
+			return nullptr;
+		}
+
+		if (soundName[0] != 0) {
+			if (sound->bundle->readFile(soundName, 0x2000, &ptr, header_outside) == 0 || ptr == nullptr) {
+				closeSound(sound);
+				free(ptr);
+				return nullptr;
+			}
+		}
+
+		sound->resPtr = nullptr;
+		break;
+	default:
+		error("ImuseDigiSndMgr::openSound() Unknown soundType %d (trying to load sound %d)", soundType, soundId);
+	}
+
+	Common::strlcpy(sound->name, soundName, sizeof(sound->name));
+	sound->soundId = soundId;
+
+	if (soundType == IMUSE_BUNDLE) {
+		free(ptr);
+	}
+	return sound;
+}
+
+void ImuseDigiSndMgr::closeSound(SoundDesc *soundDesc) {
+	// Check if there's an actual sound to close...
+	if (!checkForProperHandle(soundDesc))
+		return;
+
+	if (soundDesc->resPtr) {
+		bool found = false;
+		for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
+			if ((_sounds[l].soundId == soundDesc->soundId) && (&_sounds[l] != soundDesc))
+				found = true;
+		}
+		// TODO
+		// if (!found)
+		// 	_vm->_res->unlock(rtSound, soundDesc->soundId);
+	}
+
+	delete soundDesc->bundle;
+
+	memset(soundDesc, 0, sizeof(SoundDesc));
+}
+
+ImuseDigiSndMgr::SoundDesc *ImuseDigiSndMgr::findSoundById(int soundId) {
+	SoundDesc *soundDesc = nullptr;
+	for (int i = 0; i < MAX_IMUSE_SOUNDS; i++) {
+		if (_sounds[i].soundId == soundId) {
+			soundDesc = &_sounds[i];
+			break;
+		}
+	}
+	return soundDesc;
+}
+
+ImuseDigiSndMgr::SoundDesc *ImuseDigiSndMgr::getSounds() {
+	return _sounds;
+}
+
+void ImuseDigiSndMgr::scheduleSoundForDeallocation(int soundId) {
+	SoundDesc *soundDesc = nullptr;
+	for (int i = 0; i < MAX_IMUSE_SOUNDS; i++) {
+		if (_sounds[i].soundId == soundId) {
+			soundDesc = &_sounds[i];
+		}
+	}
+
+	// Check if there's an actual sound to deallocate...
+	if (!checkForProperHandle(soundDesc))
+		return;
+
+	soundDesc->scheduledForDealloc = true;
+}
+
+void ImuseDigiSndMgr::closeSoundById(int soundId) {
+	SoundDesc *soundDesc = nullptr;
+	for (int i = 0; i < MAX_IMUSE_SOUNDS; i++) {
+		if (_sounds[i].soundId == soundId) {
+			soundDesc = &_sounds[i];
+		}
+	}
+
+	if (soundDesc) {
+		assert(checkForProperHandle(soundDesc));
+
+		// TODO
+		// if (soundDesc->resPtr) {
+		// 	_vm->_res->unlock(rtSound, soundDesc->soundId);
+		// }
+
+		delete soundDesc->bundle;
+
+		memset(soundDesc, 0, sizeof(SoundDesc));
+	}
+}
+
+bool ImuseDigiSndMgr::checkForProperHandle(SoundDesc *soundDesc) {
+	if (!soundDesc)
+		return false;
+	for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
+		if (soundDesc == &_sounds[l])
+			return true;
+	}
+	return false;
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_sndmgr.h b/engines/grim/imuse/dimuse_sndmgr.h
new file mode 100644
index 00000000000..72703118e81
--- /dev/null
+++ b/engines/grim/imuse/dimuse_sndmgr.h
@@ -0,0 +1,95 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef GRIM_IMUSE_SNDMGR_H
+#define GRIM_IMUSE_SNDMGR_H
+
+
+#include "common/scummsys.h"
+
+namespace Audio {
+class SeekableAudioStream;
+}
+
+namespace Common {
+class SeekableReadStream;
+}
+
+namespace Grim {
+
+class BundleMgr;
+class BundleDirCache;
+
+class ImuseDigiSndMgr {
+public:
+
+#define MAX_IMUSE_SOUNDS 16
+
+#define IMUSE_RESOURCE 1
+#define IMUSE_BUNDLE 2
+
+#define IMUSE_VOLGRP_VOICE 1
+#define IMUSE_VOLGRP_SFX 2
+#define IMUSE_VOLGRP_MUSIC 3
+
+public:
+
+	struct SoundDesc {
+		bool inUse;
+		bool scheduledForDealloc;
+
+		byte *resPtr;
+		int resSize;
+		int resCurOffset;
+		char name[15];
+		int16 soundId;
+		BundleMgr *bundle;
+	};
+
+private:
+
+	SoundDesc _sounds[MAX_IMUSE_SOUNDS];
+	bool checkForProperHandle(SoundDesc *soundDesc);
+	SoundDesc *allocSlot();
+
+	byte _disk;
+	BundleDirCache *_cacheBundleDir;
+
+	bool openMusicBundle(SoundDesc *sound, int &disk);
+	bool openVoiceBundle(SoundDesc *sound, int &disk);
+
+public:
+
+	ImuseDigiSndMgr();
+	~ImuseDigiSndMgr();
+
+	SoundDesc *openSound(int32 soundId, const char *soundName, int soundType, int volGroupId, int disk);
+	void closeSound(SoundDesc *soundDesc);
+	void closeSoundById(int soundId);
+	SoundDesc *findSoundById(int soundId);
+	SoundDesc *getSounds();
+	void scheduleSoundForDeallocation(int soundId);
+
+};
+
+} // End of namespace Grim
+
+#endif
diff --git a/engines/grim/imuse/dimuse_streamer.cpp b/engines/grim/imuse/dimuse_streamer.cpp
new file mode 100644
index 00000000000..1ad808cd3a0
--- /dev/null
+++ b/engines/grim/imuse/dimuse_streamer.cpp
@@ -0,0 +1,359 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_engine.h"
+
+namespace Grim {
+
+int IMuseDigital::streamerInit() {
+	for (int l = 0; l < DIMUSE_MAX_STREAMS; l++) {
+		_streams[l].soundId = 0;
+	}
+	_lastStreamLoaded = nullptr;
+	return 0;
+}
+
+IMuseDigiStream *IMuseDigital::streamerAllocateSound(int soundId, int bufId, int32 maxRead) {
+	IMuseDigiSndBuffer *bufInfoPtr = _filesHandler->getBufInfo(bufId);
+	if (!bufInfoPtr) {
+		debug(5, "IMuseDigital::streamerAlloc(): ERROR: couldn't get buffer info");
+		return nullptr;
+	}
+
+	if ((bufInfoPtr->bufSize / 4) <= maxRead) {
+		debug(5, "IMuseDigital::streamerAlloc(): ERROR: maxRead too big for buffer");
+		return nullptr;
+	}
+
+	for (int l = 0; l < DIMUSE_MAX_STREAMS; l++) {
+		if (_streams[l].soundId && _streams[l].bufId == bufId) {
+			debug(5, "IMuseDigital::streamerAlloc(): ERROR: stream bufId %d already in use", bufId);
+			return nullptr;
+		}
+	}
+
+	for (int l = 0; l < DIMUSE_MAX_STREAMS; l++) {
+		if (!_streams[l].soundId) {
+			_streams[l].endOffset = _filesHandler->seek(soundId, 0, SEEK_END, bufId);
+			_streams[l].curOffset = 0;
+			_streams[l].soundId = soundId;
+			_streams[l].bufId = bufId;
+			_streams[l].buf = bufInfoPtr->buffer;
+			_streams[l].bufFreeSize = bufInfoPtr->bufSize - maxRead - 4;
+			_streams[l].loadSize = bufInfoPtr->loadSize;
+			_streams[l].criticalSize = bufInfoPtr->criticalSize;
+			_streams[l].maxRead = maxRead;
+			_streams[l].loadIndex = 0;
+			_streams[l].readIndex = 0;
+			_streams[l].paused = 0;
+			return &_streams[l];
+		}
+	}
+	debug(5, "IMuseDigital::streamerAlloc(): ERROR: no spare streams");
+	return nullptr;
+}
+
+int IMuseDigital::streamerClearSoundInStream(IMuseDigiStream *streamPtr) {
+	streamPtr->soundId = 0;
+	if (_lastStreamLoaded == streamPtr) {
+		_lastStreamLoaded = 0;
+	}
+	return 0;
+}
+
+int IMuseDigital::streamerProcessStreams() {
+	dispatchPredictFirstStream();
+
+	IMuseDigiStream *stream1 = nullptr;
+	IMuseDigiStream *stream2 = nullptr;
+
+	for (int l = 0; l < DIMUSE_MAX_STREAMS; l++) {
+		if ((_streams[l].soundId) && (!_streams[l].paused)) {
+			if (stream2) {
+				if (stream1) {
+					debug(5, "IMuseDigital::streamerProcessStreams(): WARNING: three streams in use");
+				} else {
+					stream1 = &_streams[l];
+				}
+			} else {
+				stream2 = &_streams[l];
+			}
+		}
+	}
+
+	if (!stream1) {
+		if (stream2)
+			streamerFetchData(stream2);
+		return 0;
+	}
+
+	if (!stream2) {
+		if (stream1)
+			streamerFetchData(stream1);
+		return 0;
+	}
+
+	// Check if we've reached or surpassed criticalSize
+	bool critical1 = (streamerGetFreeBufferAmount(stream1) >= stream1->criticalSize);
+	bool critical2 = (streamerGetFreeBufferAmount(stream2) >= stream2->criticalSize);
+
+	if (!critical1) {
+		if (!critical2) {
+			if (stream1 == _lastStreamLoaded) {
+				streamerFetchData(stream1);
+				streamerFetchData(stream2);
+				return 0;
+			} else {
+				streamerFetchData(stream2);
+				streamerFetchData(stream1);
+				return 0;
+			}
+		} else {
+			streamerFetchData(stream1);
+			return 0;
+		}
+	}
+
+	if (!critical2) {
+		streamerFetchData(stream2);
+		return 0;
+	} else {
+		if (stream1 == _lastStreamLoaded) {
+			streamerFetchData(stream1);
+		} else {
+			streamerFetchData(stream2);
+		}
+		return 0;
+	}
+}
+
+uint8 *IMuseDigital::streamerGetStreamBuffer(IMuseDigiStream *streamPtr, int size) {
+	if (size > streamerGetFreeBufferAmount(streamPtr) || streamPtr->maxRead < size)
+		return 0;
+
+	if (size > streamPtr->bufFreeSize - streamPtr->readIndex) {
+		memcpy(&streamPtr->buf[streamPtr->bufFreeSize],
+			streamPtr->buf,
+			size - streamPtr->bufFreeSize + streamPtr->readIndex + 4);
+	}
+
+	int32 readIndex_tmp = streamPtr->readIndex;
+	uint8 *ptr = &streamPtr->buf[readIndex_tmp];
+	streamPtr->readIndex = readIndex_tmp + size;
+	if (streamPtr->bufFreeSize <= readIndex_tmp + size)
+		streamPtr->readIndex = readIndex_tmp + size - streamPtr->bufFreeSize;
+
+	return ptr;
+}
+
+uint8 *IMuseDigital::streamerGetStreamBufferAtOffset(IMuseDigiStream *streamPtr, int32 offset, int size) {
+	if (offset + size > streamerGetFreeBufferAmount(streamPtr) || streamPtr->maxRead < size)
+		return 0;
+
+	int32 offsetReadIndex = offset + streamPtr->readIndex;
+	if (offsetReadIndex >= streamPtr->bufFreeSize) {
+		offsetReadIndex -= streamPtr->bufFreeSize;
+	}
+
+	if (size > streamPtr->bufFreeSize - offsetReadIndex) {
+		memcpy(&streamPtr->buf[streamPtr->bufFreeSize], streamPtr->buf, size + offsetReadIndex - streamPtr->bufFreeSize);
+	}
+
+	return &streamPtr->buf[offsetReadIndex];
+}
+
+int IMuseDigital::streamerSetReadIndex(IMuseDigiStream *streamPtr, int offset) {
+	_streamerBailFlag = 1;
+	if (offset > streamerGetFreeBufferAmount(streamPtr))
+		return -1;
+
+	streamPtr->readIndex += offset;
+	if (streamPtr->readIndex >= streamPtr->bufFreeSize) {
+		streamPtr->readIndex -= streamPtr->bufFreeSize;
+	}
+	return 0;
+}
+
+int IMuseDigital::streamerSetLoadIndex(IMuseDigiStream *streamPtr, int offset) {
+	_streamerBailFlag = 1;
+	if (offset > streamerGetFreeBufferAmount(streamPtr))
+		return -1;
+
+	streamPtr->loadIndex = streamPtr->readIndex + offset;
+	if (streamPtr->loadIndex >= streamPtr->bufFreeSize) {
+		streamPtr->loadIndex -= streamPtr->bufFreeSize;
+	}
+	return 0;
+}
+
+int IMuseDigital::streamerGetFreeBufferAmount(IMuseDigiStream *streamPtr) {
+	int32 freeBufferSize = streamPtr->loadIndex - streamPtr->readIndex;
+	if (freeBufferSize < 0)
+		freeBufferSize += streamPtr->bufFreeSize;
+	return freeBufferSize;
+}
+
+int IMuseDigital::streamerSetSoundToStreamFromOffset(IMuseDigiStream *streamPtr, int soundId, int32 offset) {
+	_streamerBailFlag = 1;
+	streamPtr->soundId = soundId;
+	streamPtr->curOffset = offset;
+	streamPtr->endOffset = 0;
+	streamPtr->paused = 0;
+	if (_lastStreamLoaded == streamPtr) {
+		_lastStreamLoaded = nullptr;
+	}
+	return 0;
+}
+
+void IMuseDigital::streamerQueryStream(IMuseDigiStream *streamPtr, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
+	dispatchPredictFirstStream();
+
+	bufSize = streamPtr->bufFreeSize;
+	criticalSize = streamPtr->criticalSize;
+	freeSpace = streamerGetFreeBufferAmount(streamPtr);
+	paused = streamPtr->paused;
+}
+
+int IMuseDigital::streamerFeedStream(IMuseDigiStream *streamPtr, uint8 *srcBuf, int32 sizeToFeed, int paused) {
+	int32 size = streamPtr->readIndex - streamPtr->loadIndex;
+	if (size <= 0)
+		size += streamPtr->bufFreeSize;
+	if (sizeToFeed > (size - 4)) {
+		// Don't worry, judging from the intro of The Dig, this is totally expected
+		// to happen, and when it does, the output matches the EXE behavior
+		debug(5, "IMuseDigital::streamerFeedStream(): WARNING: buffer overflow");
+		_streamerBailFlag = 1;
+
+		int32 newTentativeSize = sizeToFeed - (size - 4) - (sizeToFeed - (size - 4)) % 12 + 12;
+		size = streamPtr->loadIndex - streamPtr->readIndex;
+		if (size < 0)
+			size += streamPtr->bufFreeSize;
+		if (size >= newTentativeSize) {
+			streamPtr->readIndex = newTentativeSize + streamPtr->readIndex;
+			if (streamPtr->bufFreeSize <= streamPtr->readIndex)
+				streamPtr->readIndex -= streamPtr->bufFreeSize;
+		}
+	}
+
+	if (sizeToFeed > 0) {
+		do {
+			size = streamPtr->bufFreeSize - streamPtr->loadIndex;
+			if (size >= sizeToFeed) {
+				size = sizeToFeed;
+			}
+			sizeToFeed -= size;
+			memcpy(&streamPtr->buf[streamPtr->loadIndex], srcBuf, size);
+			srcBuf += size;
+
+			int val = size + streamPtr->loadIndex;
+			streamPtr->curOffset += size;
+			streamPtr->loadIndex += size;
+			if (val >= streamPtr->bufFreeSize) {
+				streamPtr->loadIndex = val - streamPtr->bufFreeSize;
+			}
+		} while (sizeToFeed > 0);
+	}
+
+	streamPtr->paused = paused;
+	return 0;
+}
+
+int IMuseDigital::streamerFetchData(IMuseDigiStream *streamPtr) {
+	if (streamPtr->endOffset == 0) {
+		streamPtr->endOffset = _filesHandler->seek(streamPtr->soundId, 0, SEEK_END, streamPtr->bufId);
+	}
+
+	int32 size = streamPtr->readIndex - streamPtr->loadIndex;
+	if (size <= 0)
+		size += streamPtr->bufFreeSize;
+
+	int32 loadSize = streamPtr->loadSize;
+	int32 remainingSize = streamPtr->endOffset - streamPtr->curOffset;
+
+	if (loadSize >= size - 4) {
+		loadSize = size - 4;
+	}
+
+	if (loadSize >= remainingSize) {
+		loadSize = remainingSize;
+	}
+
+	if (remainingSize <= 0) {
+		streamPtr->paused = 1;
+
+		// Pad the buffer
+		streamPtr->buf[streamPtr->loadIndex] = 127;
+		streamPtr->loadIndex++;
+		streamPtr->buf[streamPtr->loadIndex] = 127;
+		streamPtr->loadIndex++;
+		streamPtr->buf[streamPtr->loadIndex] = 127;
+		streamPtr->loadIndex++;
+		streamPtr->buf[streamPtr->loadIndex] = 127;
+		streamPtr->loadIndex++;
+	}
+
+	int32 actualAmount;
+	int32 requestedAmount;
+
+	while (1) {
+		if (loadSize <= 0)
+			return 0;
+
+		requestedAmount = streamPtr->bufFreeSize - streamPtr->loadIndex;
+		if (requestedAmount >= loadSize) {
+			requestedAmount = loadSize;
+		}
+
+		if (_filesHandler->seek(streamPtr->soundId, streamPtr->curOffset, SEEK_SET, streamPtr->bufId) != streamPtr->curOffset) {
+			debug(5, "IMuseDigital::streamerFetchData(): ERROR: invalid seek in streamer (%d), pausing stream...", streamPtr->curOffset);
+			streamPtr->paused = 1;
+			return 0;
+		}
+
+		_streamerBailFlag = 0;
+
+		_mutex->lock();
+		actualAmount = _filesHandler->read(streamPtr->soundId, &streamPtr->buf[streamPtr->loadIndex], requestedAmount, streamPtr->bufId);
+		_mutex->unlock();
+
+		if (_streamerBailFlag)
+			return 0;
+
+		loadSize -= actualAmount;
+		streamPtr->curOffset += actualAmount;
+		_lastStreamLoaded = streamPtr;
+
+		int32 newLoadIndex = actualAmount + streamPtr->loadIndex;
+		streamPtr->loadIndex = newLoadIndex;
+		if (newLoadIndex >= streamPtr->bufFreeSize) {
+			streamPtr->loadIndex = newLoadIndex - streamPtr->bufFreeSize;
+		}
+
+		if (actualAmount != requestedAmount)
+			break;
+	}
+
+	debug(5, "IMuseDigital::streamerFetchData(): ERROR: unable to load the correct amount of data (req=%d, act=%d)", requestedAmount, actualAmount);
+	_lastStreamLoaded = nullptr;
+	return 0;
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_tables.cpp b/engines/grim/imuse/dimuse_tables.cpp
new file mode 100644
index 00000000000..14e990e67bd
--- /dev/null
+++ b/engines/grim/imuse/dimuse_tables.cpp
@@ -0,0 +1,216 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_tables.h"
+
+namespace Grim {
+
+const imuseComiTable _comiStateMusicTable[] = {
+	{0, 1000, "STATE_NULL",         0, 0,    0, ""            }, /* 00 */
+	{0, 1001, "stateNoChange",      0, 0,    0, ""            }, /* 01 */
+	{3, 1098, "stateCredits1",      0, 0,   60, "1098-C~1.IMX"}, /* 02 */
+	{3, 1099, "stateMenu",          0, 0,   60, "1099-M~1.IMX"}, /* 03 */
+	{3, 1100, "stateHold1",         4, 0,   60, "1100-H~1.IMX"}, /* 04 */
+	{3, 1101, "stateWaterline1",    4, 0,   60, "1101-W~1.IMX"}, /* 05 */
+	{3, 1102, "stateHold2",         6, 1,   60, "1102-H~1.IMX"}, /* 06 */
+	{3, 1103, "stateWaterline2",    6, 0,   60, "1103-W~1.IMX"}, /* 07 */
+	{3, 1104, "stateCannon",        0, 0,   60, "1104-C~1.IMX"}, /* 08 */
+	{3, 1105, "stateTreasure",      0, 0,   60, "1105-T~1.IMX"}, /* 09 */
+	{3, 1200, "stateFortBase",     10, 1,   60, "1200-F~1.IMX"}, /* 10 */
+	{3, 1201, "statePreFort",      10, 1,   60, "1201-P~1.IMX"}, /* 11 */
+	{3, 1202, "statePreVooOut",    12, 0,   60, "1202-P~1.IMX"}, /* 12 */
+	{3, 1203, "statePreVooIn",     12, 0,   60, "1203-P~1.IMX"}, /* 13 */
+	{3, 1204, "statePreVooLady",   12, 0,   60, "1204-P~1.IMX"}, /* 14 */
+	{3, 1205, "stateVoodooOut",     0, 0,   60, "1205-V~1.IMX"}, /* 15 */
+	{3, 1210, "stateVoodooIn",      0, 0,   60, "1210-V~1.IMX"}, /* 16 */
+	{12,1212, "stateVoodooInAlt",   0, 1,   42, "1210-V~1.IMX"}, /* 17 */
+	{3, 1215, "stateVoodooLady",    0, 0,   60, "1215-V~1.IMX"}, /* 18 */
+	{3, 1219, "statePrePlundermap", 0, 0,   60, "1219-P~1.IMX"}, /* 19 */
+	{3, 1220, "statePlundermap",    0, 0,   60, "1220-P~1.IMX"}, /* 20 */
+	{3, 1222, "statePreCabana",     0, 0,   60, "1222-P~1.IMX"}, /* 21 */
+	{3, 1223, "stateCabana",        0, 0,   60, "1223-C~1.IMX"}, /* 22 */
+	{3, 1224, "statePostCabana",   23, 0,   60, "1224-P~1.IMX"}, /* 23 */
+	{3, 1225, "stateBeachClub",    23, 0,   60, "1225-B~1.IMX"}, /* 24 */
+	{3, 1230, "stateCliff",         0, 0,   60, "1230-C~1.IMX"}, /* 25 */
+	{3, 1232, "stateBelly",         0, 0,   48, "1232-B~1.IMX"}, /* 26 */
+	{3, 1235, "stateQuicksand",     0, 0,   60, "1235-Q~1.IMX"}, /* 27 */
+	{3, 1240, "stateDangerBeach",   0, 0,   48, "1240-D~1.IMX"}, /* 28 */
+	{12,1241, "stateDangerBeachAlt",0, 2,   48, "1240-D~1.IMX"}, /* 29 */
+	{3, 1245, "stateRowBoat",       0, 0,   60, "1245-R~1.IMX"}, /* 30 */
+	{3, 1247, "stateAlongside",     0, 0,   48, "1247-A~1.IMX"}, /* 31 */
+	{12,1248, "stateAlongsideAlt",  0, 1,   48, "1247-A~1.IMX"}, /* 32 */
+	{3, 1250, "stateChimpBoat",     0, 0,   30, "1250-C~1.IMX"}, /* 33 */
+	{3, 1255, "stateMrFossey",      0, 0,   48, "1255-M~1.IMX"}, /* 34 */
+	{3, 1259, "statePreTown",       0, 0,   60, "1259-P~1.IMX"}, /* 35 */
+	{3, 1260, "stateTown",          0, 0,   60, "1260-T~1.IMX"}, /* 36 */
+	{3, 1264, "statePreMeadow",     0, 0,   60, "1264-P~1.IMX"}, /* 37 */
+	{3, 1265, "stateMeadow",        0, 0,   60, "1265-M~1.IMX"}, /* 38 */
+	{3, 1266, "stateMeadowAmb",     0, 0,   60, "1266-M~1.IMX"}, /* 39 */
+	{3, 1270, "stateWardrobePre",  40, 0,   60, "1270-W~1.IMX"}, /* 40 */
+	{3, 1272, "statePreShow",      40, 0,   60, "1272-P~1.IMX"}, /* 41 */
+	{3, 1274, "stateWardrobeShow", 42, 0,   60, "1274-W~1.IMX"}, /* 42 */
+	{3, 1276, "stateShow",         42, 0,   60, "1276-S~1.IMX"}, /* 43 */
+	{3, 1277, "stateWardrobeJug",  44, 0,   60, "1277-W~1.IMX"}, /* 44 */
+	{3, 1278, "stateJuggling",     44, 0,   60, "1278-J~1.IMX"}, /* 45 */
+	{3, 1279, "statePostShow",      0, 0,   60, "1279-P~1.IMX"}, /* 46 */
+	{3, 1280, "stateChickenShop",   0, 0,   60, "1280-C~1.IMX"}, /* 47 */
+	{3, 1285, "stateBarberShop",   48, 0,   60, "1285-B~1.IMX"}, /* 48 */
+	{3, 1286, "stateVanHelgen",    48, 0,   60, "1286-V~1.IMX"}, /* 49 */
+	{3, 1287, "stateBill",         48, 0,   60, "1287-B~1.IMX"}, /* 50 */
+	{3, 1288, "stateHaggis",       48, 0,   60, "1288-H~1.IMX"}, /* 51 */
+	{3, 1289, "stateRottingham",   48, 0,   60, "1289-R~1.IMX"}, /* 52 */
+	{3, 1305, "stateDeck",          0, 0,   60, "1305-D~1.IMX"}, /* 53 */
+	{3, 1310, "stateCombatMap",     0, 0,   60, "1310-C~1.IMX"}, /* 54 */
+	{3, 1320, "stateShipCombat",    0, 0,   60, "1320-S~1.IMX"}, /* 55 */
+	{3, 1325, "stateSwordfight",    0, 0,   60, "1325-S~1.IMX"}, /* 56 */
+	{3, 1327, "stateSwordRott",     0, 0,   60, "1327-S~1.IMX"}, /* 57 */
+	{3, 1330, "stateTownEdge",      0, 0,   60, "1330-T~1.IMX"}, /* 58 */
+	{3, 1335, "stateSwordLose",     0, 0,   60, "1335-S~1.IMX"}, /* 59 */
+	{3, 1340, "stateSwordWin",      0, 0,   60, "1340-S~1.IMX"}, /* 60 */
+	{3, 1345, "stateGetMap",        0, 0,   60, "1345-G~1.IMX"}, /* 61 */
+	{3, 1400, "stateWreckBeach",    0, 0,   60, "1400-W~1.IMX"}, /* 62 */
+	{3, 1405, "stateBloodMap",     63, 0,   60, "1405-B~1.IMX"}, /* 63 */
+	{3, 1410, "stateClearing",      0, 0,   60, "1410-C~1.IMX"}, /* 64 */
+	{3, 1415, "stateLighthouse",   63, 0,   60, "1415-L~1.IMX"}, /* 65 */
+	{3, 1420, "stateVillage",      66, 0,   60, "1420-V~1.IMX"}, /* 66 */
+	{3, 1423, "stateVolcano",      66, 0,   60, "1423-V~1.IMX"}, /* 67 */
+	{3, 1425, "stateAltar",        66, 0,   60, "1425-A~1.IMX"}, /* 68 */
+	{3, 1430, "stateHotelOut",      0, 0,   60, "1430-H~1.IMX"}, /* 69 */
+	{3, 1435, "stateHotelBar",     70, 0,   60, "1435-H~1.IMX"}, /* 70 */
+	{3, 1440, "stateHotelIn",      70, 0,   60, "1440-H~1.IMX"}, /* 71 */
+	{3, 1445, "stateTarotLady",    70, 0,   60, "1445-T~1.IMX"}, /* 72 */
+	{3, 1447, "stateGoodsoup",     70, 0,   60, "1447-G~1.IMX"}, /* 73 */
+	{3, 1448, "stateGuestRoom",     0, 0,   60, "1448-G~1.IMX"}, /* 74 */
+	{3, 1450, "stateWindmill",     63, 0,   60, "1450-W~1.IMX"}, /* 75 */
+	{3, 1455, "stateCemetary",      0, 0,   60, "1455-C~1.IMX"}, /* 76 */
+	{3, 1460, "stateCrypt",        77, 0,   60, "1460-C~1.IMX"}, /* 77 */
+	{3, 1463, "stateGraveDigger",  77, 0,   60, "1463-G~1.IMX"}, /* 78 */
+	{3, 1465, "stateMonkey1",       0, 0,   60, "1465-M~1.IMX"}, /* 79 */
+	{3, 1475, "stateStanDark",      0, 0,   60, "1475-S~1.IMX"}, /* 80 */
+	{3, 1477, "stateStanLight",     0, 0,   60, "1477-S~1.IMX"}, /* 81 */
+	{3, 1480, "stateEggBeach",     63, 0,   60, "1480-E~1.IMX"}, /* 82 */
+	{3, 1485, "stateSkullIsland",   0, 0,   60, "1485-S~1.IMX"}, /* 83 */
+	{3, 1490, "stateSmugglersCave", 0, 0,   60, "1490-S~1.IMX"}, /* 84 */
+	{3, 1500, "stateLeChuckTalk",   0, 0,   60, "1500-L~1.IMX"}, /* 85 */
+	{3, 1505, "stateCarnival",      0, 0,   60, "1505-C~1.IMX"}, /* 86 */
+	{3, 1511, "stateHang",         87, 0,   60, "1511-H~1.IMX"}, /* 87 */
+	{3, 1512, "stateRum",          87, 0,   60, "1512-RUM.IMX"}, /* 88 */
+	{3, 1513, "stateTorture",      87, 0,   60, "1513-T~1.IMX"}, /* 89 */
+	{3, 1514, "stateSnow",         87, 0,   60, "1514-S~1.IMX"}, /* 90 */
+	{3, 1515, "stateCredits",       0, 0,   60, "1515-C~1.IMX"}, /* 91 */
+	{3, 1520, "stateCarnAmb",       0, 0,   60, "1520-C~1.IMX"}, /* 92 */
+	{0,   -1, "",                   0, 0,    0, "",           }
+};
+
+const imuseComiTable _comiSeqMusicTable[] = {
+	{0, 2000, "SEQ_NULL",        0, 0,    0, ""            },
+	{0, 2100, "seqINTRO",        0, 0,    0, ""            },
+	{3, 2105, "seqInterlude1",   0, 0,   60, "2105-I~1.IMX"},
+	{8, 2110, "seqLastBoat",     0, 1,    0, ""            },
+	{0, 2115, "seqSINK_SHIP",    0, 0,    0, ""            },
+	{0, 2120, "seqCURSED_RING",  0, 0,   60, ""            },
+	{3, 2200, "seqInterlude2",   0, 0,   60, "2200-I~1.IMX"},
+	{3, 2210, "seqKidnapped",    0, 0,   60, "2210-K~1.IMX"},
+	{8, 2220, "seqSnakeVomits",  0, 1,    0, ""            },
+	{8, 2222, "seqPopBalloon",   0, 1,    0, ""            },
+	{3, 2225, "seqDropBalls",    0, 0,   60, "2225-D~1.IMX"},
+	{4, 2232, "seqArriveBarber", 0, 0,   60, "2232-A~1.IMX"},
+	{3, 2233, "seqAtonal",       0, 0,   60, "2233-A~1.IMX"},
+	{3, 2235, "seqShaveHead1",   0, 0,   60, "2235-S~1.IMX"},
+	{2, 2236, "seqShaveHead2",   0, 2,   60, "2235-S~1.IMX"},
+	{3, 2245, "seqCaberLose",    0, 0,   60, "2245-C~1.IMX"},
+	{3, 2250, "seqCaberWin",     0, 0,   60, "2250-C~1.IMX"},
+	{3, 2255, "seqDuel1",        0, 0,   60, "2255-D~1.IMX"},
+	{2, 2256, "seqDuel2",        0, 2,   60, "2255-D~1.IMX"},
+	{2, 2257, "seqDuel3",        0, 3,   60, "2255-D~1.IMX"},
+	{3, 2260, "seqBlowUpTree1",  0, 0,   60, "2260-B~1.IMX"},
+	{2, 2261, "seqBlowUpTree2",  0, 2,   60, "2260-B~1.IMX"},
+	{3, 2275, "seqMonkeys",      0, 0,   60, "2275-M~1.IMX"},
+	{9, 2277, "seqAttack",       0, 1,    0, ""            },
+	{3, 2285, "seqSharks",       0, 0,   60, "2285-S~1.IMX"},
+	{3, 2287, "seqTowelWalk",    0, 0,   60, "2287-T~1.IMX"},
+	{0, 2293, "seqNICE_BOOTS",   0, 0,    0, ""            },
+	{0, 2295, "seqBIG_BONED",    0, 0,    0, ""            },
+	{3, 2300, "seqToBlood",      0, 0,   60, "2300-T~1.IMX"},
+	{3, 2301, "seqInterlude3",   0, 0,   60, "2301-I~1.IMX"},
+	{3, 2302, "seqRott1",        0, 0,   60, "2302-R~1.IMX"},
+	{2, 2304, "seqRott2",        0, 2,   60, "2302-R~1.IMX"},
+	{2, 2305, "seqRott2b",       0,21,   60, "2302-R~1.IMX"},
+	{2, 2306, "seqRott3",        0, 3,   60, "2302-R~1.IMX"},
+	{2, 2308, "seqRott4",        0, 4,   60, "2302-R~1.IMX"},
+	{2, 2309, "seqRott5",        0, 5,   60, "2302-R~1.IMX"},
+	{3, 2311, "seqVerse1",       0, 0,   60, "2311-S~1.IMX"},
+	{2, 2312, "seqVerse2",       0, 2,   60, "2311-S~1.IMX"},
+	{2, 2313, "seqVerse3",       0, 3,   60, "2311-S~1.IMX"},
+	{2, 2314, "seqVerse4",       0, 4,   60, "2311-S~1.IMX"},
+	{2, 2315, "seqVerse5",       0, 5,   60, "2311-S~1.IMX"},
+	{2, 2316, "seqVerse6",       0, 6,   60, "2311-S~1.IMX"},
+	{2, 2317, "seqVerse7",       0, 7,   60, "2311-S~1.IMX"},
+	{2, 2318, "seqVerse8",       0, 8,   60, "2311-S~1.IMX"},
+	{2, 2319, "seqSongEnd",      0, 9,   60, "2311-S~1.IMX"},
+	{2, 2336, "seqRiposteLose",  0, 0,   60, "2336-R~1.IMX"},
+	{2, 2337, "seqRiposteWin",   0, 0,   60, "2337-R~1.IMX"},
+	{2, 2338, "seqInsultLose",   0, 0,   60, "2338-I~1.IMX"},
+	{2, 2339, "seqInsultWin",    0, 0,   60, "2339-I~1.IMX"},
+	{3, 2340, "seqSwordLose",    0, 0,   60, "1335-S~1.IMX"},
+	{3, 2345, "seqSwordWin",     0, 0,   60, "1340-S~1.IMX"},
+	{3, 2347, "seqGetMap",       0, 0,   60, "1345-G~1.IMX"},
+	{3, 2400, "seqInterlude4",   0, 0,   60, "2400-I~1.IMX"},
+	{0, 2405, "seqSHIPWRECK",    0, 0,    0, ""            },
+	{3, 2408, "seqFakeCredits",  0, 0,   60, "2408-F~1.IMX"},
+	{3, 2410, "seqPassOut",      0, 0,   60, "2410-P~1.IMX"},
+	{3, 2414, "seqGhostTalk",    0, 0,   60, "2414-G~1.IMX"},
+	{2, 2415, "seqGhostWedding", 0, 1,   60, "2414-G~1.IMX"},
+	{3, 2420, "seqEruption",     0, 0,   60, "2420-E~1.IMX"},
+	{3, 2425, "seqSacrifice",    0, 0,   60, "2425-S~1.IMX"},
+	{2, 2426, "seqSacrificeEnd", 0, 1,   60, "2425-S~1.IMX"},
+	{3, 2430, "seqScareDigger",  0, 0,   60, "2430-S~1.IMX"},
+	{3, 2445, "seqSkullArrive",  0, 0,   60, "2445-S~1.IMX"},
+	{3, 2450, "seqFloat",        0, 0,   60, "2450-C~1.IMX"},
+	{2, 2451, "seqFall",         0, 1,   60, "2450-C~1.IMX"},
+	{2, 2452, "seqUmbrella",     0, 2,   60, "2450-C~1.IMX"},
+	{3, 2460, "seqFight",        0, 0,   60, "2460-F~1.IMX"},
+	{0, 2465, "seqLAVE_RIDE",    0, 0,    0, ""            },
+	{0, 2470, "seqMORE_SLAW",    0, 0,    0, ""            },
+	{0, 2475, "seqLIFT_CURSE",   0, 0,    0, ""            },
+	{3, 2500, "seqInterlude5",   0, 0,   60, "2500-I~1.IMX"},
+	{3, 2502, "seqExitSkycar",   0, 0,   60, "2502-E~1.IMX"},
+	{3, 2504, "seqGrow1",        0, 0,   60, "2504-G~1.IMX"},
+	{2, 2505, "seqGrow2",        0, 1,   60, "2504-G~1.IMX"},
+	{3, 2508, "seqInterlude6",   0, 0,   60, "2508-I~1.IMX"},
+	{0, 2515, "seqFINALE",       0, 0,    0, ""            },
+	{3, 2520, "seqOut",          0, 0,   60, "2520-OUT.IMX"},
+	{3, 2530, "seqZap1a",        0, 0,   60, "2530-Z~1.IMX"},
+	{2, 2531, "seqZap1b",        0, 1,   60, "2530-Z~1.IMX"},
+	{2, 2532, "seqZap1c",        0, 2,   60, "2530-Z~1.IMX"},
+	{2, 2540, "seqZap2a",        0, 0,   60, "2540-Z~1.IMX"},
+	{2, 2541, "seqZap2b",        0, 1,   60, "2540-Z~1.IMX"},
+	{2, 2542, "seqZap2c",        0, 2,   60, "2540-Z~1.IMX"},
+	{3, 2550, "seqZap3a",        0, 0,   60, "2550-Z~1.IMX"},
+	{2, 2551, "seqZap3b",        0, 1,   60, "2550-Z~1.IMX"},
+	{2, 2552, "seqZap3c",        0, 2,   60, "2550-Z~1.IMX"},
+	{3, 2560, "seqZap4a",        0, 0,   60, "2560-Z~1.IMX"},
+	{2, 2561, "seqZap4b",        0, 1,   60, "2560-Z~1.IMX"},
+	{2, 2562, "seqZap4c",        0, 2,   60, "2560-Z~1.IMX"},
+	{0,   -1, "",                0, 0,    0, ""            }
+};
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_tables.h b/engines/grim/imuse/dimuse_tables.h
new file mode 100644
index 00000000000..e9c4ae0fad9
--- /dev/null
+++ b/engines/grim/imuse/dimuse_tables.h
@@ -0,0 +1,44 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef GRIM_IMUSE_TABLES_H
+#define GRIM_IMUSE_TABLES_H
+
+#include "common/scummsys.h"
+
+namespace Grim {
+
+struct imuseComiTable {
+	byte transitionType;
+	int16 soundId;
+	char name[20];
+	byte attribPos;
+	byte hookId;
+	int16 fadeOutDelay;
+	char filename[13];
+};
+
+extern const imuseComiTable _comiStateMusicTable[];
+extern const imuseComiTable _comiSeqMusicTable[];
+
+} // End of namespace Grim
+
+#endif
diff --git a/engines/grim/imuse/dimuse_tracks.cpp b/engines/grim/imuse/dimuse_tracks.cpp
new file mode 100644
index 00000000000..84eb4f8f7f6
--- /dev/null
+++ b/engines/grim/imuse/dimuse_tracks.cpp
@@ -0,0 +1,727 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_engine.h"
+
+namespace Grim {
+
+int IMuseDigital::tracksInit() {
+	_trackCount = _lowLatencyMode ? DIMUSE_MAX_TRACKS : 6;
+	_tracksPauseTimer = 0;
+	_trackList = nullptr;
+
+	if (waveOutInit(&waveOutSettings))
+		return -1;
+
+	if (_internalMixer->init(waveOutSettings.bytesPerSample,
+			waveOutSettings.numChannels,
+			waveOutSettings.mixBuf,
+			waveOutSettings.mixBufSize,
+			waveOutSettings.sizeSampleKB,
+			_trackCount) ||
+			dispatchInit() ||
+		streamerInit()) {
+		return -1;
+	}
+
+	for (int l = 0; l < _trackCount; l++) {
+		_tracks[l].index = l;
+		_tracks[l].prev = nullptr;
+		_tracks[l].next = nullptr;
+		_tracks[l].dispatchPtr = dispatchGetDispatchByTrackId(l);
+		_tracks[l].dispatchPtr->trackPtr = &_tracks[l];
+		_tracks[l].soundId = 0;
+		_tracks[l].group = 0;
+		_tracks[l].marker = 0;
+		_tracks[l].priority = 0;
+		_tracks[l].vol = 0;
+		_tracks[l].effVol = 0;
+		_tracks[l].pan = 0;
+		_tracks[l].detune = 0;
+		_tracks[l].transpose = 0;
+		_tracks[l].pitchShift = 0;
+		_tracks[l].mailbox = 0;
+		_tracks[l].jumpHook = 0;
+		_tracks[l].syncSize_0 = 0;
+		_tracks[l].syncSize_1 = 0;
+		_tracks[l].syncSize_2 = 0;
+		_tracks[l].syncSize_3 = 0;
+		_tracks[l].syncPtr_0 = nullptr;
+		_tracks[l].syncPtr_1 = nullptr;
+		_tracks[l].syncPtr_2 = nullptr;
+		_tracks[l].syncPtr_3 = nullptr;
+	}
+
+	return 0;
+}
+
+void IMuseDigital::tracksPause() {
+	_tracksPauseTimer = 1;
+}
+
+void IMuseDigital::tracksResume() {
+	_tracksPauseTimer = 0;
+}
+
+void IMuseDigital::tracksSaveLoad(Common::Serializer &ser) {
+	Common::StackLock lock(*_mutex);
+	dispatchSaveLoad(ser);
+
+	for (int l = 0; l < _trackCount; l++) {
+		ser.syncAsSint32LE(_tracks[l].soundId, VER(103));
+		ser.syncAsSint32LE(_tracks[l].marker, VER(103));
+		ser.syncAsSint32LE(_tracks[l].group, VER(103));
+		ser.syncAsSint32LE(_tracks[l].priority, VER(103));
+		ser.syncAsSint32LE(_tracks[l].vol, VER(103));
+		ser.syncAsSint32LE(_tracks[l].effVol, VER(103));
+		ser.syncAsSint32LE(_tracks[l].pan, VER(103));
+		ser.syncAsSint32LE(_tracks[l].detune, VER(103));
+		ser.syncAsSint32LE(_tracks[l].transpose, VER(103));
+		ser.syncAsSint32LE(_tracks[l].pitchShift, VER(103));
+		ser.syncAsSint32LE(_tracks[l].mailbox, VER(103));
+		ser.syncAsSint32LE(_tracks[l].jumpHook, VER(103));
+
+		ser.syncAsSint32LE(_tracks[l].syncSize_0, VER(103));
+		ser.syncAsSint32LE(_tracks[l].syncSize_1, VER(103));
+		ser.syncAsSint32LE(_tracks[l].syncSize_2, VER(103));
+		ser.syncAsSint32LE(_tracks[l].syncSize_3, VER(103));
+
+		if (_tracks[l].syncSize_0) {
+			if (ser.isLoading())
+				_tracks[l].syncPtr_0 = (byte *)malloc(_tracks[l].syncSize_0);
+			ser.syncArray(_tracks[l].syncPtr_0, _tracks[l].syncSize_0, Common::Serializer::Byte, VER(103));
+		}
+
+		if (_tracks[l].syncSize_1) {
+			if (ser.isLoading())
+				_tracks[l].syncPtr_1 = (byte *)malloc(_tracks[l].syncSize_1);
+			ser.syncArray(_tracks[l].syncPtr_1, _tracks[l].syncSize_1, Common::Serializer::Byte, VER(103));
+		}
+
+		if (_tracks[l].syncSize_2) {
+			if (ser.isLoading())
+				_tracks[l].syncPtr_2 = (byte *)malloc(_tracks[l].syncSize_2);
+			ser.syncArray(_tracks[l].syncPtr_2, _tracks[l].syncSize_2, Common::Serializer::Byte, VER(103));
+		}
+
+		if (_tracks[l].syncSize_3) {
+			if (ser.isLoading())
+				_tracks[l].syncPtr_3 = (byte *)malloc(_tracks[l].syncSize_3);
+			ser.syncArray(_tracks[l].syncPtr_3, _tracks[l].syncSize_3, Common::Serializer::Byte, VER(103));
+		}
+	}
+
+	if (ser.isLoading()) {
+		for (int l = 0; l < _trackCount; l++) {
+			_tracks[l].prev = nullptr;
+			_tracks[l].next = nullptr;
+			_tracks[l].dispatchPtr = dispatchGetDispatchByTrackId(l);
+			_tracks[l].dispatchPtr->trackPtr = &_tracks[l];
+			if (_tracks[l].soundId) {
+				addTrackToList(&_trackList, &_tracks[l]);
+			}
+		}
+
+		dispatchRestoreStreamZones();
+	}
+}
+
+void IMuseDigital::tracksSetGroupVol() {
+	IMuseDigiTrack* curTrack = _trackList;
+	while (curTrack) {
+		curTrack->effVol = ((curTrack->vol + 1) * _groupsHandler->getGroupVol(curTrack->group)) / 128;
+		curTrack = curTrack->next;
+	}
+}
+
+void IMuseDigital::tracksCallback() {
+	if (_tracksPauseTimer) {
+		if (++_tracksPauseTimer < 3)
+			return;
+		_tracksPauseTimer = 3;
+	}
+
+	// This piece of code is responsible for adaptive buffer overrun correction:
+	// it checks whether a buffer underrun has occurred within our output stream
+	// and then it increments the buffer count.
+	//
+	// This is not part of the original implementation, but it's used to yield
+	// smooth audio hopefully on every device.
+	if (_internalMixer->_stream->endOfData() && _checkForUnderrun) {
+		debug(5, "IMuseDigital::tracksCallback(): WARNING: audio buffer underrun, adapting the buffer queue count...");
+
+		adaptBufferCount();
+
+		// Allow the routine to cooldown: i.e. wait until the engine manages to
+		// refill the stream with the most recent maximum number of queueable buffers.
+		_underrunCooldown = _maxQueuedStreams;
+		_checkForUnderrun = false;
+	}
+
+	// If we leave the number of queued streams unbounded, we fill the queue with streams faster than
+	// we can play them: this leads to a very noticeable audio latency and desync with the graphics.
+	if ((int)_internalMixer->_stream->numQueuedStreams() < _maxQueuedStreams) {
+		dispatchPredictFirstStream();
+
+		waveOutWrite(&_outputAudioBuffer, _outputFeedSize, _outputSampleRate);
+
+		if (_outputFeedSize != 0) {
+			// Let's see if we should check for buffer underruns...
+			if (!_checkForUnderrun) {
+				if (_underrunCooldown == 0) {
+					_checkForUnderrun = true;
+				} else {
+					_underrunCooldown--;
+				}
+			}
+
+			_internalMixer->clearMixerBuffer();
+
+			if (!_tracksPauseTimer) {
+				IMuseDigiTrack *track = _trackList;
+
+				while (track) {
+					IMuseDigiTrack *next = track->next;
+					dispatchProcessDispatches(track, _outputFeedSize, _outputSampleRate);
+					track = next;
+				};
+			}
+
+			_internalMixer->loop(&_outputAudioBuffer, _outputFeedSize);
+		}
+	}
+}
+
+void IMuseDigital::tracksLowLatencyCallback() {
+	// Why do we need a low latency mode?
+	//
+	// For every audio callback, this engine works by collecting all the sound
+	// data for every track and by mixing it up in a single output stream.
+	// This is exactly how the original executables worked, so our implementation
+	// provides a very faithful recreation of that experience. And it comes with
+	// a compromise that e.g. The Dig and Full Throttle didn't have to front:
+	//
+	// in order to provide glitchless audio, an appropriate stream queue size
+	// has to be enforced: a longer queue yields a lower probability of audio glitches
+	// but a higher latency, and viceversa. In our case, this depends on the audio backend
+	// configuration. As such: some configurations might encounter audible latency (#13462).
+	//
+	// We solve this issue by offering this alternate low latency mode which, instead
+	// of keeping a single stream for everything, creates (and disposes) streams on the fly
+	// for every different sound. This means that whenever the new sound data is ready,
+	// a new stream is initialized and played immediately, without having to wait for all
+	// the other sounds to be processed and mixed in the same sample pool.
+
+	if (_tracksPauseTimer) {
+		if (++_tracksPauseTimer < 3)
+			return;
+		_tracksPauseTimer = 3;
+	}
+
+	// The callback path is heavily inspired from the original one (see tracksCallback()),
+	// but it handles each track separatedly.
+
+	dispatchPredictFirstStream();
+
+	IMuseDigiTrack *track = _trackList;
+
+	while (track) {
+
+		IMuseDigiTrack *next = track->next;
+		int idx = track->index;
+
+		bool canQueueBufs = (int)_internalMixer->getStream(idx)->numQueuedStreams() < (_maxQueuedStreams + 1);
+
+		if (canQueueBufs) {
+			waveOutLowLatencyWrite(&_outputLowLatencyAudioBuffers[idx], _outputFeedSize, _outputSampleRate, idx);
+
+			if (_outputFeedSize != 0) {
+				// Ordinary audio tracks handling...
+				_internalMixer->setCurrentMixerBuffer(_outputLowLatencyAudioBuffers[idx]);
+				_internalMixer->clearMixerBuffer();
+
+				if (!_tracksPauseTimer) {
+					dispatchProcessDispatches(track, _outputFeedSize, _outputSampleRate);
+				}
+
+				_internalMixer->loop(&_outputLowLatencyAudioBuffers[idx], _outputFeedSize);
+
+				// If, after processing the track dispatch, the sound is set to zero
+				// it means that it has reached the end: let's notify its stream...
+				if (track->soundId == 0) {
+					_internalMixer->endStream(idx);
+				}
+			}
+		}
+
+		track = next;
+	}
+}
+
+int IMuseDigital::tracksStartSound(int soundId, int tryPriority, int group) {
+	int priority = clampNumber(tryPriority, 0, 127);
+
+	debug(5, "IMuseDigital::tracksStartSound(): sound %d with priority %d and group %d", soundId, priority, group);
+	IMuseDigiTrack *allocatedTrack = tracksReserveTrack(priority);
+
+	if (!allocatedTrack) {
+		debug(5, "IMuseDigital::tracksStartSound(): ERROR: couldn't find a spare track to allocate sound %d", soundId);
+		return -6;
+	}
+
+	allocatedTrack->soundId = soundId;
+	allocatedTrack->marker = 0;
+	allocatedTrack->group = 0;
+	allocatedTrack->priority = priority;
+	allocatedTrack->vol = 127;
+	allocatedTrack->effVol = _groupsHandler->getGroupVol(0);
+	allocatedTrack->pan = 64;
+	allocatedTrack->detune = 0;
+	allocatedTrack->transpose = 0;
+	allocatedTrack->pitchShift = 256;
+	allocatedTrack->mailbox = 0;
+	allocatedTrack->jumpHook = 0;
+	allocatedTrack->syncSize_0 = 0;
+	allocatedTrack->syncPtr_0 = nullptr;
+	allocatedTrack->syncSize_1 = 0;
+	allocatedTrack->syncPtr_1 = nullptr;
+	allocatedTrack->syncSize_2 = 0;
+	allocatedTrack->syncPtr_2 = nullptr;
+	allocatedTrack->syncSize_3 = 0;
+	allocatedTrack->syncPtr_3 = nullptr;
+
+	if (dispatchAllocateSound(allocatedTrack, group)) {
+		debug(5, "IMuseDigital::tracksStartSound(): ERROR: dispatch couldn't start sound %d", soundId);
+		allocatedTrack->soundId = 0;
+		return -1;
+	}
+
+	_mutex->lock();
+	addTrackToList(&_trackList, allocatedTrack);
+	_mutex->unlock();
+
+	return 0;
+}
+
+int IMuseDigital::tracksStopSound(int soundId) {
+	if (!_trackList)
+		return -1;
+
+	IMuseDigiTrack *nextTrack = _trackList;
+	IMuseDigiTrack *curTrack;
+
+	while (nextTrack) {
+		curTrack = nextTrack;
+		nextTrack = curTrack->next;
+		if (curTrack->soundId == soundId) {
+			tracksClear(curTrack);
+		}
+	}
+
+	return 0;
+}
+
+int IMuseDigital::tracksStopAllSounds() {
+	Common::StackLock lock(*_mutex);
+	IMuseDigiTrack *nextTrack = _trackList;
+	IMuseDigiTrack *curTrack;
+
+	while (nextTrack) {
+		curTrack = nextTrack;
+		nextTrack = curTrack->next;
+		tracksClear(curTrack);
+	}
+
+	_filesHandler->closeAllSounds();
+
+	return 0;
+}
+
+int IMuseDigital::tracksGetNextSound(int soundId) {
+	int foundSoundId = 0;
+	IMuseDigiTrack *track = _trackList;
+	while (track) {
+		if (track->soundId > soundId) {
+			if (!foundSoundId || track->soundId < foundSoundId) {
+				foundSoundId = track->soundId;
+			}
+		}
+		track = track->next;
+	};
+
+	return foundSoundId;
+}
+
+int IMuseDigital::tracksQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
+	if (!_trackList) {
+		debug(5, "IMuseDigital::tracksQueryStream(): WARNING: empty trackList, ignoring call...");
+		return -1;
+	}
+
+	IMuseDigiTrack *track = _trackList;
+	do {
+		if (track->soundId) {
+			if (soundId == track->soundId && track->dispatchPtr->streamPtr) {
+				streamerQueryStream(track->dispatchPtr->streamPtr, bufSize, criticalSize, freeSpace, paused);
+				return 0;
+			}
+		}
+		track = track->next;
+	} while (track);
+
+	debug(5, "IMuseDigital::tracksQueryStream(): WARNING: couldn't find sound %d in trackList, ignoring call...", soundId);
+	return -1;
+}
+
+int IMuseDigital::tracksFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused) {
+	if (!_trackList)
+		return -1;
+
+	IMuseDigiTrack *track = _trackList;
+	do {
+		if (track->soundId != 0) {
+			if (track->soundId == soundId && track->dispatchPtr->streamPtr) {
+				streamerFeedStream(track->dispatchPtr->streamPtr, srcBuf, sizeToFeed, paused);
+				return 0;
+			}
+		}
+		track = track->next;
+	} while (track);
+
+	return -1;
+}
+
+void IMuseDigital::tracksClear(IMuseDigiTrack *trackPtr) {
+	Common::StackLock lock(*_mutex);
+
+	if (trackPtr->syncPtr_0) {
+		trackPtr->syncSize_0 = 0;
+		free(trackPtr->syncPtr_0);
+		trackPtr->syncPtr_0 = nullptr;
+	}
+
+	if (trackPtr->syncPtr_1) {
+		trackPtr->syncSize_1 = 0;
+		free(trackPtr->syncPtr_1);
+		trackPtr->syncPtr_1 = nullptr;
+	}
+
+	if (trackPtr->syncPtr_2) {
+		trackPtr->syncSize_2 = 0;
+		free(trackPtr->syncPtr_2);
+		trackPtr->syncPtr_2 = nullptr;
+	}
+
+	if (trackPtr->syncPtr_3) {
+		trackPtr->syncSize_3 = 0;
+		free(trackPtr->syncPtr_3);
+		trackPtr->syncPtr_3 = nullptr;
+	}
+
+	removeTrackFromList(&_trackList, trackPtr);
+	dispatchRelease(trackPtr);
+	_fadesHandler->clearFadeStatus(trackPtr->soundId, -1);
+	_triggersHandler->clearTrigger(trackPtr->soundId, _emptyMarker, -1);
+
+	// Unlock the sound, if it's loaded as a resource
+	// TODO
+	// if (trackPtr->soundId < 1000 && trackPtr->soundId) {
+	// 	_vm->_res->unlock(rtSound, trackPtr->soundId);
+	// }
+
+	if (_lowLatencyMode)
+		waveOutEmptyBuffer(trackPtr->index);
+
+	trackPtr->soundId = 0;
+}
+
+int IMuseDigital::tracksSetParam(int soundId, int opcode, int value) {
+	if (!_trackList)
+		return -4;
+
+	IMuseDigiTrack *track = _trackList;
+	while (track) {
+		if (track->soundId == soundId) {
+			switch (opcode) {
+			case DIMUSE_P_GROUP:
+				if (value >= 16)
+					return -5;
+				track->group = value;
+				track->effVol = ((track->vol + 1) * _groupsHandler->getGroupVol(value)) / 128;
+				return 0;
+			case DIMUSE_P_PRIORITY:
+				if (value > 127)
+					return -5;
+				track->priority = value;
+				return 0;
+			case DIMUSE_P_VOLUME:
+				if (value > 127)
+					return -5;
+				track->vol = value;
+				track->effVol = ((value + 1) * _groupsHandler->getGroupVol(track->group)) / 128;
+				return 0;
+			case DIMUSE_P_PAN:
+				if (value > 127)
+					return -5;
+				track->pan = value;
+				return 0;
+			case DIMUSE_P_DETUNE:
+				if (value < -9216 || value > 9216)
+					return -5;
+				track->detune = value;
+				track->pitchShift = value + track->transpose * 256;
+				return 0;
+			case DIMUSE_P_TRANSPOSE:
+				if (value < 0 || value > 4095)
+					return -5;
+
+				track->pitchShift = value;
+				return 0;
+			case DIMUSE_P_MAILBOX:
+				track->mailbox = value;
+				return 0;
+			default:
+				debug(5, "IMuseDigital::tracksSetParam(): unknown opcode %d", opcode);
+				return -5;
+			}
+		}
+		track = track->next;
+	}
+
+	return -4;
+}
+
+int IMuseDigital::tracksGetParam(int soundId, int opcode) {
+	if (!_trackList) {
+		if (opcode != DIMUSE_P_SND_TRACK_NUM)
+			return -4;
+		else
+			return 0;
+	}
+
+	IMuseDigiTrack *track = _trackList;
+	int l = 0;
+	do {
+		if (track)
+			l++;
+		if (track->soundId == soundId) {
+			switch (opcode) {
+			case DIMUSE_P_BOGUS_ID:
+				return -1;
+			case DIMUSE_P_SND_TRACK_NUM:
+				return l;
+			case DIMUSE_P_TRIGS_SNDS:
+				return -1;
+			case DIMUSE_P_MARKER:
+				return track->marker;
+			case DIMUSE_P_GROUP:
+				return track->group;
+			case DIMUSE_P_PRIORITY:
+				return track->priority;
+			case DIMUSE_P_VOLUME:
+				return track->vol;
+			case DIMUSE_P_PAN:
+				return track->pan;
+			case DIMUSE_P_DETUNE:
+				return track->detune;
+			case DIMUSE_P_TRANSPOSE:
+				return track->transpose;
+			case DIMUSE_P_MAILBOX:
+				return track->mailbox;
+			case DIMUSE_P_SND_HAS_STREAM:
+				return (track->dispatchPtr->streamPtr != 0);
+			case DIMUSE_P_STREAM_BUFID:
+				return track->dispatchPtr->streamBufID;
+			case DIMUSE_P_SND_POS_IN_MS: // getCurSoundPositionInMs
+				if (track->dispatchPtr->wordSize == 0)
+					return 0;
+				if (track->dispatchPtr->sampleRate == 0)
+					return 0;
+				if (track->dispatchPtr->channelCount == 0)
+					return 0;
+				return (track->dispatchPtr->currentOffset * 5) / (((track->dispatchPtr->wordSize / 8) * track->dispatchPtr->sampleRate * track->dispatchPtr->channelCount) / 200);
+			default:
+				return -5;
+			}
+		}
+
+		track = track->next;
+	} while (track);
+
+	return 0;
+}
+
+int IMuseDigital::tracksLipSync(int soundId, int syncId, int msPos, int32 &width, int32 &height) {
+	int32 w, h;
+
+	byte *syncPtr = nullptr;
+	int32 syncSize = 0;
+
+	IMuseDigiTrack *curTrack;
+	int16 val;
+
+	w = 0;
+	h = 0;
+	curTrack = _trackList;
+
+	if (msPos >= 0) {
+		// Check for an invalid timestamp:
+		// this has to be a suitable 2-bytes word...
+		if (((msPos >> 4) & 0xFFFF0000) != 0) {
+			return -5;
+		} else {
+			if (_trackList) {
+				do {
+					if (curTrack->soundId == soundId)
+						break;
+					curTrack = curTrack->next;
+				} while (curTrack);
+			}
+
+			if (curTrack) {
+				if (syncId >= 0 && syncId < 4) {
+					if (syncId == 0) {
+						syncPtr = curTrack->syncPtr_0;
+						syncSize = curTrack->syncSize_0;
+					} else if (syncId == 1) {
+						syncPtr = curTrack->syncPtr_1;
+						syncSize = curTrack->syncSize_1;
+					} else if (syncId == 2) {
+						syncPtr = curTrack->syncPtr_2;
+						syncSize = curTrack->syncSize_2;
+					} else if (syncId == 3) {
+						syncPtr = curTrack->syncPtr_3;
+						syncSize = curTrack->syncSize_3;
+					}
+
+					if (syncSize && syncPtr) {
+						// SYNC data is packed in a number of 4-bytes entries, in the following order:
+						// - Width and height values, packed as one byte each, next to each other;
+						// - The time position of said values, packed as an unsigned word (2-bytes).
+
+						// Given an input timestamp (in ms), we're going to get its representation as 60Hz
+						// increments by dividing it by 16, then we're going to search the SYNC data from
+						// the beginning to find the first entry with a timestamp being equal or greater
+						// our 60Hz timestamp.
+						uint16 inputTs = msPos >> 4;
+						int32 numOfEntries = (syncSize >> 2);
+						uint16 *syncDataWordPtr = (uint16 *)syncPtr;
+						uint16 curEntryTs = 0;
+						int idx;
+						for (idx = 0; idx < numOfEntries; idx++) {
+							curEntryTs = READ_LE_UINT16(&syncDataWordPtr[idx * 2 + 1]);
+							if (curEntryTs >= inputTs) {
+								break;
+							}
+						}
+
+						// If no relevant entry is found, or if the found entry timestamp is strictly greater
+						// than ours, then we get the previous entry. If no entry was found, this will get the
+						// last entry in our data block.
+						if (idx == numOfEntries || curEntryTs > inputTs) {
+							idx--;
+						}
+
+						// Finally, extract width and height values and remove
+						// their signs by performing AND operations with 0x7F...
+						val = READ_LE_INT16(&syncDataWordPtr[idx * 2]);
+						w = (val >> 8) & 0x7F;
+						h = val & 0x7F;
+					}
+				}
+			} else {
+				return -4;
+			}
+		}
+	}
+
+	width = w;
+	height = h;
+
+	return 0;
+}
+
+int IMuseDigital::tracksSetHook(int soundId, int hookId) {
+	if (hookId > 128)
+		return -5;
+	if (!_trackList)
+		return -4;
+
+	IMuseDigiTrack *track = _trackList;
+	while (track->soundId != soundId) {
+		track = track->next;
+		if (!track)
+			return -4;
+	}
+
+	track->jumpHook = hookId;
+
+	return 0;
+}
+
+int IMuseDigital::tracksGetHook(int soundId) {
+	if (!_trackList)
+		return -4;
+
+	IMuseDigiTrack *track = _trackList;
+	while (track->soundId != soundId) {
+		track = track->next;
+		if (!track)
+			return -4;
+	}
+
+	return track->jumpHook;
+}
+
+IMuseDigiTrack *IMuseDigital::tracksReserveTrack(int priority) {
+	IMuseDigiTrack *curTrack;
+	IMuseDigiTrack *reservedTrack = nullptr;
+	int minPriorityFound;
+
+	// Pick the track from the pool of free tracks
+	for (int i = 0; i < _trackCount; i++) {
+		reservedTrack = &_tracks[i];
+		if (!reservedTrack->soundId) {
+			return reservedTrack;
+		}
+	}
+
+	// If no free track is found, steal the lower priority one
+	curTrack = _trackList;
+	for (minPriorityFound = 127; curTrack; curTrack = curTrack->next) {
+		if (curTrack->priority <= minPriorityFound) {
+			minPriorityFound = curTrack->priority;
+			reservedTrack = curTrack;
+		}
+	}
+
+	if (reservedTrack && priority >= minPriorityFound) {
+		tracksClear(reservedTrack);
+	}
+
+	return reservedTrack;
+}
+
+void IMuseDigital::tracksDeinit() {
+	tracksStopAllSounds();
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_triggers.cpp b/engines/grim/imuse/dimuse_triggers.cpp
new file mode 100644
index 00000000000..3b4776f0bec
--- /dev/null
+++ b/engines/grim/imuse/dimuse_triggers.cpp
@@ -0,0 +1,348 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/dimuse_triggers.h"
+
+namespace Grim {
+
+IMuseDigiTriggersHandler::IMuseDigiTriggersHandler(IMuseDigital *engine, Common::Mutex *mutex) {
+	_engine = engine;
+	_mutex = mutex;
+	_emptyMarker[0] = '\0';
+}
+
+IMuseDigiTriggersHandler::~IMuseDigiTriggersHandler() {}
+
+int IMuseDigiTriggersHandler::init() {
+	return clearAllTriggers();
+}
+
+int IMuseDigiTriggersHandler::deinit() {
+	return clearAllTriggers();
+}
+
+int IMuseDigiTriggersHandler::clearAllTriggers() {
+	Common::StackLock lock(*_mutex);
+
+	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+		_trigs[l].sound = 0;
+		memset(_trigs[l].text, 0, sizeof(_trigs[l].text));
+		_trigs[l].opcode = 0;
+		_trigs[l].a = 0;
+		_trigs[l].b = 0;
+		_trigs[l].c = 0;
+		_trigs[l].d = 0;
+		_trigs[l].e = 0;
+		_trigs[l].f = 0;
+		_trigs[l].g = 0;
+		_trigs[l].h = 0;
+		_trigs[l].i = 0;
+		_trigs[l].j = 0;
+		_trigs[l].clearLater = 0;
+	}
+
+	for (int l = 0; l < DIMUSE_MAX_DEFERS; l++) {
+		_defers[l].counter = 0;
+		_defers[l].opcode = 0;
+		_defers[l].a = 0;
+		_defers[l].b = 0;
+		_defers[l].c = 0;
+		_defers[l].d = 0;
+		_defers[l].e = 0;
+		_defers[l].f = 0;
+		_defers[l].g = 0;
+		_defers[l].h = 0;
+		_defers[l].i = 0;
+		_defers[l].j = 0;
+	}
+
+	_defersOn = 0;
+	_midProcessing = 0;
+	return 0;
+}
+
+void IMuseDigiTriggersHandler::saveLoad(Common::Serializer &ser) {
+	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+		ser.syncAsSint32LE(_trigs[l].sound, VER(103));
+		ser.syncArray(_trigs[l].text, 256, Common::Serializer::SByte, VER(103));
+		ser.syncAsSint32LE(_trigs[l].opcode, VER(103));
+		ser.syncAsSint32LE(_trigs[l].a, VER(103));
+		ser.syncAsSint32LE(_trigs[l].b, VER(103));
+		ser.syncAsSint32LE(_trigs[l].c, VER(103));
+		ser.syncAsSint32LE(_trigs[l].d, VER(103));
+		ser.syncAsSint32LE(_trigs[l].e, VER(103));
+		ser.syncAsSint32LE(_trigs[l].f, VER(103));
+		ser.syncAsSint32LE(_trigs[l].g, VER(103));
+		ser.syncAsSint32LE(_trigs[l].h, VER(103));
+		ser.syncAsSint32LE(_trigs[l].i, VER(103));
+		ser.syncAsSint32LE(_trigs[l].j, VER(103));
+		ser.syncAsSint32LE(_trigs[l].clearLater, VER(103));
+	}
+
+	for (int l = 0; l < DIMUSE_MAX_DEFERS; l++) {
+		ser.syncAsSint32LE(_defers[l].counter, VER(103));
+		ser.syncAsSint32LE(_defers[l].opcode, VER(103));
+		ser.syncAsSint32LE(_defers[l].a, VER(103));
+		ser.syncAsSint32LE(_defers[l].b, VER(103));
+		ser.syncAsSint32LE(_defers[l].c, VER(103));
+		ser.syncAsSint32LE(_defers[l].d, VER(103));
+		ser.syncAsSint32LE(_defers[l].e, VER(103));
+		ser.syncAsSint32LE(_defers[l].f, VER(103));
+		ser.syncAsSint32LE(_defers[l].g, VER(103));
+		ser.syncAsSint32LE(_defers[l].h, VER(103));
+		ser.syncAsSint32LE(_defers[l].i, VER(103));
+		ser.syncAsSint32LE(_defers[l].j, VER(103));
+	}
+
+	if (ser.isLoading())
+		_defersOn = 1;
+}
+
+int IMuseDigiTriggersHandler::setTrigger(int soundId, char *marker, int opcode, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
+	Common::StackLock lock(*_mutex);
+
+	if (soundId == 0) {
+		return -5;
+	}
+
+	if (marker == nullptr) {
+		marker = _emptyMarker;
+	}
+
+	if (strlen(marker) >= 256) {
+		debug(5, "IMuseDigiTriggersHandler::setTrigger(): ERROR: attempting to set trigger with oversized marker string");
+		return -5;
+	}
+
+	for (int index = 0; index < DIMUSE_MAX_TRIGGERS; index++) {
+		if (_trigs[index].sound == 0) {
+			_trigs[index].sound = soundId;
+			_trigs[index].clearLater = 0;
+			_trigs[index].opcode = opcode;
+			Common::strlcpy(_trigs[index].text, marker, sizeof(_trigs[index].text));
+			_trigs[index].a = d;
+			_trigs[index].b = e;
+			_trigs[index].c = f;
+			_trigs[index].d = g;
+			_trigs[index].e = h;
+			_trigs[index].f = i;
+			_trigs[index].g = j;
+			_trigs[index].h = k;
+			_trigs[index].i = l;
+			_trigs[index].j = m;
+
+			debug(5, "IMuseDigiTriggersHandler::setTrigger(): Successfully set trigger for soundId %d and marker '%s'", soundId, marker);
+			return 0;
+		}
+	}
+
+	debug(5, "IMuseDigiTriggersHandler::setTrigger(): ERROR: unable to allocate trigger \"%s\" for sound %d, every slot is full", marker, soundId);
+	return -6;
+}
+
+int IMuseDigiTriggersHandler::checkTrigger(int soundId, char *marker, int opcode) {
+	Common::StackLock lock(*_mutex);
+
+	int r = 0;
+	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+		if (_trigs[l].sound != 0) {
+			if (soundId == -1 || _trigs[l].sound == soundId) {
+				if (!strcmp(marker, _emptyMarker) || !strcmp(marker, _trigs[l].text)) {
+					if (opcode == -1 || _trigs[l].opcode == opcode)
+						r++;
+				}
+			}
+		}
+	}
+
+	return r;
+}
+
+int IMuseDigiTriggersHandler::clearTrigger(int soundId, char *marker, int opcode) {
+	Common::StackLock lock(*_mutex);
+
+	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+		if ((_trigs[l].sound != 0) && (soundId == -1 || _trigs[l].sound == soundId) &&
+            (!strcmp(marker, _emptyMarker) || !strcmp(marker, _trigs[l].text)) &&
+            (opcode == -1 || _trigs[l].opcode == opcode)) {
+
+			if (_midProcessing) {
+				_trigs[l].clearLater = 1;
+			} else {
+				_trigs[l].sound = 0;
+			}
+		}
+	}
+	return 0;
+}
+
+void IMuseDigiTriggersHandler::processTriggers(int soundId, char *marker) {
+	char textBuffer[256];
+	int r;
+
+	if (strlen(marker) >= 256) {
+		debug(5, "IMuseDigiTriggersHandler::processTriggers(): ERROR: the input marker string is oversized");
+		return;
+	}
+
+	Common::strlcpy(_textBuffer, marker, sizeof(textBuffer));
+	_midProcessing++;
+	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+		if (!_trigs[l].sound || _trigs[l].sound != soundId || (_trigs[l].text[0] && strcmp(_textBuffer, _trigs[l].text))) {
+			continue;
+		}
+
+		// Save the string into our local buffer for later
+		r = 0;
+		if (_textBuffer[0] != '\0') {
+			do {
+				textBuffer[r] = _textBuffer[r];
+				r++;
+			} while (_textBuffer[r] != '\0');
+		}
+		textBuffer[r] = '\0';
+
+		_trigs[l].sound = 0;
+
+		debug(5, "IMuseDigiTriggersHandler::processTriggers(): executing trigger for soundId %d and marker '%s'", soundId, marker);
+		if (_trigs[l].opcode == DIMUSE_C_SCRIPT_CALLBACK) {
+			// Call the script callback (a function which sets _stoppingSequence to 1)
+			_engine->scriptTriggerCallback(_textBuffer);
+		} else {
+			if (_trigs[l].opcode < 30) {
+				// Execute a command
+				_engine->cmdsHandleCmd(_trigs[l].opcode, (uint8 *)textBuffer,
+					_trigs[l].a, _trigs[l].b,
+					_trigs[l].c, _trigs[l].d,
+					_trigs[l].e, _trigs[l].f,
+					_trigs[l].g, _trigs[l].h,
+					_trigs[l].i, _trigs[l].j);
+			}
+		}
+
+		// Restore the global textBuffer
+		r = 0;
+		if (textBuffer[0] != '\0') {
+			do {
+				_textBuffer[r] = textBuffer[r];
+				r++;
+			} while (textBuffer[r] != '\0');
+		}
+		_textBuffer[r] = '\0';
+	}
+	if (--_midProcessing == 0) {
+		for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+			if (_trigs[l].clearLater) {
+				_trigs[l].sound = 0;
+			}
+		}
+	}
+}
+
+int IMuseDigiTriggersHandler::deferCommand(int count, int opcode, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
+	Common::StackLock lock(*_mutex);
+
+	if (!count) {
+		return -5;
+	}
+
+	for (int index = 0; index < DIMUSE_MAX_DEFERS; index++) {
+		if (!_defers[index].counter) {
+			_defers[index].counter = count;
+			_defers[index].opcode = opcode;
+			_defers[index].a = c;
+			_defers[index].b = d;
+			_defers[index].c = e;
+			_defers[index].d = f;
+			_defers[index].e = g;
+			_defers[index].f = h;
+			_defers[index].g = i;
+			_defers[index].h = j;
+			_defers[index].i = k;
+			_defers[index].j = l;
+			_defersOn = 1;
+			return 0;
+		}
+	}
+	debug(5, "IMuseDigiTriggersHandler::deferCommand(): ERROR: couldn't allocate deferred command");
+	return -6;
+}
+
+void IMuseDigiTriggersHandler::loop() {
+	if (!_defersOn)
+		return;
+
+	_defersOn = 0;
+	for (int l = 0; l < DIMUSE_MAX_DEFERS; l++) {
+		if (_defers[l].counter == 0)
+			continue;
+
+		_defersOn = 1;
+		_defers[l].counter--;
+
+		if (_defers[l].counter == 1) {
+			if (_defers[l].opcode == DIMUSE_C_SCRIPT_CALLBACK) {
+				_engine->scriptTriggerCallback(_trigs[l].text);
+			} else {
+				if (_defers[l].opcode < 30) {
+					_engine->cmdsHandleCmd(_trigs[l].opcode, nullptr,
+						_trigs[l].a, _trigs[l].b,
+						_trigs[l].c, _trigs[l].d,
+						_trigs[l].e, _trigs[l].f,
+						_trigs[l].g, _trigs[l].h,
+						_trigs[l].i, _trigs[l].j);
+				}
+			}
+		}
+	}
+}
+
+int IMuseDigiTriggersHandler::countPendingSounds(int soundId) {
+	Common::StackLock lock(*_mutex);
+
+	int r = 0;
+	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+		if (!_trigs[l].sound)
+			continue;
+
+		int opcode = _trigs[l].opcode;
+		if ((opcode == DIMUSE_C_START_SND && _trigs[l].a == soundId) ||
+			(opcode == DIMUSE_C_SWITCH_STREAM && _trigs[l].b == soundId)) {
+			r++;
+		}
+	}
+
+	for (int l = 0; l < DIMUSE_MAX_DEFERS; l++) {
+		if (!_defers[l].counter)
+			continue;
+
+		int opcode = _defers[l].opcode;
+		if ((opcode == DIMUSE_C_START_SND && _defers[l].a == soundId) ||
+			(opcode == DIMUSE_C_SWITCH_STREAM && _defers[l].b == soundId)) {
+			r++;
+		}
+	}
+
+	return r;
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_triggers.h b/engines/grim/imuse/dimuse_triggers.h
new file mode 100644
index 00000000000..6f8515f193d
--- /dev/null
+++ b/engines/grim/imuse/dimuse_triggers.h
@@ -0,0 +1,64 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef GRIM_IMUSE_TRIGGERS_H
+#define GRIM_IMUSE_TRIGGERS_H
+
+#include "common/scummsys.h"
+#include "common/textconsole.h"
+#include "common/util.h"
+#include "engines/grim/imuse/dimuse_defs.h"
+
+namespace Grim {
+
+class IMuseDigiTriggersHandler {
+
+private:
+	IMuseDigital *_engine;
+	Common::Mutex *_mutex;
+	IMuseDigiTrigger _trigs[DIMUSE_MAX_TRIGGERS] = {};
+	IMuseDigiDefer _defers[DIMUSE_MAX_DEFERS] = {};
+
+	int  _defersOn = 0;
+	int  _midProcessing = 0;
+	char _textBuffer[256] = {};
+	char _emptyMarker[1] = {};
+
+public:
+	IMuseDigiTriggersHandler(IMuseDigital *engine, Common::Mutex *mutex);
+	~IMuseDigiTriggersHandler();
+
+	int  init();
+	int  clearAllTriggers();
+	void saveLoad(Common::Serializer &ser);
+	int  setTrigger(int soundId, char *marker, int opcode, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n);
+	int  checkTrigger(int soundId, char *marker, int opcode);
+	int  clearTrigger(int soundId, char *marker, int opcode);
+	void processTriggers(int soundId, char *marker);
+	int  deferCommand(int count, int opcode, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n);
+	void loop();
+	int  countPendingSounds(int soundId);
+	int  deinit();
+
+};
+
+} // End of namespace Grim
+#endif
diff --git a/engines/grim/imuse/dimuse_utils.cpp b/engines/grim/imuse/dimuse_utils.cpp
new file mode 100644
index 00000000000..4e09b356e55
--- /dev/null
+++ b/engines/grim/imuse/dimuse_utils.cpp
@@ -0,0 +1,175 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_engine.h"
+
+namespace Grim {
+
+int IMuseDigital::addTrackToList(IMuseDigiTrack **listPtr, IMuseDigiTrack *listPtr_Item) {
+	Common::StackLock lock(*_mutex);
+
+	// [0] is ->prev, [1] is ->next
+	if (!listPtr_Item || listPtr_Item->prev || listPtr_Item->next) {
+		debug(5, "IMuseDigital::addTrackToList(): ERROR: arguments might be null");
+		return -5;
+	} else {
+		// Set item's next element to the list
+		listPtr_Item->next = *listPtr;
+
+		if (*listPtr) {
+			// If the list is empty, use this item as the list
+			(*listPtr)->prev = listPtr_Item;
+		}
+
+		// Set the previous element of the item as nullptr,
+		// effectively making the item the first element of the list
+		listPtr_Item->prev = nullptr;
+
+		// Update the list with the new data
+		*listPtr = listPtr_Item;
+
+	}
+	return 0;
+}
+
+int IMuseDigital::removeTrackFromList(IMuseDigiTrack **listPtr, IMuseDigiTrack *listPtr_Item) {
+	Common::StackLock lock(*_mutex);
+
+	IMuseDigiTrack *currentTrack = *listPtr;
+	IMuseDigiTrack *nextTrack;
+	if (listPtr_Item && currentTrack) {
+		do {
+			if (currentTrack == listPtr_Item)
+				break;
+			currentTrack = currentTrack->next;
+		} while (currentTrack);
+
+		if (currentTrack) {
+			nextTrack = listPtr_Item->next;
+
+			if (nextTrack)
+				nextTrack->prev = listPtr_Item->prev;
+
+			if (listPtr_Item->prev) {
+				listPtr_Item->prev->next = listPtr_Item->next;
+			} else {
+				*listPtr = listPtr_Item->next;
+			}
+
+			listPtr_Item->prev = nullptr;
+			listPtr_Item->next = nullptr;
+			return 0;
+		} else {
+			debug(5, "IMuseDigital::removeTrackFromList(): ERROR: item not on list");
+			return -3;
+		}
+	} else {
+		debug(5, "IMuseDigital::removeTrackFromList(): ERROR: arguments might be null");
+		return -5;
+	}
+}
+
+int IMuseDigital::addStreamZoneToList(IMuseDigiStreamZone **listPtr, IMuseDigiStreamZone *listPtr_Item) {
+	if (!listPtr_Item || listPtr_Item->prev || listPtr_Item->next) {
+		debug(5, "IMuseDigital::addStreamZoneToList(): ERROR: arguments might be null");
+		return -5;
+	} else {
+		// Set item's next element to the list
+		listPtr_Item->next = *listPtr;
+
+		if (*listPtr) {
+			// If the list is empty, use this item as the list
+			(*listPtr)->prev = listPtr_Item;
+		}
+
+		// Set the previous element of the item as nullptr,
+		// effectively making the item the first element of the list
+		listPtr_Item->prev = nullptr;
+
+		// Update the list with the new data
+		*listPtr = listPtr_Item;
+
+	}
+	return 0;
+}
+
+int IMuseDigital::removeStreamZoneFromList(IMuseDigiStreamZone **listPtr, IMuseDigiStreamZone *listPtr_Item) {
+	IMuseDigiStreamZone *currentStrZone = *listPtr;
+	IMuseDigiStreamZone *nextStrZone;
+	if (listPtr_Item && currentStrZone) {
+		do {
+			if (currentStrZone == listPtr_Item)
+				break;
+			currentStrZone = currentStrZone->next;
+		} while (currentStrZone);
+
+		if (currentStrZone) {
+			nextStrZone = listPtr_Item->next;
+
+			if (nextStrZone)
+				nextStrZone->prev = listPtr_Item->prev;
+
+			if (listPtr_Item->prev) {
+				listPtr_Item->prev->next = listPtr_Item->next;
+			} else {
+				*listPtr = listPtr_Item->next;
+			}
+
+			listPtr_Item->prev = nullptr;
+			listPtr_Item->next = nullptr;
+			return 0;
+		} else {
+			debug(5, "IMuseDigital::removeStreamZoneFromList(): ERROR: item not on list");
+			return -3;
+		}
+	} else {
+		debug(5, "IMuseDigital::removeStreamZoneFromList(): ERROR: arguments might be null");
+		return -5;
+	}
+}
+
+int IMuseDigital::clampNumber(int value, int minValue, int maxValue) {
+	if (value < minValue)
+		return minValue;
+
+	if (value > maxValue)
+		return maxValue;
+
+	return value;
+}
+
+int IMuseDigital::checkHookId(int &trackHookId, int sampleHookId) {
+	if (sampleHookId) {
+		if (trackHookId == sampleHookId) {
+			trackHookId = 0;
+			return 0;
+		} else {
+			return -1;
+		}
+	} else if (trackHookId == 128) {
+		trackHookId = 0;
+		return -1;
+	} else {
+		return 0;
+	}
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_wave.cpp b/engines/grim/imuse/dimuse_wave.cpp
new file mode 100644
index 00000000000..1daaabb3817
--- /dev/null
+++ b/engines/grim/imuse/dimuse_wave.cpp
@@ -0,0 +1,127 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_engine.h"
+
+namespace Grim {
+
+int IMuseDigital::waveInit() {
+	if (tracksInit())
+		return -1;
+	return 0;
+}
+
+int IMuseDigital::waveTerminate() {
+	return 0;
+}
+
+int IMuseDigital::wavePause() {
+	Common::StackLock lock(*_mutex);
+	tracksPause();
+	return 0;
+}
+
+int IMuseDigital::waveResume() {
+	Common::StackLock lock(*_mutex);
+	tracksResume();
+	return 0;
+}
+
+void IMuseDigital::waveSaveLoad(Common::Serializer &ser) {
+	Common::StackLock lock(*_mutex);
+	tracksSaveLoad(ser);
+}
+
+void IMuseDigital::waveUpdateGroupVolumes() {
+	Common::StackLock lock(*_mutex);
+	tracksSetGroupVol();
+}
+
+int IMuseDigital::waveStartSound(int soundId, int priority) {
+	Common::StackLock lock(*_mutex);
+	return tracksStartSound(soundId, priority, 0);
+}
+
+int IMuseDigital::waveStopSound(int soundId) {
+	Common::StackLock lock(*_mutex);
+	return tracksStopSound(soundId);
+}
+
+int IMuseDigital::waveStopAllSounds() {
+	Common::StackLock lock(*_mutex);
+	return tracksStopAllSounds();
+}
+
+int IMuseDigital::waveGetNextSound(int soundId) {
+	return tracksGetNextSound(soundId);
+}
+
+int IMuseDigital::waveSetParam(int soundId, int opcode, int value) {
+	Common::StackLock lock(*_mutex);
+	return tracksSetParam(soundId, opcode, value);
+}
+
+int IMuseDigital::waveGetParam(int soundId, int opcode) {
+	Common::StackLock lock(*_mutex);
+	return tracksGetParam(soundId, opcode);
+}
+
+int IMuseDigital::waveSetHook(int soundId, int hookId) {
+	return tracksSetHook(soundId, hookId);
+}
+
+int IMuseDigital::waveGetHook(int soundId) {
+	return tracksGetHook(soundId);
+}
+
+int IMuseDigital::waveStartStream(int soundId, int priority, int bufferId) {
+	if (soundId == 0)
+		return -1;
+
+	Common::StackLock lock(*_mutex);
+	return tracksStartSound(soundId, priority, bufferId);
+}
+
+int IMuseDigital::waveSwitchStream(int oldSoundId, int newSoundId, int fadeLengthMs, int fadeSyncFlag2, int fadeSyncFlag1) {
+	Common::StackLock lock(*_mutex);
+	return dispatchSwitchStream(oldSoundId, newSoundId, fadeLengthMs, fadeSyncFlag2, fadeSyncFlag1);
+}
+
+int IMuseDigital::waveProcessStreams() {
+	Common::StackLock lock(*_mutex);
+	return streamerProcessStreams();
+}
+
+int  IMuseDigital::waveQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
+	Common::StackLock lock(*_mutex);
+	return tracksQueryStream(soundId, bufSize, criticalSize, freeSpace, paused);
+}
+
+int IMuseDigital::waveFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused) {
+	Common::StackLock lock(*_mutex);
+	return tracksFeedStream(soundId, srcBuf, sizeToFeed, paused);
+}
+
+int IMuseDigital::waveLipSync(int soundId, int syncId, int msPos, int32 &width, int32 &height) {
+	return tracksLipSync(soundId, syncId, msPos, width, height);
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_waveout.cpp b/engines/grim/imuse/dimuse_waveout.cpp
new file mode 100644
index 00000000000..751a972088c
--- /dev/null
+++ b/engines/grim/imuse/dimuse_waveout.cpp
@@ -0,0 +1,183 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/dimuse_engine.h"
+
+namespace Grim {
+
+int IMuseDigital::waveOutInit(waveOutParamsStruct *waveOutSettingsStruct) {
+	_waveOutBytesPerSample = 2;
+	_waveOutNumChannels = _mixer->getOutputStereo() ? 2 : 1;
+	_waveOutZeroLevel = 0;
+
+	_waveOutSampleRate = _internalSampleRate;
+	_waveOutPreferredFeedSize = _internalFeedSize;
+
+	_waveOutOutputBuffer = nullptr;
+	_waveOutMixBuffer = nullptr;
+	_waveOutLowLatencyOutputBuffer = nullptr;
+
+	if (!_lowLatencyMode) {
+		// Nine buffers (waveOutPreferredFeedSize * 4 bytes each), two will be used for the mixer
+		_waveOutOutputBuffer = (uint8 *)malloc(_waveOutNumChannels * _waveOutBytesPerSample * _waveOutPreferredFeedSize * 9);
+		_waveOutMixBuffer = _waveOutOutputBuffer + (_waveOutNumChannels * _waveOutBytesPerSample * _waveOutPreferredFeedSize * 7); // 8-th buffer
+	}
+
+	// Replicate another set of buffers for the low latency mode, we will use the previous ones for cutscenes if the mode is active
+	if (_lowLatencyMode) {
+		_waveOutLowLatencyOutputBuffer = (uint8 *)malloc(_waveOutNumChannels * _waveOutBytesPerSample * _waveOutPreferredFeedSize * 9);
+	}
+
+	// This information will be fed to the internal mixer during its initialization
+	waveOutSettingsStruct->bytesPerSample = _waveOutBytesPerSample * 8;
+	waveOutSettingsStruct->numChannels = _waveOutNumChannels;
+	waveOutSettingsStruct->mixBufSize = (_waveOutBytesPerSample * _waveOutNumChannels) * _waveOutPreferredFeedSize;
+	waveOutSettingsStruct->sizeSampleKB = 0;
+	waveOutSettingsStruct->mixBuf = _waveOutMixBuffer; // Note: in low latency mode this initialization is a dummy
+
+	// Init the buffers filling them with zero volume samples
+	if (!_lowLatencyMode) {
+		memset(_waveOutOutputBuffer, _waveOutZeroLevel, _waveOutNumChannels * _waveOutBytesPerSample * _waveOutPreferredFeedSize * 9);
+	}
+
+	if (_lowLatencyMode) {
+		memset(_waveOutLowLatencyOutputBuffer, _waveOutZeroLevel, _waveOutNumChannels * _waveOutBytesPerSample * _waveOutPreferredFeedSize * 9);
+	}
+
+	_waveOutDisableWrite = 0;
+	return 0;
+}
+
+void IMuseDigital::waveOutWrite(uint8 **audioData, int &feedSize, int &sampleRate) {
+	uint8 *curBufferBlock;
+	if (_waveOutDisableWrite)
+		return;
+
+	feedSize = 0;
+
+	// A bit of context for what follows:
+	//
+	// In COMI, when entering certain rooms (e.g. barber shop in Plunder Island), the game
+	// sends a State music event followed immediately by a Sequence music event.
+	// If the iMUSE callback happens to run between these two commands, it can cause a brief
+	// audio glitch where a few milliseconds of the intermediate state music is heard
+	// before being replaced by the sequence music, with the fade in between canceled.
+	//
+	// To prevent this, we skip the very first audio callback after any music change
+	// by setting _waveOutXorTrigger to 1 in playComiMusic(). This gives the scripts
+	// enough time to send any follow-up sequence events before iMUSE processes
+	// the audio transition, ensuring the absence of glitches and most importantly
+	// no permanent audio delay on other audio feeds.
+	//
+	// This is very strongly inspired by what the disassembly does:
+	//
+	// The original DirectSound implementation uses the XOR flag combined with play
+	// cursor position checks that naturally skip audio processing cycles when the
+	// play cursor gets too close to the write cursor. In addition to this, the main
+	// portion of tracksCallback() is executed in loop until feedSide is finally 0.
+	// This creates the exact timing conditions where rapid music events have sufficient
+	// time to accumulate before iMUSE processes any audio transitions.
+	//
+	// We're not using DirectSound, so recreate this I could either simulate the
+	// play cursor handling shenanigans, or I could just do exactly what I have done :-)
+	if (_waveOutXorTrigger != 0) {
+		_waveOutXorTrigger = 0;
+		return;
+	}
+
+	if (_mixer->isReady()) {
+		curBufferBlock = &_waveOutOutputBuffer[_waveOutPreferredFeedSize * _waveOutWriteIndex * _waveOutBytesPerSample * _waveOutNumChannels];
+
+		*audioData = curBufferBlock;
+
+		sampleRate = _waveOutSampleRate;
+		feedSize = _waveOutPreferredFeedSize;
+		_waveOutWriteIndex = (_waveOutWriteIndex + 1) % 7;
+
+		byte *ptr = (byte *)malloc(_outputFeedSize * _waveOutBytesPerSample * _waveOutNumChannels);
+		memcpy(ptr, curBufferBlock, _outputFeedSize * _waveOutBytesPerSample * _waveOutNumChannels);
+
+		_internalMixer->getStream(-1)->queueBuffer(ptr,
+			_outputFeedSize * _waveOutBytesPerSample * _waveOutNumChannels,
+			DisposeAfterUse::YES,
+			waveOutGetStreamFlags());
+
+	}
+}
+
+int IMuseDigital::waveOutDeinit() {
+	_waveOutDisableWrite = 1;
+	return 0;
+}
+
+void IMuseDigital::waveOutCallback() {
+	Common::StackLock lock(*_mutex);
+	if (_lowLatencyMode) {
+		tracksLowLatencyCallback();
+	} else {
+		tracksCallback();
+	}
+}
+
+byte IMuseDigital::waveOutGetStreamFlags() {
+	byte flags = Audio::FLAG_16BITS;
+
+	if (_mixer->getOutputStereo()) {
+		flags |= Audio::FLAG_STEREO;
+	}
+
+#ifdef SCUMM_LITTLE_ENDIAN
+	flags |= Audio::FLAG_LITTLE_ENDIAN;
+#endif
+	return flags;
+}
+
+void IMuseDigital::waveOutLowLatencyWrite(uint8 **audioData, int &feedSize, int &sampleRate, int idx) {
+	uint8 *curBufferBlock;
+	if (_waveOutDisableWrite)
+		return;
+
+	feedSize = 0;
+	if (_mixer->isReady()) {
+		curBufferBlock = &_waveOutLowLatencyOutputBuffer[_waveOutPreferredFeedSize * idx * _waveOutBytesPerSample * _waveOutNumChannels];
+
+		*audioData = curBufferBlock;
+
+		sampleRate = _waveOutSampleRate;
+		feedSize = _waveOutPreferredFeedSize;
+
+		byte *ptr = (byte *)malloc(_outputFeedSize * _waveOutBytesPerSample * _waveOutNumChannels);
+		memcpy(ptr, curBufferBlock, _outputFeedSize * _waveOutBytesPerSample * _waveOutNumChannels);
+
+		_internalMixer->getStream(idx)->queueBuffer(ptr,
+			 _outputFeedSize * _waveOutBytesPerSample * _waveOutNumChannels,
+			 DisposeAfterUse::YES,
+			 waveOutGetStreamFlags());
+	}
+}
+
+void IMuseDigital::waveOutEmptyBuffer(int idx) {
+	// This is necessary in low latency mode to clean-up the buffers of stale/finished sounds
+	int bufferSize = _waveOutNumChannels * _waveOutBytesPerSample * _waveOutPreferredFeedSize;
+	memset(&_waveOutLowLatencyOutputBuffer[bufferSize * idx], _waveOutZeroLevel, bufferSize);
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/imuse_sndmgr.h b/engines/grim/imuse/imuse_sndmgr.h
index 58ad566aa8c..9ec55a7ba0a 100644
--- a/engines/grim/imuse/imuse_sndmgr.h
+++ b/engines/grim/imuse/imuse_sndmgr.h
@@ -19,8 +19,8 @@
  *
  */
 
-#ifndef GRIM_IMUSE_SNDMGR_H
-#define GRIM_IMUSE_SNDMGR_H
+#ifndef GRIM_IMUSE_OLD_SNDMGR_H
+#define GRIM_IMUSE_OLD_SNDMGR_H
 
 #include "audio/mixer.h"
 #include "audio/audiostream.h"
diff --git a/engines/grim/imuse/imuse_tables.h b/engines/grim/imuse/imuse_tables.h
index 3ef14334d6d..1cf0564208d 100644
--- a/engines/grim/imuse/imuse_tables.h
+++ b/engines/grim/imuse/imuse_tables.h
@@ -19,8 +19,8 @@
  *
  */
 
-#ifndef GRIM_IMUSE_TABLES_H
-#define GRIM_IMUSE_TABLES_H
+#ifndef GRIM_IMUSE_OLD_TABLES_H
+#define GRIM_IMUSE_OLD_TABLES_H
 
 namespace Grim {
 
diff --git a/engines/grim/module.mk b/engines/grim/module.mk
index eda8a07dd27..97319cfe7fe 100644
--- a/engines/grim/module.mk
+++ b/engines/grim/module.mk
@@ -42,6 +42,24 @@ MODULE_OBJS := \
 	emi/lua_v2_actor.o \
 	emi/lua_v2_sound.o \
 	emi/emi_registry.o \
+	imuse/dimuse_bndmgr.o \
+	imuse/dimuse_cmds.o \
+	imuse/dimuse_codecs.o \
+	imuse/dimuse_dispatch.o \
+	imuse/dimuse_engine.o \
+	imuse/dimuse_fades.o \
+	imuse/dimuse_files.o \
+	imuse/dimuse_groups.o \
+	imuse/dimuse_internalmixer.o \
+	imuse/dimuse_scripts.o \
+	imuse/dimuse_sndmgr.o \
+	imuse/dimuse_streamer.o \
+	imuse/dimuse_tables.o \
+	imuse/dimuse_tracks.o \
+	imuse/dimuse_triggers.o \
+	imuse/dimuse_utils.o \
+	imuse/dimuse_wave.o \
+	imuse/dimuse_waveout.o \
 	imuse/imuse.o \
 	imuse/imuse_mcmp_mgr.o \
 	imuse/imuse_music.o \


Commit: 879b900f0e7f83944cb87e75062f8d0f7b4019b7
    https://github.com/scummvm/scummvm/commit/879b900f0e7f83944cb87e75062f8d0f7b4019b7
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Port GRIM differences on SCUMM-derived iMUSE code

Changed paths:
    engines/grim/imuse/dimuse_defs.h
    engines/grim/imuse/dimuse_dispatch.cpp
    engines/grim/imuse/dimuse_engine.cpp
    engines/grim/imuse/dimuse_engine.h
    engines/grim/imuse/dimuse_fades.cpp
    engines/grim/imuse/dimuse_groups.cpp
    engines/grim/imuse/dimuse_groups.h
    engines/grim/imuse/dimuse_streamer.cpp
    engines/grim/imuse/dimuse_tracks.cpp
    engines/grim/imuse/dimuse_triggers.cpp
    engines/grim/imuse/dimuse_wave.cpp


diff --git a/engines/grim/imuse/dimuse_defs.h b/engines/grim/imuse/dimuse_defs.h
index 37027c5a41b..3ff243b0f87 100644
--- a/engines/grim/imuse/dimuse_defs.h
+++ b/engines/grim/imuse/dimuse_defs.h
@@ -199,14 +199,6 @@ struct IMuseDigiTrack {
 	int pitchShift;
 	int mailbox;
 	int jumpHook;
-	int32 syncSize_0;
-	byte *syncPtr_0;
-	int32 syncSize_1;
-	byte *syncPtr_1;
-	int32 syncSize_2;
-	byte *syncPtr_2;
-	int32 syncSize_3;
-	byte *syncPtr_3;
 };
 
 struct IMuseDigiStreamZone {
diff --git a/engines/grim/imuse/dimuse_dispatch.cpp b/engines/grim/imuse/dimuse_dispatch.cpp
index 6044890d6a4..8541e9b824b 100644
--- a/engines/grim/imuse/dimuse_dispatch.cpp
+++ b/engines/grim/imuse/dimuse_dispatch.cpp
@@ -716,53 +716,7 @@ int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
 
 			continue;
 		case MKTAG('S', 'Y', 'N', 'C'):
-		{
-			// SYNC block (fixed size: x bytes)
-			// - The tag 'SYNC' (4 bytes)
-			// - SYNC size in bytes (4 bytes)
-			// - SYNC data (variable length)
-
-			// It is possible to gather a total maximum of 4 SYNCs for a single track;
-			// this is not a problem however, as speech files only have one SYNC block,
-			// and the most we get is four (one for each character) in
-			// A Pirate I Was Meant To Be, in Part 3 of COMI
-
-			// Curiously we skip the first four bytes of data, ending up having the first
-			// four bytes of the next block in our syncPtr; but this is exactly what happens
-			// within the interpreter, so I'm not going to argue with it
-
-			int32 targetSyncSize = READ_UINT32(mapCurEvent + 4); // As per specifications above, we fetch the size
-			uint8 *mapEventStart = mapCurEvent + 4 + 4 + 4; // We skip the 'SYNC' tag, the size, and an additional 4-bytes dword
-
-			// Allocate space for the data block and fill it, 4 bytes at a time...
-			byte *syncData = (byte *)malloc(targetSyncSize);
-			uint32 *syncDwordPtr = (uint32 *)syncData;
-			uint32 *mapEventsDwordPtr = (uint32 *)mapEventStart;
-			if (syncData) {
-				for (int i = 0; i < (targetSyncSize >> 2); i++) {
-					WRITE_LE_UINT32(&syncDwordPtr[i], mapEventsDwordPtr[i]);
-				}
-			}
-
-			if (!dispatchPtr->trackPtr->syncPtr_0) {
-				dispatchPtr->trackPtr->syncPtr_0 = syncData;
-				dispatchPtr->trackPtr->syncSize_0 = targetSyncSize;
-
-			} else if (!dispatchPtr->trackPtr->syncPtr_1) {
-				dispatchPtr->trackPtr->syncPtr_1 = syncData;
-				dispatchPtr->trackPtr->syncSize_1 = targetSyncSize;
-
-			} else if (!dispatchPtr->trackPtr->syncPtr_2) {
-				dispatchPtr->trackPtr->syncPtr_2 = syncData;
-				dispatchPtr->trackPtr->syncSize_2 = targetSyncSize;
-
-			} else if (!dispatchPtr->trackPtr->syncPtr_3) {
-				dispatchPtr->trackPtr->syncPtr_3 = syncData;
-				dispatchPtr->trackPtr->syncSize_3 = targetSyncSize;
-			}
-
 			continue;
-		}
 		case MKTAG('F', 'R', 'M', 'T'):
 			// Format block (fixed size: 28 bytes)
 			// - The tag 'FRMT' (4 bytes)
diff --git a/engines/grim/imuse/dimuse_engine.cpp b/engines/grim/imuse/dimuse_engine.cpp
index 6138ad7acae..08c3b69763c 100644
--- a/engines/grim/imuse/dimuse_engine.cpp
+++ b/engines/grim/imuse/dimuse_engine.cpp
@@ -353,71 +353,6 @@ int32 IMuseDigital::getCurMusicPosInMs() {
 	return diMUSEGetParam(soundId, DIMUSE_P_SND_POS_IN_MS);
 }
 
-int32 IMuseDigital::getCurVoiceLipSyncWidth() {
-	int32 width, height;
-	getSpeechLipSyncInfo(width, height);
-	return width;
-}
-
-int32 IMuseDigital::getCurVoiceLipSyncHeight() {
-	int32 width, height;
-	getSpeechLipSyncInfo(width, height);
-	return height;
-}
-
-int32 IMuseDigital::getCurMusicLipSyncWidth(int syncId) {
-	int32 width, height;
-	getMusicLipSyncInfo(syncId, width, height);
-	return width;
-}
-
-int32 IMuseDigital::getCurMusicLipSyncHeight(int syncId) {
-	int32 width, height;
-	getMusicLipSyncInfo(syncId, width, height);
-	return height;
-}
-
-void IMuseDigital::getSpeechLipSyncInfo(int32 &width, int32 &height) {
-	int curSpeechPosInMs;
-
-	width = 0;
-	height = 0;
-
-	if (diMUSEGetParam(kTalkSoundID, DIMUSE_P_SND_TRACK_NUM) > 0) {
-		curSpeechPosInMs = diMUSEGetParam(kTalkSoundID, DIMUSE_P_SND_POS_IN_MS);
-		// TODO
-		// diMUSELipSync(kTalkSoundID, 0, _vm->VAR(_vm->VAR_SYNC) + curSpeechPosInMs + 50, width, height);
-	}
-}
-
-void IMuseDigital::getMusicLipSyncInfo(int syncId, int32 &width, int32 &height) {
-	int soundId;
-	int speechSoundId;
-	int curSpeechPosInMs;
-
-	soundId = 0;
-	speechSoundId = 0;
-	width = 0;
-	height = 0;
-	while (1) {
-		soundId = diMUSEGetNextSound(soundId);
-		if (!soundId)
-			break;
-		if (diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM)) {
-			if (diMUSEGetParam(soundId, DIMUSE_P_STREAM_BUFID) == DIMUSE_BUFFER_MUSIC) {
-				speechSoundId = soundId;
-				break;
-			}
-		}
-	}
-
-	if (speechSoundId) {
-		curSpeechPosInMs = diMUSEGetParam(speechSoundId, DIMUSE_P_SND_POS_IN_MS);
-		// TODO
-		// diMUSELipSync(speechSoundId, syncId, _vm->VAR(_vm->VAR_SYNC) + curSpeechPosInMs + 50, width, height);
-	}
-}
-
 int32 IMuseDigital::getSoundElapsedTimeInMs(int soundId) {
 	if (diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM)) {
 		return diMUSEGetParam(soundId, DIMUSE_P_SND_POS_IN_MS);
@@ -579,10 +514,6 @@ int IMuseDigital::diMUSEFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed,
 	return cmdsHandleCmd(DIMUSE_C_FEED_STREAM, srcBuf, soundId, -1, sizeToFeed, paused);
 }
 
-int IMuseDigital::diMUSELipSync(int soundId, int syncId, int msPos, int32 &width, int32 &height) {
-	return waveLipSync(soundId, syncId, msPos, width, height);
-}
-
 int IMuseDigital::diMUSEGetMusicGroupVol() {
 	// TODO
 	// if (_vm->isUsingOriginalGUI()) {
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/dimuse_engine.h
index ed51b6ba51d..29c6130b80f 100644
--- a/engines/grim/imuse/dimuse_engine.h
+++ b/engines/grim/imuse/dimuse_engine.h
@@ -185,7 +185,6 @@ private:
 	void tracksClear(IMuseDigiTrack *trackPtr);
 	int tracksSetParam(int soundId, int opcode, int value);
 	int tracksGetParam(int soundId, int opcode);
-	int tracksLipSync(int soundId, int syncId, int msPos, int32 &width, int32 &height);
 	int tracksSetHook(int soundId, int hookId);
 	int tracksGetHook(int soundId);
 	IMuseDigiTrack *tracksReserveTrack(int priority);
@@ -254,7 +253,6 @@ private:
 	int waveProcessStreams();
 	int waveQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
 	int waveFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused);
-	int waveLipSync(int soundId, int syncId, int msPos, int32 &width, int32 &height);
 
 	// Waveapi
 	waveOutParamsStruct waveOutSettings;
@@ -310,12 +308,6 @@ public:
 	int getFeedSize();
 
 	int32 getCurMusicPosInMs();
-	int32 getCurVoiceLipSyncWidth();
-	int32 getCurVoiceLipSyncHeight();
-	int32 getCurMusicLipSyncWidth(int syncId);
-	int32 getCurMusicLipSyncHeight(int syncId);
-	void getSpeechLipSyncInfo(int32 &width, int32 &height);
-	void getMusicLipSyncInfo(int syncId, int32 &width, int32 &height);
 	int32 getSoundElapsedTimeInMs(int soundId);
 
 	// General engine functions
@@ -344,7 +336,6 @@ public:
 	int diMUSEProcessStreams();
 	int diMUSEQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
 	int diMUSEFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused);
-	int diMUSELipSync(int soundId, int syncId, int msPos, int32 &width, int32 &height);
 	int diMUSEGetMusicGroupVol();
 	int diMUSEGetSFXGroupVol();
 	int diMUSEGetVoiceGroupVol();
diff --git a/engines/grim/imuse/dimuse_fades.cpp b/engines/grim/imuse/dimuse_fades.cpp
index 0c4aeb473f5..21bfacb3706 100644
--- a/engines/grim/imuse/dimuse_fades.cpp
+++ b/engines/grim/imuse/dimuse_fades.cpp
@@ -42,12 +42,14 @@ int IMuseDigiFadesHandler::fadeParam(int soundId, int opcode, int destinationVal
 	if (!soundId || fadeLength < 0)
 		return -5;
 
-	if (opcode != DIMUSE_P_PRIORITY && opcode != DIMUSE_P_VOLUME && opcode != DIMUSE_P_PAN && opcode != DIMUSE_P_DETUNE && opcode != DIMUSE_P_UNKNOWN && opcode != 17)
+	if (opcode != DIMUSE_P_PRIORITY && opcode != DIMUSE_P_VOLUME && opcode != DIMUSE_P_PAN && opcode != DIMUSE_P_DETUNE)
 		return -5;
 
 	clearFadeStatus(soundId, opcode);
 
-	if (!fadeLength) {
+	int len50HzTicks = 5 * fadeLength / 6;
+
+	if (!len50HzTicks) {
 		debug(5, "IMuseDigiFadesHandler::fadeParam(): WARNING: allocated fade with zero length for sound %d", soundId);
 		if (opcode != DIMUSE_P_VOLUME || destinationValue) {
 			_engine->diMUSESetParam(soundId, opcode, destinationValue);
@@ -63,19 +65,19 @@ int IMuseDigiFadesHandler::fadeParam(int soundId, int opcode, int destinationVal
 			_fades[l].sound = soundId;
 			_fades[l].param = opcode;
 			_fades[l].currentVal = _engine->diMUSEGetParam(soundId, opcode);
-			_fades[l].length = fadeLength;
-			_fades[l].counter = fadeLength;
-			_fades[l].slope = (destinationValue - _fades[l].currentVal) / fadeLength;
+			_fades[l].length = len50HzTicks;
+			_fades[l].counter = len50HzTicks;
+			_fades[l].slope = (destinationValue - _fades[l].currentVal) / len50HzTicks;
 			_fades[l].modOvfloCounter = 0;
 			_fades[l].status = 1;
 			_fadesOn = 1;
 
 			if ((destinationValue - _fades[l].currentVal) < 0) {
 				_fades[l].nudge = -1;
-				_fades[l].slopeMod = (-(destinationValue - _fades[l].currentVal) % fadeLength);
+				_fades[l].slopeMod = (-(destinationValue - _fades[l].currentVal) % len50HzTicks);
 			} else {
 				_fades[l].nudge = 1;
-				_fades[l].slopeMod = (destinationValue - _fades[l].currentVal) % fadeLength;
+				_fades[l].slopeMod = (destinationValue - _fades[l].currentVal) % len50HzTicks;
 			}
 
 			return 0;
@@ -121,7 +123,7 @@ void IMuseDigiFadesHandler::loop() {
 			if (_fades[l].currentVal != currentVolume) {
 				_fades[l].currentVal = currentVolume;
 
-				if (!(_fades[l].counter % 6)) {
+				if (!(_fades[l].counter % 5)) {
 					debug(5, "IMuseDigiFadesHandler::loop(): running fade for sound %d with id %d, currently at volume %d", _fades[l].sound, l, currentVolume);
 					if ((_fades[l].param != DIMUSE_P_VOLUME) || currentVolume) {
 						_engine->diMUSESetParam(_fades[l].sound, _fades[l].param, currentVolume);
diff --git a/engines/grim/imuse/dimuse_groups.cpp b/engines/grim/imuse/dimuse_groups.cpp
index 77e42de3fb3..79e95c8c152 100644
--- a/engines/grim/imuse/dimuse_groups.cpp
+++ b/engines/grim/imuse/dimuse_groups.cpp
@@ -39,7 +39,7 @@ int IMuseDigiGroupsHandler::init() {
 	return 0;
 }
 
-int IMuseDigiGroupsHandler::setGroupVol(int id, int volume) {
+int IMuseDigiGroupsHandler::setGroupVol(uint32 id, int volume) {
 	Common::StackLock lock(*_mutex);
 
 	int l;
@@ -52,9 +52,11 @@ int IMuseDigiGroupsHandler::setGroupVol(int id, int volume) {
 		return _vols[id];
 	}
 
-	if (volume > 127)
+	if (volume < 0 || volume > 127)
 		return -5;
 
+	int oldVolume = _vols[id];
+
 	if (id) {
 		_vols[id] = volume;
 		_effVols[id] = (_vols[0] * (volume + 1)) / 128;
@@ -68,10 +70,10 @@ int IMuseDigiGroupsHandler::setGroupVol(int id, int volume) {
 	}
 
 	_engine->diMUSEUpdateGroupVolumes();
-	return _vols[id];
+	return oldVolume;
 }
 
-int IMuseDigiGroupsHandler::getGroupVol(int id) {
+int IMuseDigiGroupsHandler::getGroupVol(uint32 id) {
 	Common::StackLock lock(*_mutex);
 
 	if (id >= DIMUSE_MAX_GROUPS) {
diff --git a/engines/grim/imuse/dimuse_groups.h b/engines/grim/imuse/dimuse_groups.h
index 512a0c82f58..cd16fe7d3ae 100644
--- a/engines/grim/imuse/dimuse_groups.h
+++ b/engines/grim/imuse/dimuse_groups.h
@@ -42,8 +42,8 @@ public:
 	IMuseDigiGroupsHandler(IMuseDigital *engine, Common::Mutex *mutex);
 	~IMuseDigiGroupsHandler();
 	int init();
-	int setGroupVol(int id, int volume);
-	int getGroupVol(int id);
+	int setGroupVol(uint32 id, int volume);
+	int getGroupVol(uint32 id);
 };
 
 } // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_streamer.cpp b/engines/grim/imuse/dimuse_streamer.cpp
index 1ad808cd3a0..ea7f6963ca9 100644
--- a/engines/grim/imuse/dimuse_streamer.cpp
+++ b/engines/grim/imuse/dimuse_streamer.cpp
@@ -87,14 +87,12 @@ int IMuseDigital::streamerProcessStreams() {
 
 	for (int l = 0; l < DIMUSE_MAX_STREAMS; l++) {
 		if ((_streams[l].soundId) && (!_streams[l].paused)) {
-			if (stream2) {
-				if (stream1) {
-					debug(5, "IMuseDigital::streamerProcessStreams(): WARNING: three streams in use");
-				} else {
-					stream1 = &_streams[l];
+			if (stream1) {
+				if (!stream2) {
+					stream2 = &_streams[l];
 				}
 			} else {
-				stream2 = &_streams[l];
+				stream1 = &_streams[l];
 			}
 		}
 	}
@@ -152,7 +150,7 @@ uint8 *IMuseDigital::streamerGetStreamBuffer(IMuseDigiStream *streamPtr, int siz
 	if (size > streamPtr->bufFreeSize - streamPtr->readIndex) {
 		memcpy(&streamPtr->buf[streamPtr->bufFreeSize],
 			streamPtr->buf,
-			size - streamPtr->bufFreeSize + streamPtr->readIndex + 4);
+			size - streamPtr->bufFreeSize + streamPtr->readIndex);
 	}
 
 	int32 readIndex_tmp = streamPtr->readIndex;
@@ -237,20 +235,8 @@ int IMuseDigital::streamerFeedStream(IMuseDigiStream *streamPtr, uint8 *srcBuf,
 	if (size <= 0)
 		size += streamPtr->bufFreeSize;
 	if (sizeToFeed > (size - 4)) {
-		// Don't worry, judging from the intro of The Dig, this is totally expected
-		// to happen, and when it does, the output matches the EXE behavior
 		debug(5, "IMuseDigital::streamerFeedStream(): WARNING: buffer overflow");
-		_streamerBailFlag = 1;
-
-		int32 newTentativeSize = sizeToFeed - (size - 4) - (sizeToFeed - (size - 4)) % 12 + 12;
-		size = streamPtr->loadIndex - streamPtr->readIndex;
-		if (size < 0)
-			size += streamPtr->bufFreeSize;
-		if (size >= newTentativeSize) {
-			streamPtr->readIndex = newTentativeSize + streamPtr->readIndex;
-			if (streamPtr->bufFreeSize <= streamPtr->readIndex)
-				streamPtr->readIndex -= streamPtr->bufFreeSize;
-		}
+		streamerSetReadIndex(streamPtr, sizeToFeed - (size - 4) - (sizeToFeed - (size - 4)) % 12 + 12);
 	}
 
 	if (sizeToFeed > 0) {
@@ -298,61 +284,54 @@ int IMuseDigital::streamerFetchData(IMuseDigiStream *streamPtr) {
 
 	if (remainingSize <= 0) {
 		streamPtr->paused = 1;
-
-		// Pad the buffer
-		streamPtr->buf[streamPtr->loadIndex] = 127;
-		streamPtr->loadIndex++;
-		streamPtr->buf[streamPtr->loadIndex] = 127;
-		streamPtr->loadIndex++;
-		streamPtr->buf[streamPtr->loadIndex] = 127;
-		streamPtr->loadIndex++;
-		streamPtr->buf[streamPtr->loadIndex] = 127;
-		streamPtr->loadIndex++;
 	}
 
 	int32 actualAmount;
 	int32 requestedAmount;
 
-	while (1) {
-		if (loadSize <= 0)
-			return 0;
+	if (loadSize > 0) {
+		while (1) {
+			requestedAmount = streamPtr->bufFreeSize - streamPtr->loadIndex;
+			if (requestedAmount >= loadSize) {
+				requestedAmount = loadSize;
+			}
 
-		requestedAmount = streamPtr->bufFreeSize - streamPtr->loadIndex;
-		if (requestedAmount >= loadSize) {
-			requestedAmount = loadSize;
-		}
+			if (_filesHandler->seek(streamPtr->soundId, streamPtr->curOffset, SEEK_SET, streamPtr->bufId) != streamPtr->curOffset) {
+				debug(5, "IMuseDigital::streamerFetchData(): ERROR: invalid seek in streamer (%d), pausing stream...", streamPtr->curOffset);
+				streamPtr->paused = 1;
+				return 0;
+			}
 
-		if (_filesHandler->seek(streamPtr->soundId, streamPtr->curOffset, SEEK_SET, streamPtr->bufId) != streamPtr->curOffset) {
-			debug(5, "IMuseDigital::streamerFetchData(): ERROR: invalid seek in streamer (%d), pausing stream...", streamPtr->curOffset);
-			streamPtr->paused = 1;
-			return 0;
-		}
+			_streamerBailFlag = 0;
+
+			_mutex->lock();
+			actualAmount = _filesHandler->read(streamPtr->soundId, &streamPtr->buf[streamPtr->loadIndex], requestedAmount, streamPtr->bufId);
+			_mutex->unlock();
 
-		_streamerBailFlag = 0;
+			if (_streamerBailFlag)
+				return 0;
 
-		_mutex->lock();
-		actualAmount = _filesHandler->read(streamPtr->soundId, &streamPtr->buf[streamPtr->loadIndex], requestedAmount, streamPtr->bufId);
-		_mutex->unlock();
+			loadSize -= actualAmount;
+			streamPtr->curOffset += actualAmount;
+			_lastStreamLoaded = streamPtr;
 
-		if (_streamerBailFlag)
-			return 0;
+			int32 newLoadIndex = actualAmount + streamPtr->loadIndex;
+			streamPtr->loadIndex = newLoadIndex;
+			if (newLoadIndex >= streamPtr->bufFreeSize) {
+				streamPtr->loadIndex = newLoadIndex - streamPtr->bufFreeSize;
+			}
 
-		loadSize -= actualAmount;
-		streamPtr->curOffset += actualAmount;
-		_lastStreamLoaded = streamPtr;
+			if (actualAmount != requestedAmount)
+				break;
 
-		int32 newLoadIndex = actualAmount + streamPtr->loadIndex;
-		streamPtr->loadIndex = newLoadIndex;
-		if (newLoadIndex >= streamPtr->bufFreeSize) {
-			streamPtr->loadIndex = newLoadIndex - streamPtr->bufFreeSize;
+			if (loadSize <= 0)
+				return 0;
 		}
 
-		if (actualAmount != requestedAmount)
-			break;
+		debug(5, "IMuseDigital::streamerFetchData(): ERROR: unable to load the correct amount of data (req=%d, act=%d)", requestedAmount, actualAmount);
+		_lastStreamLoaded = nullptr;
 	}
 
-	debug(5, "IMuseDigital::streamerFetchData(): ERROR: unable to load the correct amount of data (req=%d, act=%d)", requestedAmount, actualAmount);
-	_lastStreamLoaded = nullptr;
 	return 0;
 }
 
diff --git a/engines/grim/imuse/dimuse_tracks.cpp b/engines/grim/imuse/dimuse_tracks.cpp
index 84eb4f8f7f6..11dd20873a2 100644
--- a/engines/grim/imuse/dimuse_tracks.cpp
+++ b/engines/grim/imuse/dimuse_tracks.cpp
@@ -24,7 +24,7 @@
 namespace Grim {
 
 int IMuseDigital::tracksInit() {
-	_trackCount = _lowLatencyMode ? DIMUSE_MAX_TRACKS : 6;
+	_trackCount = DIMUSE_MAX_TRACKS;
 	_tracksPauseTimer = 0;
 	_trackList = nullptr;
 
@@ -60,14 +60,6 @@ int IMuseDigital::tracksInit() {
 		_tracks[l].pitchShift = 0;
 		_tracks[l].mailbox = 0;
 		_tracks[l].jumpHook = 0;
-		_tracks[l].syncSize_0 = 0;
-		_tracks[l].syncSize_1 = 0;
-		_tracks[l].syncSize_2 = 0;
-		_tracks[l].syncSize_3 = 0;
-		_tracks[l].syncPtr_0 = nullptr;
-		_tracks[l].syncPtr_1 = nullptr;
-		_tracks[l].syncPtr_2 = nullptr;
-		_tracks[l].syncPtr_3 = nullptr;
 	}
 
 	return 0;
@@ -98,35 +90,6 @@ void IMuseDigital::tracksSaveLoad(Common::Serializer &ser) {
 		ser.syncAsSint32LE(_tracks[l].pitchShift, VER(103));
 		ser.syncAsSint32LE(_tracks[l].mailbox, VER(103));
 		ser.syncAsSint32LE(_tracks[l].jumpHook, VER(103));
-
-		ser.syncAsSint32LE(_tracks[l].syncSize_0, VER(103));
-		ser.syncAsSint32LE(_tracks[l].syncSize_1, VER(103));
-		ser.syncAsSint32LE(_tracks[l].syncSize_2, VER(103));
-		ser.syncAsSint32LE(_tracks[l].syncSize_3, VER(103));
-
-		if (_tracks[l].syncSize_0) {
-			if (ser.isLoading())
-				_tracks[l].syncPtr_0 = (byte *)malloc(_tracks[l].syncSize_0);
-			ser.syncArray(_tracks[l].syncPtr_0, _tracks[l].syncSize_0, Common::Serializer::Byte, VER(103));
-		}
-
-		if (_tracks[l].syncSize_1) {
-			if (ser.isLoading())
-				_tracks[l].syncPtr_1 = (byte *)malloc(_tracks[l].syncSize_1);
-			ser.syncArray(_tracks[l].syncPtr_1, _tracks[l].syncSize_1, Common::Serializer::Byte, VER(103));
-		}
-
-		if (_tracks[l].syncSize_2) {
-			if (ser.isLoading())
-				_tracks[l].syncPtr_2 = (byte *)malloc(_tracks[l].syncSize_2);
-			ser.syncArray(_tracks[l].syncPtr_2, _tracks[l].syncSize_2, Common::Serializer::Byte, VER(103));
-		}
-
-		if (_tracks[l].syncSize_3) {
-			if (ser.isLoading())
-				_tracks[l].syncPtr_3 = (byte *)malloc(_tracks[l].syncSize_3);
-			ser.syncArray(_tracks[l].syncPtr_3, _tracks[l].syncSize_3, Common::Serializer::Byte, VER(103));
-		}
 	}
 
 	if (ser.isLoading()) {
@@ -299,14 +262,6 @@ int IMuseDigital::tracksStartSound(int soundId, int tryPriority, int group) {
 	allocatedTrack->pitchShift = 256;
 	allocatedTrack->mailbox = 0;
 	allocatedTrack->jumpHook = 0;
-	allocatedTrack->syncSize_0 = 0;
-	allocatedTrack->syncPtr_0 = nullptr;
-	allocatedTrack->syncSize_1 = 0;
-	allocatedTrack->syncPtr_1 = nullptr;
-	allocatedTrack->syncSize_2 = 0;
-	allocatedTrack->syncPtr_2 = nullptr;
-	allocatedTrack->syncSize_3 = 0;
-	allocatedTrack->syncPtr_3 = nullptr;
 
 	if (dispatchAllocateSound(allocatedTrack, group)) {
 		debug(5, "IMuseDigital::tracksStartSound(): ERROR: dispatch couldn't start sound %d", soundId);
@@ -327,16 +282,18 @@ int IMuseDigital::tracksStopSound(int soundId) {
 
 	IMuseDigiTrack *nextTrack = _trackList;
 	IMuseDigiTrack *curTrack;
+	int result = -1;
 
 	while (nextTrack) {
 		curTrack = nextTrack;
 		nextTrack = curTrack->next;
 		if (curTrack->soundId == soundId) {
 			tracksClear(curTrack);
+			result = 0;
 		}
 	}
 
-	return 0;
+	return result;
 }
 
 int IMuseDigital::tracksStopAllSounds() {
@@ -412,30 +369,6 @@ int IMuseDigital::tracksFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed,
 void IMuseDigital::tracksClear(IMuseDigiTrack *trackPtr) {
 	Common::StackLock lock(*_mutex);
 
-	if (trackPtr->syncPtr_0) {
-		trackPtr->syncSize_0 = 0;
-		free(trackPtr->syncPtr_0);
-		trackPtr->syncPtr_0 = nullptr;
-	}
-
-	if (trackPtr->syncPtr_1) {
-		trackPtr->syncSize_1 = 0;
-		free(trackPtr->syncPtr_1);
-		trackPtr->syncPtr_1 = nullptr;
-	}
-
-	if (trackPtr->syncPtr_2) {
-		trackPtr->syncSize_2 = 0;
-		free(trackPtr->syncPtr_2);
-		trackPtr->syncPtr_2 = nullptr;
-	}
-
-	if (trackPtr->syncPtr_3) {
-		trackPtr->syncSize_3 = 0;
-		free(trackPtr->syncPtr_3);
-		trackPtr->syncPtr_3 = nullptr;
-	}
-
 	removeTrackFromList(&_trackList, trackPtr);
 	dispatchRelease(trackPtr);
 	_fadesHandler->clearFadeStatus(trackPtr->soundId, -1);
@@ -520,14 +453,13 @@ int IMuseDigital::tracksGetParam(int soundId, int opcode) {
 	IMuseDigiTrack *track = _trackList;
 	int l = 0;
 	do {
-		if (track)
-			l++;
 		if (track->soundId == soundId) {
 			switch (opcode) {
 			case DIMUSE_P_BOGUS_ID:
 				return -1;
 			case DIMUSE_P_SND_TRACK_NUM:
-				return l;
+				l++;
+				break;
 			case DIMUSE_P_TRIGS_SNDS:
 				return -1;
 			case DIMUSE_P_MARKER:
@@ -566,97 +498,10 @@ int IMuseDigital::tracksGetParam(int soundId, int opcode) {
 		track = track->next;
 	} while (track);
 
-	return 0;
-}
-
-int IMuseDigital::tracksLipSync(int soundId, int syncId, int msPos, int32 &width, int32 &height) {
-	int32 w, h;
-
-	byte *syncPtr = nullptr;
-	int32 syncSize = 0;
-
-	IMuseDigiTrack *curTrack;
-	int16 val;
-
-	w = 0;
-	h = 0;
-	curTrack = _trackList;
-
-	if (msPos >= 0) {
-		// Check for an invalid timestamp:
-		// this has to be a suitable 2-bytes word...
-		if (((msPos >> 4) & 0xFFFF0000) != 0) {
-			return -5;
-		} else {
-			if (_trackList) {
-				do {
-					if (curTrack->soundId == soundId)
-						break;
-					curTrack = curTrack->next;
-				} while (curTrack);
-			}
-
-			if (curTrack) {
-				if (syncId >= 0 && syncId < 4) {
-					if (syncId == 0) {
-						syncPtr = curTrack->syncPtr_0;
-						syncSize = curTrack->syncSize_0;
-					} else if (syncId == 1) {
-						syncPtr = curTrack->syncPtr_1;
-						syncSize = curTrack->syncSize_1;
-					} else if (syncId == 2) {
-						syncPtr = curTrack->syncPtr_2;
-						syncSize = curTrack->syncSize_2;
-					} else if (syncId == 3) {
-						syncPtr = curTrack->syncPtr_3;
-						syncSize = curTrack->syncSize_3;
-					}
-
-					if (syncSize && syncPtr) {
-						// SYNC data is packed in a number of 4-bytes entries, in the following order:
-						// - Width and height values, packed as one byte each, next to each other;
-						// - The time position of said values, packed as an unsigned word (2-bytes).
-
-						// Given an input timestamp (in ms), we're going to get its representation as 60Hz
-						// increments by dividing it by 16, then we're going to search the SYNC data from
-						// the beginning to find the first entry with a timestamp being equal or greater
-						// our 60Hz timestamp.
-						uint16 inputTs = msPos >> 4;
-						int32 numOfEntries = (syncSize >> 2);
-						uint16 *syncDataWordPtr = (uint16 *)syncPtr;
-						uint16 curEntryTs = 0;
-						int idx;
-						for (idx = 0; idx < numOfEntries; idx++) {
-							curEntryTs = READ_LE_UINT16(&syncDataWordPtr[idx * 2 + 1]);
-							if (curEntryTs >= inputTs) {
-								break;
-							}
-						}
-
-						// If no relevant entry is found, or if the found entry timestamp is strictly greater
-						// than ours, then we get the previous entry. If no entry was found, this will get the
-						// last entry in our data block.
-						if (idx == numOfEntries || curEntryTs > inputTs) {
-							idx--;
-						}
-
-						// Finally, extract width and height values and remove
-						// their signs by performing AND operations with 0x7F...
-						val = READ_LE_INT16(&syncDataWordPtr[idx * 2]);
-						w = (val >> 8) & 0x7F;
-						h = val & 0x7F;
-					}
-				}
-			} else {
-				return -4;
-			}
-		}
-	}
-
-	width = w;
-	height = h;
+	if (opcode != DIMUSE_P_SND_TRACK_NUM)
+		return -4;
 
-	return 0;
+	return l;
 }
 
 int IMuseDigital::tracksSetHook(int soundId, int hookId) {
@@ -698,9 +543,8 @@ IMuseDigiTrack *IMuseDigital::tracksReserveTrack(int priority) {
 
 	// Pick the track from the pool of free tracks
 	for (int i = 0; i < _trackCount; i++) {
-		reservedTrack = &_tracks[i];
-		if (!reservedTrack->soundId) {
-			return reservedTrack;
+		if (!_tracks[i].soundId) {
+			return &_tracks[i];
 		}
 	}
 
@@ -715,9 +559,10 @@ IMuseDigiTrack *IMuseDigital::tracksReserveTrack(int priority) {
 
 	if (reservedTrack && priority >= minPriorityFound) {
 		tracksClear(reservedTrack);
+		return reservedTrack;
 	}
 
-	return reservedTrack;
+	return nullptr;
 }
 
 void IMuseDigital::tracksDeinit() {
diff --git a/engines/grim/imuse/dimuse_triggers.cpp b/engines/grim/imuse/dimuse_triggers.cpp
index 3b4776f0bec..725143e8aad 100644
--- a/engines/grim/imuse/dimuse_triggers.cpp
+++ b/engines/grim/imuse/dimuse_triggers.cpp
@@ -229,13 +229,11 @@ void IMuseDigiTriggersHandler::processTriggers(int soundId, char *marker) {
 			_engine->scriptTriggerCallback(_textBuffer);
 		} else {
 			if (_trigs[l].opcode < 30) {
-				// Execute a command
+				// Execute a command (the same argument on all slots is intentional)
+				int lastArg = _trigs[l].j;
 				_engine->cmdsHandleCmd(_trigs[l].opcode, (uint8 *)textBuffer,
-					_trigs[l].a, _trigs[l].b,
-					_trigs[l].c, _trigs[l].d,
-					_trigs[l].e, _trigs[l].f,
-					_trigs[l].g, _trigs[l].h,
-					_trigs[l].i, _trigs[l].j);
+					lastArg, lastArg, lastArg, lastArg, lastArg,
+					lastArg, lastArg, lastArg, lastArg, lastArg);
 			}
 		}
 
@@ -299,17 +297,15 @@ void IMuseDigiTriggersHandler::loop() {
 		_defersOn = 1;
 		_defers[l].counter--;
 
-		if (_defers[l].counter == 1) {
+		if (_defers[l].counter == 0) {
 			if (_defers[l].opcode == DIMUSE_C_SCRIPT_CALLBACK) {
-				_engine->scriptTriggerCallback(_trigs[l].text);
+				_engine->scriptTriggerCallback(_emptyMarker);
 			} else {
 				if (_defers[l].opcode < 30) {
-					_engine->cmdsHandleCmd(_trigs[l].opcode, nullptr,
-						_trigs[l].a, _trigs[l].b,
-						_trigs[l].c, _trigs[l].d,
-						_trigs[l].e, _trigs[l].f,
-						_trigs[l].g, _trigs[l].h,
-						_trigs[l].i, _trigs[l].j);
+					int lastArg = _defers[l].j;
+					_engine->cmdsHandleCmd(_defers[l].opcode, nullptr,
+						lastArg, lastArg, lastArg, lastArg, lastArg,
+						lastArg, lastArg, lastArg, lastArg, lastArg);
 				}
 			}
 		}
diff --git a/engines/grim/imuse/dimuse_wave.cpp b/engines/grim/imuse/dimuse_wave.cpp
index 1daaabb3817..cd343b0559a 100644
--- a/engines/grim/imuse/dimuse_wave.cpp
+++ b/engines/grim/imuse/dimuse_wave.cpp
@@ -120,8 +120,4 @@ int IMuseDigital::waveFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, i
 	return tracksFeedStream(soundId, srcBuf, sizeToFeed, paused);
 }
 
-int IMuseDigital::waveLipSync(int soundId, int syncId, int msPos, int32 &width, int32 &height) {
-	return tracksLipSync(soundId, syncId, msPos, width, height);
-}
-
 } // End of namespace Grim


Commit: ee9278fe459e47553d8c9279303ca060b0522be3
    https://github.com/scummvm/scummvm/commit/ee9278fe459e47553d8c9279303ca060b0522be3
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Port GRIM differences in dimuse_dispatch.cpp

Changed paths:
    engines/grim/imuse/dimuse_defs.h
    engines/grim/imuse/dimuse_dispatch.cpp
    engines/grim/imuse/dimuse_engine.h


diff --git a/engines/grim/imuse/dimuse_defs.h b/engines/grim/imuse/dimuse_defs.h
index 3ff243b0f87..891f5d0e3e9 100644
--- a/engines/grim/imuse/dimuse_defs.h
+++ b/engines/grim/imuse/dimuse_defs.h
@@ -29,7 +29,7 @@ namespace Grim {
 #define DIMUSE_MAX_TRIGGERS    8
 #define DIMUSE_MAX_DEFERS      8
 #define DIMUSE_MAX_TRACKS      8
-#define DIMUSE_MAX_MAP_SIZE    2048
+#define DIMUSE_MAX_MAP_SIZE    512
 #define DIMUSE_MAX_DISPATCHES  8
 #define DIMUSE_MAX_STREAMZONES 50
 #define DIMUSE_MAX_FADE_VOLUME 8323072
@@ -237,6 +237,7 @@ struct IMuseDigiDispatch {
 	int wordSize;
 	int sampleRate;
 	int channelCount;
+	int swapEndiannessFlag;
 	int32 currentOffset;
 	int32 audioRemaining;
 	int32 map[DIMUSE_MAX_MAP_SIZE];
diff --git a/engines/grim/imuse/dimuse_dispatch.cpp b/engines/grim/imuse/dimuse_dispatch.cpp
index 8541e9b824b..2a2e4f5a2a0 100644
--- a/engines/grim/imuse/dimuse_dispatch.cpp
+++ b/engines/grim/imuse/dimuse_dispatch.cpp
@@ -53,6 +53,7 @@ int IMuseDigital::dispatchInit() {
 			_dispatches[i].wordSize = 0;
 			_dispatches[i].sampleRate = 0;
 			_dispatches[i].channelCount = 0;
+			_dispatches[i].swapEndiannessFlag = 0;
 			_dispatches[i].currentOffset = 0;
 			_dispatches[i].audioRemaining = 0;
 			memset(_dispatches[i].map, 0, sizeof(_dispatches[i].map));
@@ -90,9 +91,10 @@ void IMuseDigital::dispatchSaveLoad(Common::Serializer &ser) {
 		ser.syncAsSint32LE(_dispatches[l].wordSize, VER(103));
 		ser.syncAsSint32LE(_dispatches[l].sampleRate, VER(103));
 		ser.syncAsSint32LE(_dispatches[l].channelCount, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].swapEndiannessFlag, VER(103));
 		ser.syncAsSint32LE(_dispatches[l].currentOffset, VER(103));
 		ser.syncAsSint32LE(_dispatches[l].audioRemaining, VER(103));
-		ser.syncArray(_dispatches[l].map, 2048, Common::Serializer::Sint32LE, VER(103));
+		ser.syncArray(_dispatches[l].map, DIMUSE_MAX_MAP_SIZE, Common::Serializer::Sint32LE, VER(103));
 
 		// This is only needed to signal if the sound originally had a stream associated with it
 		int hasStream = 0;
@@ -181,7 +183,7 @@ int IMuseDigital::dispatchAllocateSound(IMuseDigiTrack *trackPtr, int groupId) {
 	trackDispatch->audioRemaining = 0;
 	trackDispatch->fadeBuf = nullptr;
 
-	memset(trackDispatch->map, 0, sizeof(trackDispatch->map));
+	trackDispatch->map[0] = 0;
 
 	if (groupId) {
 		trackDispatch->streamPtr = streamerAllocateSound(trackPtr->soundId, groupId, sizeToFeed);
@@ -279,7 +281,7 @@ int IMuseDigital::dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeL
 		// Validate and adjust the fade dispatch size further;
 		// this should correctly align the dispatch size to avoid starting a fade without
 		// inverting the stereo image by mistake
-		dispatchValidateFadeSize(curDispatch, _dispatchFadeSize, "dispatchSwitchStream");
+		dispatchValidateFadeSize(curDispatch, _dispatchFadeSize);
 
 		curDispatch->fadeBuf = dispatchAllocateFade(_dispatchFadeSize, "dispatchSwitchStream");
 
@@ -301,7 +303,14 @@ int IMuseDigital::dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeL
 				if ((_dispatchFadeSize - curDispatch->fadeRemaining) >= 0x4000)
 					effFadeSize = 0x4000;
 
-				memcpy(&curDispatch->fadeBuf[curDispatch->fadeRemaining], streamerGetStreamBuffer(curDispatch->streamPtr, effFadeSize), effFadeSize);
+				uint8 *streamBuf = streamerGetStreamBuffer(curDispatch->streamPtr, effFadeSize);
+				if (!streamBuf) {
+					memset(&curDispatch->fadeBuf[curDispatch->fadeRemaining], 0, _dispatchFadeSize - curDispatch->fadeRemaining);
+					curDispatch->fadeRemaining = _dispatchFadeSize;
+					break;
+				}
+
+				memcpy(&curDispatch->fadeBuf[curDispatch->fadeRemaining], streamBuf, effFadeSize);
 
 				curDispatch->fadeRemaining += effFadeSize;
 			}
@@ -311,9 +320,8 @@ int IMuseDigital::dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeL
 	}
 
 	// Clear fades and triggers for the old soundId
-	char emptyMarker[1] = "";
 	_fadesHandler->clearFadeStatus(curDispatch->trackPtr->soundId, -1);
-	_triggersHandler->clearTrigger(curDispatch->trackPtr->soundId, (char *)emptyMarker, -1);
+	_triggersHandler->clearTrigger(curDispatch->trackPtr->soundId, _emptyMarker, -1);
 
 	// Setup the new soundId
 	curDispatch->trackPtr->soundId = newSoundId;
@@ -341,7 +349,7 @@ int IMuseDigital::dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeL
 
 		curDispatch->currentOffset = 0;
 		curDispatch->audioRemaining = 0;
-		memset(curDispatch->map, 0, sizeof(curDispatch->map));
+		curDispatch->map[0] = 0;
 
 		getMapResult = dispatchNavigateMap(curDispatch);
 		if (!getMapResult || getMapResult == -3) {
@@ -378,9 +386,6 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 			effFeedSize = sampleRate * inFrameCount / effSampleRate;
 		}
 
-		if (dispatchPtr->fadeWordSize == 12 && dispatchPtr->fadeChannelCount == 1)
-			inFrameCount &= 0xFFFFFFFE;
-
 		// If the fade is still going on
 		if (inFrameCount) {
 			// Update the fade volume
@@ -406,16 +411,15 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 			// Deallocate fade if it ended
 			if (!dispatchPtr->fadeRemaining) {
 				dispatchDeallocateFade(dispatchPtr, "dispatchProcessDispatches");
+				dispatchPtr->fadeBuf = nullptr;
 			}
 		} else {
-			debug(5, "IMuseDigital::dispatchProcessDispatches(): WARNING: fade for sound %d ends with incomplete frame (or odd 12-bit mono frame)", trackPtr->soundId);
+			debug(5, "IMuseDigital::dispatchProcessDispatches(): WARNING: fade for sound %d ends with incomplete frame", trackPtr->soundId);
 
 			// Fade ended, deallocate it
 			dispatchDeallocateFade(dispatchPtr, "dispatchProcessDispatches");
-		}
-
-		if (!dispatchPtr->fadeRemaining)
 			dispatchPtr->fadeBuf = nullptr;
+		}
 	}
 
 	// This index keeps track of the offset position until which we have
@@ -446,12 +450,6 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 					effFeedSize = sampleRate * inFrameCount / effSampleRate;
 				}
 
-				if (dispatchPtr->fadeWordSize == 12 && dispatchPtr->fadeChannelCount == 1)
-					inFrameCount &= 0xFFFFFFFE;
-
-				if (!inFrameCount)
-					debug(5, "IMuseDigital::dispatchProcessDispatches(): WARNING: fade for sound %d ends with incomplete frame (or odd 12-bit mono frame)", trackPtr->soundId);
-
 				// Update the fade volume
 				effRemainingFade = (inFrameCount * dispatchPtr->fadeWordSize * dispatchPtr->fadeChannelCount) / 8;
 				mixVolume = dispatchUpdateFadeMixVolume(dispatchPtr, effRemainingFade);
@@ -494,12 +492,7 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 			effFeedSize = sampleRate * (8 * dispatchPtr->audioRemaining / effWordSize) / effSampleRate;
 		}
 
-		if (dispatchPtr->wordSize == 12 && dispatchPtr->channelCount == 1)
-			inFrameCount &= 0xFFFFFFFE;
-
 		if (!inFrameCount) {
-			if (dispatchPtr->wordSize == 12)
-				debug(5, "IMuseDigital::dispatchProcessDispatches(): WARNING: region in sound %d ends with incomplete frame (or odd 12-bit mono frame)", trackPtr->soundId);
 			tracksClear(trackPtr);
 			return;
 		}
@@ -521,11 +514,6 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 					_dispatchCurStreamFreeSpace,
 					_dispatchCurStreamPaused);
 
-				if (_dispatchCurStreamPaused) {
-					debug(5, "IMuseDigital::dispatchProcessDispatches(): WARNING: stopping starving paused stream for sound %d", dispatchPtr->trackPtr->soundId);
-					tracksClear(trackPtr);
-				}
-
 				return;
 			}
 			dispatchPtr->streamZoneList->offset += effRemainingAudio;
@@ -535,9 +523,6 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 			soundAddrData = _filesHandler->getSoundAddrData(trackPtr->soundId);
 			if (!soundAddrData) {
 				debug(5, "IMuseDigital::dispatchProcessDispatches(): ERROR: soundAddrData for sound %d is NULL", trackPtr->soundId);
-				// Try to gracefully play nothing instead of getting stuck on an infinite loop
-				dispatchPtr->currentOffset += effRemainingAudio;
-				dispatchPtr->audioRemaining -= effRemainingAudio;
 				return;
 			}
 
@@ -561,9 +546,6 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 
 					inFrameCount = effFeedSize * effSampleRate / sampleRate;
 
-					if (dispatchPtr->wordSize == 12 && dispatchPtr->channelCount == 1)
-						inFrameCount &= 0xFFFFFFFE;
-
 					srcBuf = &srcBuf[effRemainingAudio - ((dispatchPtr->wordSize * inFrameCount * dispatchPtr->channelCount) / 8)];
 				}
 			}
@@ -571,12 +553,7 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 			// If there's still a fadeBuffer active in our dispatch
 			// we balance the volume of the considered track with
 			// the fade volume, effectively creating a crossfade
-			if (dispatchPtr->fadeBuf) {
-				// Fade-in
-				mixVolume = dispatchUpdateFadeSlope(dispatchPtr);
-			} else {
-				mixVolume = trackPtr->effVol;
-			}
+			mixVolume = dispatchUpdateFadeSlope(dispatchPtr);
 		} else {
 			mixVolume = trackPtr->effVol;
 		}
@@ -617,7 +594,7 @@ void IMuseDigital::dispatchPredictFirstStream() {
 
 int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
 	uint8 *mapCurEvent;
-	int32 blockTag, effFadeSize, elapsedFadeSize, regionOffset;
+	int32 blockTag, effFadeSize, elapsedFadeSize, soundId;
 	char *marker = NULL;
 
 	int getMapResult = dispatchGetMap(dispatchPtr);
@@ -722,10 +699,11 @@ int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
 			// - The tag 'FRMT' (4 bytes)
 			// - Block size in bytes minus 8 (4 bytes)
 			// - Block offset (4 bytes)
-			// - Empty field (4 bytes) (which is set to 1 in Grim Fandango, I suspect this is the endianness)
+			// - Endianness field (4 bytes) (swapEndiannessFlag is set when it's 0)
 			// - Word size between 8, 12 and 16 (4 bytes)
 			// - Sample rate (4 bytes)
 			// - Number of channels (4 bytes)
+			dispatchPtr->swapEndiannessFlag = (READ_UINT32(mapCurEvent + 12) == 0);
 			dispatchPtr->wordSize = READ_UINT32(mapCurEvent + 16);
 			dispatchPtr->sampleRate = READ_UINT32(mapCurEvent + 20);
 			dispatchPtr->channelCount = READ_UINT32(mapCurEvent + 24);
@@ -737,21 +715,8 @@ int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
 			// - Block size in bytes minus 8 (4 bytes)
 			// - Block offset (4 bytes)
 			// - Region length (4 bytes)
-			regionOffset = READ_UINT32(mapCurEvent + 8);
-			if (regionOffset == dispatchPtr->currentOffset) {
-				dispatchPtr->audioRemaining = READ_UINT32(mapCurEvent + 12);
-				return 0;
-			} else {
-				debug(5, "IMuseDigital::dispatchNavigateMap(): ERROR: region offset %d != currentOffset %d", regionOffset, dispatchPtr->currentOffset);
-				return -1;
-			}
-		case MKTAG('S', 'T', 'O', 'P'):
-			// Stop block (fixed size: 12 bytes)
-			// Contains:
-			// - The tag 'STOP' (4 bytes)
-			// - Block size in bytes minus 8 (4 bytes)
-			// - Block offset (4 bytes)
-			return -1;
+			dispatchPtr->audioRemaining = READ_UINT32(mapCurEvent + 12);
+			return 0;
 		case MKTAG('T', 'E', 'X', 'T'):
 			// Marker block (variable size)
 			// Contains:
@@ -760,14 +725,18 @@ int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
 			// - Block offset (4 bytes)
 			// - A string of characters ending with '\0' (variable length)
 			marker = (char *)mapCurEvent + 12;
-			_triggersHandler->processTriggers(dispatchPtr->trackPtr->soundId, marker);
+			soundId = dispatchPtr->trackPtr->soundId;
+			_triggersHandler->processTriggers(soundId, marker);
+			if (soundId != dispatchPtr->trackPtr->soundId)
+				return -3;
+
 			if (dispatchPtr->audioRemaining)
 				return 0;
 
 			continue;
 		default:
 			debug(5, "IMuseDigital::dispatchNavigateMap(): ERROR: Unrecognized map event at offset %dx", dispatchPtr->currentOffset);
-			break;
+			return -1;
 		};
 	}
 	return -1;
@@ -781,7 +750,7 @@ int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
 	dstMap = dispatchPtr->map;
 
 	// If there's no map, try to fetch it
-	if (dispatchPtr->map[0] != MKTAG('M', 'A', 'P', ' ')) {
+	if (dispatchPtr->map[0] != MKTAG('M', 'A', 'P', ' ') || (dispatchPtr->streamPtr && !dispatchPtr->streamZoneList)) {
 		if (dispatchPtr->currentOffset) {
 			debug(5, "IMuseDigital::dispatchNavigateMap(): found offset but no map");
 			return -1;
@@ -790,7 +759,7 @@ int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
 		// If there's a streamPtr it means that this is a sound loaded
 		// from a bundle (either music or speech)
 		if (dispatchPtr->streamPtr) {
-			copiedBuf = (uint8 *)streamerGetStreamBufferAtOffset(dispatchPtr->streamPtr, 0, 0x10);
+			copiedBuf = (uint8 *)streamerGetStreamBufferAtOffset(dispatchPtr->streamPtr, 0, 0x40);
 
 			if (!copiedBuf) {
 				return -3;
@@ -892,7 +861,7 @@ int IMuseDigital::dispatchConvertMap(uint8 *rawMap, int32 *destMap) {
 	if (READ_BE_UINT32(rawMap) == MKTAG('M', 'A', 'P', ' ')) {
 		bytesUntilEndOfMap = READ_BE_UINT32(rawMap + 4);
 		effMapSize = bytesUntilEndOfMap + 8;
-		if (effMapSize <= 0x2000) {
+		if (effMapSize <= 0x800) {
 			memcpy(destMap, rawMap, effMapSize);
 
 			// Fill (or rather, swap32) the fields:
@@ -1122,7 +1091,10 @@ void IMuseDigital::dispatchPrepareToJump(IMuseDigiDispatch *dispatchPtr, IMuseDi
 		_dispatchSize = strZnPtr->size + strZnPtr->offset - hookPosition;
 
 	// This prevents starting a fade with an inverted stereo image
-	dispatchValidateFadeSize(dispatchPtr, _dispatchSize, "dispatchPrepareToJump");
+	dispatchValidateFadeSize(dispatchPtr, _dispatchSize);
+
+	if (hookPosition < 2000 && jumpDestination > hookPosition)
+		_dispatchSize = 0;
 
 	if (dispatchPtr->fadeRemaining)
 		_dispatchSize = 0;
@@ -1198,10 +1170,10 @@ void IMuseDigital::dispatchStreamNextZone(IMuseDigiDispatch *dispatchPtr, IMuseD
 		// Set the stream load index of the sound to the new streamZone
 		streamerSetLoadIndex(dispatchPtr->streamPtr, cumulativeStreamOffset);
 
-		// Remove che previous streamZone from the list, we don't need it anymore
-		while (strZnPtr->next->prev) {
-			strZnPtr->next->prev->useFlag = 0;
-			removeStreamZoneFromList(&strZnPtr->next, strZnPtr->next->prev);
+		// Remove the following streamZones from the list, we don't need them anymore
+		while (strZnPtr->next) {
+			strZnPtr->next->useFlag = 0;
+			removeStreamZoneFromList(&strZnPtr->next, strZnPtr->next);
 		}
 
 		streamerSetSoundToStreamFromOffset(
@@ -1266,6 +1238,7 @@ uint8 *IMuseDigital::dispatchAllocateFade(int32 &fadeSize, const char *function)
 
 		// Fallback to a small fade if large fades are unavailable
 		if (!allocatedFadeBuf) {
+			fadeSize = DIMUSE_SMALL_FADE_DIM;
 			for (int i = 0; i <= DIMUSE_SMALL_FADES; i++) {
 				if (i == DIMUSE_SMALL_FADES) {
 					debug(5, "IMuseDigital::dispatchAllocateFade(): couldn't allocate small fade buffer in %s()", function);
@@ -1314,22 +1287,11 @@ void IMuseDigital::dispatchDeallocateFade(IMuseDigiDispatch *dispatchPtr, const
 }
 
 int IMuseDigital::dispatchGetFadeSize(IMuseDigiDispatch *dispatchPtr, int fadeLength) {
-	return (dispatchPtr->wordSize * dispatchPtr->channelCount * ((dispatchPtr->sampleRate * fadeLength / 1000) & 0xFFFFFFFE)) / 8;
+	return (dispatchPtr->wordSize * dispatchPtr->channelCount * (dispatchPtr->sampleRate * fadeLength / 1000)) / 8;
 }
 
-void IMuseDigital::dispatchValidateFadeSize(IMuseDigiDispatch *dispatchPtr, int32 &dispatchSize, const char *function) {
-	int alignmentModDividend;
-	if (dispatchPtr->wordSize == 8) {
-		alignmentModDividend = dispatchPtr->channelCount * 1;
-	} else {
-		alignmentModDividend = dispatchPtr->channelCount * ((dispatchPtr->wordSize == 12) + 2);
-	}
-
-	if (alignmentModDividend) {
-		dispatchSize -= dispatchSize % alignmentModDividend;
-	} else {
-		debug(5, "IMuseDigital::dispatchValidateFadeSize(): WARNING: tried mod by 0 while validating fade size in %s(), ignored", function);
-	}
+void IMuseDigital::dispatchValidateFadeSize(IMuseDigiDispatch *dispatchPtr, int32 &dispatchSize) {
+	dispatchSize -= dispatchSize & (dispatchPtr->channelCount * (dispatchPtr->wordSize >> 3) - 1);
 }
 
 int IMuseDigital::dispatchUpdateFadeMixVolume(IMuseDigiDispatch *dispatchPtr, int32 remainingFade) {
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/dimuse_engine.h
index 29c6130b80f..2be1d2e60d7 100644
--- a/engines/grim/imuse/dimuse_engine.h
+++ b/engines/grim/imuse/dimuse_engine.h
@@ -229,7 +229,7 @@ private:
 	uint8 *dispatchAllocateFade(int32 &fadeSize, const char *functionName);
 	void dispatchDeallocateFade(IMuseDigiDispatch *dispatchPtr, const char *functionName);
 	int dispatchGetFadeSize(IMuseDigiDispatch *dispatchPtr, int fadeLength);
-	void dispatchValidateFadeSize(IMuseDigiDispatch *dispatchPtr, int32 &dispatchSize, const char *functionName);
+	void dispatchValidateFadeSize(IMuseDigiDispatch *dispatchPtr, int32 &dispatchSize);
 	int dispatchUpdateFadeMixVolume(IMuseDigiDispatch *dispatchPtr, int32 remainingFade);
 	int dispatchUpdateFadeSlope(IMuseDigiDispatch *dispatchPtr);
 


Commit: e9a5938c7481cd4a66ff84a7844b661794098cd4
    https://github.com/scummvm/scummvm/commit/e9a5938c7481cd4a66ff84a7844b661794098cd4
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Implement original mixer

Changed paths:
    engines/grim/imuse/dimuse_dispatch.cpp
    engines/grim/imuse/dimuse_internalmixer.cpp
    engines/grim/imuse/dimuse_internalmixer.h
    engines/grim/imuse/dimuse_tracks.cpp


diff --git a/engines/grim/imuse/dimuse_dispatch.cpp b/engines/grim/imuse/dimuse_dispatch.cpp
index 2a2e4f5a2a0..9306005f47c 100644
--- a/engines/grim/imuse/dimuse_dispatch.cpp
+++ b/engines/grim/imuse/dimuse_dispatch.cpp
@@ -400,6 +400,7 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 				inFrameCount,
 				dispatchPtr->fadeWordSize,
 				dispatchPtr->fadeChannelCount,
+				dispatchPtr->swapEndiannessFlag,
 				effFeedSize,
 				0,
 				mixVolume,
@@ -462,6 +463,7 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 					inFrameCount,
 					dispatchPtr->fadeWordSize,
 					dispatchPtr->fadeChannelCount,
+					dispatchPtr->swapEndiannessFlag,
 					effFeedSize,
 					mixStartingPoint,
 					mixVolume,
@@ -563,6 +565,7 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 			inFrameCount,
 			dispatchPtr->wordSize,
 			dispatchPtr->channelCount,
+			dispatchPtr->swapEndiannessFlag,
 			effFeedSize,
 			mixStartingPoint,
 			mixVolume,
diff --git a/engines/grim/imuse/dimuse_internalmixer.cpp b/engines/grim/imuse/dimuse_internalmixer.cpp
index b3985fc4239..62aa45331ac 100644
--- a/engines/grim/imuse/dimuse_internalmixer.cpp
+++ b/engines/grim/imuse/dimuse_internalmixer.cpp
@@ -44,135 +44,47 @@ IMuseDigiInternalMixer::IMuseDigiInternalMixer(Audio::Mixer *mixer, int sampleRa
 		_stream = Audio::makeQueuingAudioStream(_sampleRate, _mixer->getOutputStereo());
 	else
 		_stream = nullptr;
-
-	_amp8Table = nullptr;
 }
 
 IMuseDigiInternalMixer::~IMuseDigiInternalMixer() {
-	free(_amp8Table);
-	_amp8Table = nullptr;
+	free(_softLTable);
+	free(_mixBuf);
+	_softLTable = nullptr;
+	_mixBuf = nullptr;
 }
 
-// Lookup table for a linear volume ramp (0 to 16) accounting for panning (-8 to 8)
-static const int8 _stereoVolumeTable[284] = {
-	0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
-	0,  0,  0,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,  2,  0,  0,  1,  1,  1,  1,  2,  2,  2,
-	2,  2,  3,  3,  3,  3,  3,  3,  0,  0,  1,  1,  2,  2,  2,  3,  3,  3,  3,  4,  4,  4,  4,  4,  4,  0,
-	0,  1,  1,  2,  2,  3,  3,  4,  4,  4,  4,  5,  5,  5,  5,  5,  0,  1,  1,  2,  2,  3,  3,  4,  4,  5,
-	5,  5,  6,  6,  6,  6,  6,  0,  1,  1,  2,  3,  3,  4,  4,  5,  5,  6,  6,  6,  7,  7,  7,  7,  0,  1,
-	2,  2,  3,  4,  4,  5,  6,  6,  7,  7,  7,  8,  8,  8,  8,  0,  1,  2,  3,  3,  4,  5,  6,  6,  7,  7,
-	8,  8,  9,  9,  9,  9,  0,  1,  2,  3,  4,  5,  6,  6,  7,  8,  8,  9,  9,  10, 10, 10, 10, 0,  1,  2,
-	3,  4,  5,  6,  7,  8,  9,  9,  10, 10, 11, 11, 11, 11, 0,  1,  2,  3,  5,  6,  7,  8,  8,  9,  10, 11,
-	11, 11, 12, 12, 12, 0,  1,  3,  4,  5,  6,  7,  8,  9,  10, 11, 11, 12, 12, 13, 13, 13, 0,  1,  3,  4,
-	5,  7,  8,  9,  10, 11, 12, 12, 13, 13, 14, 14, 14, 0,  1,  3,  4,  6,  7,  8,  10, 11, 12, 12, 13, 14,
-	14, 15, 15, 15, 0,  2,  3,  5,  6,  8,  9,  10, 11, 12, 13, 14, 15, 15, 16, 16, 16, 0,  0,  0
-};
-
-int IMuseDigiInternalMixer::init(int bytesPerSample, int numChannels, uint8 *mixBuf, int mixBufSize, int sizeSampleKB, int mixChannelsNum) {
-	int amplitudeValue;
-	int waveMixChannelsCount;
-	uint softLdenominator;
-	uint softLnumerator;
-	int softLcurValue;
-	int zeroCenterOffset;
-
-	_outWordSize = bytesPerSample;
-	_outChannelCount = numChannels;
-	_mixBufSize = mixBufSize;
-	_stereoReverseFlag = sizeSampleKB;
-	_mixBuf = mixBuf;
-
-	waveMixChannelsCount = mixChannelsNum;
-
-	// We're allocating:
-	// - The amplitude quantization table for 8-bit audio ((17 * 256) int16 == 2176 int32)
-	// - The amplitude quantization table for 12-bit/16-bit audio ((17 * 4096) int16 == 34816 int32)
-	// - The pseudologarithmic curve for volume fade ((8 * 4096) int16 == 16384 int32)
-	//
-	// For the first two tables 17 represents the volume range (0-16), while
-	// 256 and 4096 are respectively the dynamic range for 8-bit and 12-bit audio;
-	//
-	// Every table is initialized with int16 values, but stored as int32 and manipulated
-	// at different levels of granularity depending on the case (as uint32, uint16 or uint8).
-	// The latter is populated from the middle, inside-out; hence _softLMID.
-
-	int32 *tableMalloc = (int32 *)malloc(53376 * sizeof(int32));
-
-	_amp8Table = tableMalloc;          // Dim: 2176
-	_amp12Table = tableMalloc + 2176;  // Dim: 34816
-	_softLTable = tableMalloc + 36992; // Dim: 16384
-	_softLMID = tableMalloc + 45184;   // Mid table
-
-	if (tableMalloc) {
-		// Any unpopulated cell is expected to be set to 0
-		memset(tableMalloc, 0, 53376 * sizeof(int32));
-		zeroCenterOffset = 0;
-		for (int i = 0; i < 17; i++) {
-			amplitudeValue = -2048 * zeroCenterOffset;
-			for (int j = 0; j < 256; j++) {
-				((int16 *)&_amp8Table[i * 128])[j] = (int16)(amplitudeValue / 127);
-				amplitudeValue += 16 * zeroCenterOffset;
-			}
-
-			zeroCenterOffset += 8;
-			if (zeroCenterOffset == 8)
-				zeroCenterOffset = 7;
-		}
-
-		zeroCenterOffset = 0;
-		for (int i = 0; i < 17; i++) {
-			amplitudeValue = -2048 * zeroCenterOffset;
-			for (int j = 0; j < 4096; j++) {
-				((int16 *)&_amp12Table[i * 2048])[j] = (int16)(amplitudeValue / 127);
-				amplitudeValue += zeroCenterOffset;
-			}
-
-			zeroCenterOffset += 8;
-			if (zeroCenterOffset == 8)
-				zeroCenterOffset = 7;
-		}
-
-		if (_outWordSize == 8) {
-			if (waveMixChannelsCount * 1024 > 0) {
-				softLnumerator = 0;
-				softLdenominator = 2047 * waveMixChannelsCount;
-				for (int i = 0; i < waveMixChannelsCount * 2048; i++) {
-					softLcurValue = softLnumerator / softLdenominator + 1;
-					softLdenominator += waveMixChannelsCount - 1;
-					softLnumerator += 254 * waveMixChannelsCount;
-					softLcurValue /= 2;
-
-					((int8 *)_softLMID)[i] = (int8)softLcurValue + 128;
-					((int8 *)_softLMID)[-i] = 127 - (int8)softLcurValue;
-				}
-			}
-		} else if (waveMixChannelsCount * 2048 > 0) {
-			softLdenominator = 2047 * waveMixChannelsCount;
-			softLnumerator = 0;
-			for (int i = 0; i < waveMixChannelsCount * 2048; i++) {
-				softLcurValue = softLnumerator / softLdenominator + 1;
-				softLcurValue /= 2;
-				softLdenominator += waveMixChannelsCount - 1;
-				softLnumerator += 65534 * waveMixChannelsCount;
-				((int16 *)_softLMID)[i] = (int16)softLcurValue;
-				((int16 *)_softLMID)[-i - 1] = -1 - (int16)softLcurValue;
-			}
+int IMuseDigiInternalMixer::init(int numChannels, int mixBufSize, int mixChannelsNum) {
+	// Pan table: 17 volume levels x 17 pan positions
+	for (int i = 0; i < 17; i++) {
+		for (int j = 0; j < 17; j++) {
+			_mixerTable[17 * i + j] = (uint8)(int)((sin((double)j * 3.1415 * 0.03125) * (double)i + 0.5) * 8.0);
 		}
+	}
 
-		if (!_lowLatencyMode) {
-			_mixer->playStream(
-				Audio::Mixer::kPlainSoundType,
-				&_channelHandle,
-				_stream,
-				-1,
-				Audio::Mixer::kMaxChannelVolume);
-		}
+	_outChannelCount = numChannels;
+	_mixBufSize = 2 * mixBufSize;
+	_mixBuf = (int32 *)malloc(_mixBufSize);
 
-		return 0;
-	} else {
+	_softLTable = (int16 *)malloc(mixChannelsNum << 16);
+	if (!_softLTable) {
 		debug(5, "IMuseDigiInternalMixer::init(): ERROR: couldn't allocate mixer tables");
 		return -1;
 	}
+
+	for (int i = 0; i < (mixChannelsNum << 15); i++) {
+		_softLTable[i] = (int16)(int)(((double)i * 524272.0 / (262136.0 + (double)i * 7.0) + 1.0) * 0.5);
+	}
+
+	if (!_lowLatencyMode) {
+		_mixer->playStream(
+			Audio::Mixer::kPlainSoundType,
+			&_channelHandle,
+			_stream,
+			-1,
+			Audio::Mixer::kMaxChannelVolume);
+	}
+
+	return 0;
 }
 
 int IMuseDigiInternalMixer::clearMixerBuffer() {
@@ -184,145 +96,280 @@ int IMuseDigiInternalMixer::clearMixerBuffer() {
 	return 0;
 }
 
-void IMuseDigiInternalMixer::mix(uint8 *srcBuf, int32 inFrameCount, int wordSize, int channelCount, int feedSize, int32 mixBufStartIndex, int volume, int pan) {
-	int32 *ampTable;
-	int rightChannelVolume;
-	int leftChannelVolume;
-	int channelVolume;
-	int channelPan;
+void IMuseDigiInternalMixer::mix16ToStereo(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int leftAmp, int rightAmp) {
+	int32 *mixBufCurCell = &_mixBuf[2 * mixBufStartIndex];
+	uint32 ratio = ((uint32)inFrameCount << 16) / feedSize;
+	uint32 position = 0;
+	int32 interpolated;
+
+	switch (ratio) {
+	case 0x8000:
+		for (int i = 0; i < inFrameCount - 1; i++) {
+			interpolated = (srcBuf[0] + srcBuf[2]) >> 1;
+
+			mixBufCurCell[0] += srcBuf[0] * leftAmp;
+			mixBufCurCell[1] += srcBuf[0] * rightAmp;
+			mixBufCurCell[2] += interpolated * leftAmp;
+			mixBufCurCell[3] += interpolated * rightAmp;
+
+			srcBuf++;
+			mixBufCurCell += 4;
+		}
+
+		mixBufCurCell[0] += srcBuf[0] * leftAmp;
+		mixBufCurCell[1] += srcBuf[0] * rightAmp;
+		mixBufCurCell[2] += srcBuf[0] * leftAmp;
+		mixBufCurCell[3] += srcBuf[0] * rightAmp;
+		break;
+	case 0x10000:
+		for (uint32 i = 0; i < feedSize; i++) {
+			mixBufCurCell[0] += srcBuf[0] * leftAmp;
+			mixBufCurCell[1] += srcBuf[0] * rightAmp;
+
+			srcBuf++;
+			mixBufCurCell += 2;
+		}
+		break;
+	case 0x20000:
+		for (uint32 i = 0; i < feedSize; i++) {
+			mixBufCurCell[0] += srcBuf[0] * leftAmp;
+			mixBufCurCell[1] += srcBuf[0] * rightAmp;
+
+			srcBuf += 2;
+			mixBufCurCell += 2;
+		}
+		break;
+	default:
+		for (uint32 i = 0; i < feedSize; i++) {
+			mixBufCurCell[0] += srcBuf[0] * leftAmp;
+			mixBufCurCell[1] += srcBuf[0] * rightAmp;
+
+			mixBufCurCell += 2;
+			position += ratio;
+			srcBuf += position >> 16;
+			position &= 0xFFFF;
+		}
+		break;
+	}
+}
+
+void IMuseDigiInternalMixer::mix16ToStereoSwap(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int leftAmp, int rightAmp) {
+	int32 *mixBufCurCell = &_mixBuf[2 * mixBufStartIndex];
+	uint32 ratio = ((uint32)inFrameCount << 16) / feedSize;
+	uint32 position = 0;
+	int32 sample, interpolated;
+
+	switch (ratio) {
+	case 0x8000:
+		for (int i = 0; i < inFrameCount - 1; i++) {
+			sample = (int16)SWAP_BYTES_16(srcBuf[0]);
+			interpolated = (sample + (int16)SWAP_BYTES_16(srcBuf[2])) >> 1;
+
+			mixBufCurCell[0] += sample * leftAmp;
+			mixBufCurCell[1] += sample * rightAmp;
+			mixBufCurCell[2] += interpolated * leftAmp;
+			mixBufCurCell[3] += interpolated * rightAmp;
+
+			srcBuf++;
+			mixBufCurCell += 4;
+		}
+
+		sample = (int16)SWAP_BYTES_16(srcBuf[0]);
+		mixBufCurCell[0] += sample * leftAmp;
+		mixBufCurCell[1] += sample * rightAmp;
+		mixBufCurCell[2] += sample * leftAmp;
+		mixBufCurCell[3] += sample * rightAmp;
+		break;
+	case 0x10000:
+		for (uint32 i = 0; i < feedSize; i++) {
+			sample = (int16)SWAP_BYTES_16(srcBuf[0]);
+			mixBufCurCell[0] += sample * leftAmp;
+			mixBufCurCell[1] += sample * rightAmp;
+
+			srcBuf++;
+			mixBufCurCell += 2;
+		}
+		break;
+	case 0x20000:
+		for (uint32 i = 0; i < feedSize; i++) {
+			sample = (int16)SWAP_BYTES_16(srcBuf[0]);
+			mixBufCurCell[0] += sample * leftAmp;
+			mixBufCurCell[1] += sample * rightAmp;
+
+			srcBuf += 2;
+			mixBufCurCell += 2;
+		}
+		break;
+	default:
+		for (uint32 i = 0; i < feedSize; i++) {
+			sample = (int16)SWAP_BYTES_16(srcBuf[0]);
+			mixBufCurCell[0] += sample * leftAmp;
+			mixBufCurCell[1] += sample * rightAmp;
+
+			mixBufCurCell += 2;
+			position += ratio;
+			srcBuf += position >> 16;
+			position &= 0xFFFF;
+		}
+		break;
+	}
+}
+
+void IMuseDigiInternalMixer::mix16(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int volume) {
+	int32 *mixBufCurCell = &_mixBuf[2 * mixBufStartIndex];
+	uint32 ratio = ((uint32)inFrameCount << 16) / feedSize;
+	uint32 position = 0;
+
+	switch (ratio) {
+	case 0x8000:
+		for (int i = 0; i < inFrameCount - 1; i++) {
+			mixBufCurCell[0] += srcBuf[0] * volume;
+			mixBufCurCell[1] += srcBuf[1] * volume;
+			mixBufCurCell[2] += volume * ((srcBuf[0] + srcBuf[2]) >> 1);
+			mixBufCurCell[3] += volume * ((srcBuf[1] + srcBuf[3]) >> 1);
+
+			srcBuf += 2;
+			mixBufCurCell += 4;
+		}
+
+		mixBufCurCell[0] += srcBuf[0] * volume;
+		mixBufCurCell[1] += srcBuf[1] * volume;
+		mixBufCurCell[2] += srcBuf[0] * volume;
+		mixBufCurCell[3] += srcBuf[1] * volume;
+		break;
+	case 0x10000:
+		for (uint32 i = 0; i < 2 * feedSize; i++) {
+			mixBufCurCell[i] += srcBuf[i] * volume;
+		}
+		break;
+	case 0x20000:
+		for (uint32 i = 0; i < feedSize; i++) {
+			mixBufCurCell[0] += srcBuf[0] * volume;
+			mixBufCurCell[1] += srcBuf[1] * volume;
+
+			srcBuf += 4;
+			mixBufCurCell += 2;
+		}
+		break;
+	default:
+		for (uint32 i = 0; i < feedSize; i++) {
+			mixBufCurCell[0] += srcBuf[0] * volume;
+			mixBufCurCell[1] += srcBuf[1] * volume;
+
+			mixBufCurCell += 2;
+			position += 2 * ratio;
+			srcBuf += position >> 16;
+			position &= 0xFFFF;
+		}
+		break;
+	}
+}
+
+void IMuseDigiInternalMixer::mix16Swap(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int volume) {
+	int32 *mixBufCurCell = &_mixBuf[2 * mixBufStartIndex];
+	uint32 ratio = ((uint32)inFrameCount << 16) / feedSize;
+	uint32 position = 0;
+	int32 left, right;
+
+	switch (ratio) {
+	case 0x8000:
+		for (int i = 0; i < inFrameCount - 1; i++) {
+			left = (int16)SWAP_BYTES_16(srcBuf[0]);
+			right = (int16)SWAP_BYTES_16(srcBuf[1]);
+
+			mixBufCurCell[0] += left * volume;
+			mixBufCurCell[1] += right * volume;
+			mixBufCurCell[2] += volume * ((left + (int16)SWAP_BYTES_16(srcBuf[2])) >> 1);
+			mixBufCurCell[3] += volume * ((right + (int16)SWAP_BYTES_16(srcBuf[3])) >> 1);
+
+			srcBuf += 2;
+			mixBufCurCell += 4;
+		}
+
+		left = (int16)SWAP_BYTES_16(srcBuf[0]);
+		right = (int16)SWAP_BYTES_16(srcBuf[1]);
+		mixBufCurCell[0] += left * volume;
+		mixBufCurCell[1] += right * volume;
+		mixBufCurCell[2] += left * volume;
+		mixBufCurCell[3] += right * volume;
+		break;
+	case 0x10000:
+		for (uint32 i = 0; i < 2 * feedSize; i++) {
+			mixBufCurCell[i] += (int16)SWAP_BYTES_16(srcBuf[i]) * volume;
+		}
+		break;
+	case 0x20000:
+		for (uint32 i = 0; i < feedSize; i++) {
+			mixBufCurCell[0] += (int16)SWAP_BYTES_16(srcBuf[0]) * volume;
+			mixBufCurCell[1] += (int16)SWAP_BYTES_16(srcBuf[1]) * volume;
+
+			srcBuf += 4;
+			mixBufCurCell += 2;
+		}
+		break;
+	default:
+		for (uint32 i = 0; i < feedSize; i++) {
+			mixBufCurCell[0] += (int16)SWAP_BYTES_16(srcBuf[0]) * volume;
+			mixBufCurCell[1] += (int16)SWAP_BYTES_16(srcBuf[1]) * volume;
+
+			mixBufCurCell += 2;
+			position += 2 * ratio;
+			srcBuf += position >> 16;
+			position &= 0xFFFF;
+		}
+		break;
+	}
+}
 
-	if (_mixBuf) {
-		if (srcBuf) {
-			if (inFrameCount) {
-				if (channelCount == 1 && _outChannelCount == 2) {
-					channelVolume = volume / 8;
-					if (volume)
-						++channelVolume;
-					if (channelVolume >= 17)
-						channelVolume = 16;
-					channelPan = (pan / 8) - 8;
-					if (pan > 64)
-						++channelPan;
+void IMuseDigiInternalMixer::mix(uint8 *srcBuf, int32 inFrameCount, int wordSize, int channelCount, int swapEndiannessFlag, int feedSize, int32 mixBufStartIndex, int volume, int pan) {
+	int channelVolume, channelPan, leftAmp, rightAmp;
 
-					channelPan = channelVolume == 0 ? 0 : channelPan;
+	// The original could divide by zero here, let's avoid that...
+	if (!_mixBuf || !srcBuf || !inFrameCount || wordSize != 16 || volume < 1 || feedSize < 1)
+		return;
 
-					// Linear volume quantization from the lookup table
-					rightChannelVolume = _stereoVolumeTable[17 * channelVolume + channelPan];
-					leftChannelVolume = _stereoVolumeTable[17 * channelVolume - channelPan];
-					if (wordSize == 8) {
-						mixBits8ConvertToStereo(
-							srcBuf,
-							inFrameCount,
-							feedSize,
-							mixBufStartIndex,
-							&_amp8Table[leftChannelVolume * 128],
-							&_amp8Table[rightChannelVolume * 128]);
-					} else if (wordSize == 12) {
-						mixBits12ConvertToStereo(
-							srcBuf,
-							inFrameCount,
-							feedSize,
-							mixBufStartIndex,
-							&_amp12Table[leftChannelVolume * 2048],
-							&_amp12Table[rightChannelVolume * 2048]);
-					} else {
-						mixBits16ConvertToStereo(
-							srcBuf,
-							inFrameCount,
-							feedSize,
-							mixBufStartIndex,
-							&_amp12Table[leftChannelVolume * 2048],
-							&_amp12Table[rightChannelVolume * 2048]);
-					}
-				} else {
-					channelVolume = volume / 8;
-					if (volume)
-						channelVolume++;
-					if (channelVolume >= 17)
-						channelVolume = 16;
+	if (channelCount == 1 && _outChannelCount == 2) {
+		channelVolume = (volume >> 3) + 1;
+		if (channelVolume >= 17)
+			channelVolume = 16;
 
-					if (wordSize == 8)
-						ampTable = &_amp8Table[channelVolume * 128];
-					else
-						ampTable = &_amp12Table[channelVolume * 2048];
+		channelPan = (pan >> 3) - 8;
+		if (pan > 64)
+			++channelPan;
 
-					if (_outChannelCount == 1) {
-						if (channelCount == 1) {
-							if (wordSize == 8) {
-								mixBits8Mono(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
-							} else if (wordSize == 12) {
-								mixBits12Mono(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
-							} else {
-								mixBits16Mono(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
-							}
-						} else if (wordSize == 8) {
-							mixBits8ConvertToMono(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
-						} else if (wordSize == 12) {
-							mixBits12ConvertToMono(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
-						} else {
-							mixBits16ConvertToMono(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
-						}
-					} else if (wordSize == 8) {
-						mixBits8Stereo(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
-					} else if (wordSize == 12) {
-						mixBits12Stereo(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
-					} else {
-						mixBits16Stereo(srcBuf, inFrameCount, feedSize, mixBufStartIndex, ampTable);
-					}
-				}
-			}
-		}
+		leftAmp = _mixerTable[17 * channelVolume + 8 - channelPan];
+		rightAmp = _mixerTable[17 * channelVolume + 8 + channelPan];
+
+		if (swapEndiannessFlag)
+			mix16ToStereoSwap((const int16 *)srcBuf, inFrameCount, feedSize, mixBufStartIndex, leftAmp, rightAmp);
+		else
+			mix16ToStereo((const int16 *)srcBuf, inFrameCount, feedSize, mixBufStartIndex, leftAmp, rightAmp);
+	} else if (swapEndiannessFlag) {
+		mix16Swap((const int16 *)srcBuf, inFrameCount, feedSize, mixBufStartIndex, volume + 1);
+	} else {
+		mix16((const int16 *)srcBuf, inFrameCount, feedSize, mixBufStartIndex, volume + 1);
 	}
 }
 
 int IMuseDigiInternalMixer::loop(uint8 **destBuffer, int len) {
-	int16 *mixBuffer = (int16 *)_mixBuf;
-	uint8 *destBuffer_tmp = *destBuffer;
-
 	if (!_mixBuf || !destBuffer || !len)
 		return -1;
 
+	int16 *destBuffer_tmp = (int16 *)*destBuffer;
+	int32 value;
+
 	if (_outChannelCount == 2)
 		len *= 2;
 
-	if (!_stereoReverseFlag || _outChannelCount == 1) {
-		if (_outWordSize != 16) {
-			if (len) {
-				for (int i = 0; i < len; i++) {
-					destBuffer_tmp[i] = ((uint8 *)_softLMID)[mixBuffer[i]];
-				}
-			}
-		}
-
-		if (len) {
-			for (int i = 0; i < len; i++) {
-				((uint16 *)destBuffer_tmp)[i] = ((uint16 *)_softLMID)[mixBuffer[i]];
-			}
-		}
-	} else {
-		len /= 2;
-		if (_outWordSize == 16) {
-			if (len) {
-				for (int i = 0; i < len; i += 2) {
-					((uint16 *)destBuffer_tmp)[i]     = ((uint16 *)_softLMID)[mixBuffer[i + 1]];
-					((uint16 *)destBuffer_tmp)[i + 1] = ((uint16 *)_softLMID)[mixBuffer[i]];
-				}
-			}
-		}
-
-		if (len) {
-			for (int i = 0; i < len; i += 2) {
-				destBuffer_tmp[i] = ((uint8 *)_softLMID)[mixBuffer[i + 1]];
-				destBuffer_tmp[i + 1] = ((uint8 *)_softLMID)[mixBuffer[i]];
-			}
-		}
+	for (int i = 0; i < len; i++) {
+		value = _mixBuf[i] >> 7;
+		if (value >= 0)
+			destBuffer_tmp[i] = _softLTable[value];
+		else
+			destBuffer_tmp[i] = (int16)(-(uint16)_softLTable[-value - 1]);
 	}
-	return 0;
-}
 
-void IMuseDigiInternalMixer::setCurrentMixerBuffer(uint8 *newBuf) {
-	// Used to swap mixer buffers in low latency mode
-	_mixBuf = newBuf;
+	return 0;
 }
 
 void IMuseDigiInternalMixer::endStream(int idx) {
@@ -358,941 +405,4 @@ Audio::QueuingAudioStream *IMuseDigiInternalMixer::getStream(int idx) {
 	}
 }
 
-void IMuseDigiInternalMixer::mixBits8Mono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
-	uint16 *mixBufCurCell;
-	uint8 *srcBuf_ptr;
-	int residualLength;
-
-	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
-	srcBuf_ptr = srcBuf;
-	if (inFrameCount == feedSize) {
-		if (feedSize) {
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[i] += *((uint16 *)ampTable + srcBuf_ptr[i]);
-			}
-		}
-	} else if (2 * inFrameCount == feedSize) {
-		if (inFrameCount - 1 != 0) {
-			for (int i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-				mixBufCurCell[1] += (*((int16 *)ampTable + srcBuf_ptr[0]) + *((int16 *)ampTable + srcBuf_ptr[1])) >> 1;
-				mixBufCurCell += 2;
-				srcBuf_ptr += 1;
-			}
-		}
-		mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-		mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-	} else if (2 * feedSize == inFrameCount) {
-		if (feedSize) {
-			for (int i = 0, j = 0; i < feedSize; i++, j += 2) {
-				mixBufCurCell[i] += *((uint16 *)ampTable + srcBuf_ptr[j]);
-			}
-		}
-	} else {
-		residualLength = -inFrameCount;
-		if (feedSize) {
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[i] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-				// Seek the next srcBuf element until there's excess length
-				for (residualLength += inFrameCount; residualLength >= 0; ++srcBuf_ptr)
-					residualLength -= feedSize;
-			}
-		}
-	}
-}
-
-void IMuseDigiInternalMixer::mixBits12Mono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
-	uint16 *mixBufCurCell;
-	uint8 *srcBuf_ptr;
-	int xorFlag;
-	int residualLength;
-	int term_1;
-	int term_2;
-
-	if ((inFrameCount & 1) != 0) {
-		inFrameCount &= 0xFFFFFFFE;
-		debug(5, "DiMUSE_InternalMixer::mixBits12Mono(): WARNING: odd inFrameCount with 12-bit data");
-	}
-
-	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
-	if (feedSize == inFrameCount) {
-		if (inFrameCount / 2) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < inFrameCount / 2; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-				mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-				srcBuf_ptr += 3;
-				mixBufCurCell += 2;
-			}
-		}
-	} else if (2 * inFrameCount == feedSize) {
-		srcBuf_ptr = srcBuf;
-		if ((inFrameCount / 2) - 1) {
-			for (int i = 0; i < (inFrameCount / 2) - 1; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-
-				mixBufCurCell[1] += (*((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
-									 *((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))) >> 1;
-
-				mixBufCurCell[2] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-
-				mixBufCurCell[3] += (*((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
-									 *((int16 *)ampTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
-
-				srcBuf_ptr += 3;
-				mixBufCurCell += 4;
-			}
-		}
-
-		mixBufCurCell[0] +=  *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-		mixBufCurCell[1] +=  (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
-			                + *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
-		mixBufCurCell[2] +=  *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[3] +=  *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-	} else if (2 * feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[i] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-				srcBuf_ptr += 3;
-			}
-		}
-	} else {
-		xorFlag = 0;
-		residualLength = -inFrameCount;
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				if (xorFlag) {
-					term_1 = (srcBuf_ptr[1] & 0xF0) << 4;
-					term_2 = srcBuf_ptr[2];
-				} else {
-					term_1 = (srcBuf_ptr[1] & 0xF) << 8;
-					term_2 = srcBuf_ptr[0];
-				}
-
-				mixBufCurCell[i] += *((uint16 *)ampTable + (term_2 | term_1));
-				residualLength += inFrameCount;
-				while (residualLength >= 0) {
-					residualLength -= feedSize;
-					xorFlag ^= 1u;
-					if (!xorFlag)
-						srcBuf_ptr += 3;
-				}
-			}
-		}
-	}
-}
-
-void IMuseDigiInternalMixer::mixBits16Mono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
-	uint16 *mixBufCurCell;
-	uint16 *srcBuf_ptr;
-	int residualLength;
-
-	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
-	if (feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = (uint16 *)srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[i] += *(uint16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[i] & (int16)0xFFF7) >> 3) + 4096);
-			}
-		}
-	} else if (2 * inFrameCount == feedSize) {
-		srcBuf_ptr = (uint16 *)srcBuf;
-		int i = 0;
-		if (inFrameCount - 1 != 0) {
-			for (i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += *(uint16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[i] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[1] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[i] & (int16)0xFFF7) >> 3) + 4096)
-							       + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[i + 1] & (int16) 0xFFF7) >> 3) + 4096)) >> 1;
-				mixBufCurCell += 2;
-			}
-		}
-		mixBufCurCell[0] += *(uint16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[i] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[1] += *(uint16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[i] & (int16)0xFFF7) >> 3) + 4096);
-	} else {
-		if (2 * feedSize == inFrameCount) {
-			if (feedSize) {
-				srcBuf_ptr = (uint16 *)srcBuf;
-				for (int i = 0; i < feedSize; i++) {
-					mixBufCurCell[i] += *(uint16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-					srcBuf_ptr += 2;
-				}
-			}
-		} else {
-			residualLength = -inFrameCount;
-
-			if (feedSize) {
-				srcBuf_ptr = (uint16 *)srcBuf;
-				for (int i = 0; i < feedSize; i++) {
-					mixBufCurCell[i] += *(uint16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-
-					for (residualLength += inFrameCount; residualLength >= 0; ++srcBuf_ptr)
-						residualLength -= feedSize;
-				}
-			}
-		}
-	}
-}
-
-void IMuseDigiInternalMixer::mixBits8ConvertToMono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
-	uint8 *srcBuf_ptr;
-	int residualLength;
-	uint16 *mixBufCurCell;
-
-	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
-	srcBuf_ptr = srcBuf;
-	if (inFrameCount == feedSize) {
-		if (feedSize) {
-			for (int i = 0, j = 0; i < feedSize; i++, j += 2) {
-				mixBufCurCell[i] += (2 * *((int16 *)ampTable + srcBuf_ptr[j])) >> 1;
-			}
-		}
-	} else if (2 * inFrameCount == feedSize) {
-		if (inFrameCount != 1) {
-			for (int i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[0])) >> 1;
-				int term_1 = (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[3])) >> 1;
-				int term_2 =  *((int16 *)ampTable + srcBuf_ptr[0]) + *((int16 *)ampTable + srcBuf_ptr[2]);
-				mixBufCurCell[1] += ((term_2 >> 1) + term_1) >> 1;
-
-				srcBuf_ptr += 2;
-				mixBufCurCell += 2;
-			}
-		}
-		mixBufCurCell[0] += (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[0])) >> 1;
-		mixBufCurCell[1] += (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[0])) >> 1;
-	} else if (2 * feedSize == inFrameCount) {
-		if (feedSize) {
-			for (int i = 0, j = 0; i < feedSize; i++, j += 4) {
-				mixBufCurCell[i] += (2 * *((int16 *)ampTable + srcBuf_ptr[j])) >> 1;
-			}
-		}
-	} else {
-		residualLength = -inFrameCount;
-		if (feedSize) {
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[i] += (*((int16 *)ampTable + srcBuf_ptr[0]) + *((int16 *)ampTable + srcBuf_ptr[1])) >> 1;
-				// Skip srcBuf elements until there's excess length
-				for (residualLength += inFrameCount; residualLength >= 0; srcBuf_ptr += 2)
-					residualLength -= feedSize;
-			}
-		}
-	}
-}
-
-void IMuseDigiInternalMixer::mixBits12ConvertToMono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
-	uint8 *srcBuf_ptr;
-	int residualLength;
-	uint16 *mixBufCurCell;
-	int term_1;
-	int term_2;
-
-	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
-	if (feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[i] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8))) +
-									 *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
-				srcBuf_ptr += 3;
-			}
-		}
-	} else if (2 * inFrameCount == feedSize) {
-		srcBuf_ptr = srcBuf;
-		if (inFrameCount - 1 != 0) {
-			for (int i = 0; i < inFrameCount - 1; i++) {
-				term_1 = *((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF0) << 8)));
-				term_2 = *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF)  << 4)));
-
-				mixBufCurCell[0] += (term_1 + term_2) >> 1;
-				mixBufCurCell[1] += (((term_1 + *((int16 *)ampTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1)
-								   + ((term_2 + *((int16 *)ampTable + (srcBuf_ptr[5] | ((srcBuf_ptr[4] & 0xF0) << 4)))) >> 1)) >> 1;
-
-				srcBuf_ptr += 3;
-				mixBufCurCell += 2;
-			}
-		}
-
-		mixBufCurCell[0] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
-						   + *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
-		mixBufCurCell[1] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
-						   + *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
-
-
-	} else if (2 * feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-
-			for (int i = 0; i < feedSize; i++) {
-
-				mixBufCurCell[i] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
-								   + *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
-
-				srcBuf_ptr += 6;
-			}
-		}
-	} else {
-		residualLength = -inFrameCount;
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[i] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
-								   + *((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
-
-				for (residualLength += inFrameCount; residualLength >= 0; srcBuf_ptr += 3)
-					residualLength -= feedSize;
-			}
-		}
-	}
-}
-
-void IMuseDigiInternalMixer::mixBits16ConvertToMono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
-	uint16 *mixBufCurCell;
-	uint16 *srcBuf_ptr;
-	int residualLength;
-
-	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
-	if (feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = (uint16 *)srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[i] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)
-								   + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
-				srcBuf_ptr += 2;
-			}
-		}
-	} else if (2 * inFrameCount == feedSize) {
-		srcBuf_ptr = (uint16 *)srcBuf;
-		if (inFrameCount - 1 != 0) {
-			for (int i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)
-								   + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
-
-				mixBufCurCell[1] +=  (((*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)
-									+   *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[2] & (int16)0xFFF7) >> 3) + 4096)) >> 1)
-									+ ((*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)
-									+   *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[3] & (int16)0xFFF7) >> 3) + 4096)) >> 1)) >> 1;
-				mixBufCurCell += 2;
-				srcBuf_ptr += 2;
-			}
-		}
-
-		mixBufCurCell[0] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)
-						   + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
-		mixBufCurCell[1] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)
-						   + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
-	} else if (2 * feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = (uint16 *)srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[i] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)
-								   + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
-				srcBuf_ptr += 4;
-			}
-		}
-	} else {
-		residualLength = -inFrameCount;
-
-		if (feedSize) {
-			srcBuf_ptr = (uint16 *)srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[i] += (*(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096)
-								   + *(int16 *)((uint8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
-
-				for (residualLength += inFrameCount; residualLength >= 0; srcBuf_ptr += 2)
-					residualLength -= feedSize;
-			}
-		}
-	}
-}
-
-void IMuseDigiInternalMixer::mixBits8ConvertToStereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *leftAmpTable, int32 *rightAmpTable) {
-	uint16 *mixBufCurCell;
-	uint8 *srcBuf_ptr;
-	int residualLength;
-
-	mixBufCurCell = (uint16 *)(&_mixBuf[4 * mixBufStartIndex]);
-	if (feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
-				mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
-				mixBufCurCell += 2;
-			}
-		}
-	} else if (2 * inFrameCount == feedSize) {
-		srcBuf_ptr = srcBuf;
-		int i = 0;
-		if (inFrameCount - 1 != 0) {
-			for (i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
-				mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
-				mixBufCurCell[2] += (*((int16 *)leftAmpTable  + srcBuf_ptr[i]) + *((int16 *)leftAmpTable  + srcBuf_ptr[i + 1])) >> 1;
-				mixBufCurCell[3] += (*((int16 *)rightAmpTable + srcBuf_ptr[i]) + *((int16 *)rightAmpTable + srcBuf_ptr[i + 1])) >> 1;
-				mixBufCurCell += 4;
-			}
-		}
-		mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
-		mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
-		mixBufCurCell[2] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
-		mixBufCurCell[3] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
-	} else if (2 * feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[0]);
-				mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[0]);
-				mixBufCurCell += 2;
-				srcBuf_ptr += 2;
-			}
-		}
-	} else if (4 * inFrameCount == feedSize) {
-		srcBuf_ptr = srcBuf;
-		int i = 0;
-		if (inFrameCount - 1 != 0) {
-			for (i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
-				mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
-				mixBufCurCell[2] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
-				mixBufCurCell[3] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
-
-				mixBufCurCell[4] += (*((int16 *)leftAmpTable  + srcBuf_ptr[i]) + *((int16 *)leftAmpTable  + srcBuf_ptr[i + 1])) >> 1;
-				mixBufCurCell[5] += (*((int16 *)rightAmpTable + srcBuf_ptr[i]) + *((int16 *)rightAmpTable + srcBuf_ptr[i + 1])) >> 1;
-				mixBufCurCell[6] += (*((int16 *)leftAmpTable  + srcBuf_ptr[i]) + *((int16 *)leftAmpTable  + srcBuf_ptr[i + 1])) >> 1;
-				mixBufCurCell[7] += (*((int16 *)rightAmpTable + srcBuf_ptr[i]) + *((int16 *)rightAmpTable + srcBuf_ptr[i + 1])) >> 1;
-				mixBufCurCell += 8;
-			}
-		}
-		mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
-		mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
-		mixBufCurCell[2] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
-		mixBufCurCell[3] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
-
-		mixBufCurCell[4] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
-		mixBufCurCell[5] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
-		mixBufCurCell[6] += *((uint16 *)leftAmpTable  + srcBuf_ptr[i]);
-		mixBufCurCell[7] += *((uint16 *)rightAmpTable + srcBuf_ptr[i]);
-	} else {
-		residualLength = -inFrameCount;
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + srcBuf_ptr[0]);
-				mixBufCurCell[1] += *((uint16 *)rightAmpTable + srcBuf_ptr[0]);
-				mixBufCurCell += 2;
-
-				for (residualLength += inFrameCount; residualLength > 0; ++srcBuf_ptr)
-					residualLength -= feedSize;
-			}
-		}
-	}
-}
-
-void IMuseDigiInternalMixer::mixBits12ConvertToStereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *leftAmpTable, int32 *rightAmpTable) {
-	uint16 *mixBufCurCell;
-	uint8 *srcBuf_ptr;
-
-	int xorFlag;
-	int residualLength;
-
-	mixBufCurCell = (uint16 *)(&_mixBuf[4 * mixBufStartIndex]);
-	if (feedSize == inFrameCount) {
-		if (inFrameCount / 2) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < (inFrameCount / 2); i++) {
-				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-				mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-				mixBufCurCell[2] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-				mixBufCurCell[3] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-				srcBuf_ptr += 3;
-				mixBufCurCell += 4;
-			}
-		}
-	} else if (2 * inFrameCount == feedSize) {
-		srcBuf_ptr = srcBuf;
-		if ((inFrameCount / 2) - 1 != 0) {
-			for (int i = 0; i < (inFrameCount / 2) - 1; i++) {
-				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-				mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-
-				mixBufCurCell[2] += (*((int16 *)leftAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))
-								   + *((int16 *)leftAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))) >> 1;
-
-				mixBufCurCell[3] += (*((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))
-								   + *((int16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))) >> 1;
-
-				mixBufCurCell[4] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-				mixBufCurCell[5] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-
-				mixBufCurCell[6] += (*((int16 *)leftAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
-									 *((int16 *)leftAmpTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
-
-				mixBufCurCell[7] += (*((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
-									 *((int16 *)rightAmpTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
-
-				srcBuf_ptr += 3;
-				mixBufCurCell += 8;
-			}
-		}
-		mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-		mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-
-		mixBufCurCell[2] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
-						   + *((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
-
-		mixBufCurCell[3] += (*((int16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
-						   + *((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
-
-		mixBufCurCell[4] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[5] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[6] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[7] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-	} else if (2 * feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-				mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-				srcBuf_ptr += 3;
-				mixBufCurCell += 2;
-			}
-		}
-	} else if (4 * inFrameCount == feedSize) {
-		srcBuf_ptr = srcBuf;
-		if ((inFrameCount / 2) - 1 != 0) {
-			for (int i = 0; i < (inFrameCount / 2) - 1; i++) {
-				mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-				mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-				mixBufCurCell[2] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-				mixBufCurCell[3] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-
-				mixBufCurCell[4] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) + *((int16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)))) >> 1;
-				mixBufCurCell[5] += (*((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) + *((int16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)))) >> 1;
-				mixBufCurCell[6] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) + *((int16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)))) >> 1;
-				mixBufCurCell[7] += (*((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) + *((int16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)))) >> 1;
-
-				mixBufCurCell[8]  += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-				mixBufCurCell[9]  += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-				mixBufCurCell[10] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-				mixBufCurCell[11] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-
-				mixBufCurCell[12] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
-									  *((int16 *)leftAmpTable  + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
-				mixBufCurCell[13] += (*((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
-									  *((int16 *)rightAmpTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
-				mixBufCurCell[14] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
-									  *((int16 *)leftAmpTable  + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
-				mixBufCurCell[15] += (*((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) +
-									  *((int16 *)rightAmpTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
-
-				srcBuf_ptr += 3;
-				mixBufCurCell += 16;
-			}
-		}
-		mixBufCurCell[0] += *((uint16 *)leftAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-		mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-		mixBufCurCell[2] += *((uint16 *)leftAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-		mixBufCurCell[3] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8)));
-
-		mixBufCurCell[4] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8))) + *((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
-		mixBufCurCell[5] += (*((int16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8))) + *((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
-		mixBufCurCell[6] += (*((int16 *)leftAmpTable  + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8))) + *((int16 *)leftAmpTable  + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
-		mixBufCurCell[7] += (*((int16 *)rightAmpTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF) << 8))) + *((int16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))) >> 1;
-
-		mixBufCurCell[8] += *((uint16 *)leftAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[9] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[10] += *((uint16 *)leftAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[11] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-
-		mixBufCurCell[12] += *((uint16 *)leftAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[13] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[14] += *((uint16 *)leftAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[15] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-	} else {
-		xorFlag = 0;
-		residualLength = -inFrameCount;
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				if (xorFlag) {
-					mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[2] | (srcBuf_ptr[1] & 0xF0) << 4));
-					mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[2] | (srcBuf_ptr[1] & 0xF0) << 4));
-				} else {
-					mixBufCurCell[0] += *((uint16 *)leftAmpTable  + (srcBuf_ptr[0] | (srcBuf_ptr[1] & 0xF)  << 8));
-					mixBufCurCell[1] += *((uint16 *)rightAmpTable + (srcBuf_ptr[0] | (srcBuf_ptr[1] & 0xF)  << 8));
-				}
-
-				residualLength += inFrameCount;
-				while (residualLength > 0) {
-					residualLength -= feedSize;
-					xorFlag ^= 1u;
-					if (!xorFlag)
-						srcBuf_ptr += 3;
-				}
-
-				mixBufCurCell += 2;
-			}
-		}
-	}
-}
-
-void IMuseDigiInternalMixer::mixBits16ConvertToStereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *leftAmpTable, int32 *rightAmpTable) {
-	uint16 *mixBufCurCell;
-	uint16 *srcBuf_tmp;
-	int residualLength;
-
-	mixBufCurCell = (uint16 *)(&_mixBuf[2 * mixBufStartIndex]);
-
-	if (feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_tmp = (uint16 *)srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell += 2;
-			}
-		}
-	} else if (2 * inFrameCount == feedSize) {
-		srcBuf_tmp = (uint16 *)srcBuf;
-		int i = 0;
-		if (inFrameCount - 1 != 0) {
-			for (i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-
-				mixBufCurCell[2] += (*(int16 *)((uint8 *)leftAmpTable + (((int16)srcBuf_tmp[i]     & (int16)0xFFF7) >> 3) + 4096)
-								   + *(int16 *)((uint8 *)leftAmpTable + (((int16)srcBuf_tmp[i + 1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
-
-				mixBufCurCell[3] += (*(int16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i]     & (int16)0xFFF7) >> 3) + 4096)
-								   + *(int16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i + 1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
-				mixBufCurCell += 4;
-			}
-		}
-		mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[2] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[3] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-	} else if (2 * feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_tmp = (uint16 *)srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[0] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[0] & (int16)0xFFF7) >> 3) + 4096);
-				srcBuf_tmp += 2;
-				mixBufCurCell += 2;
-			}
-		}
-	} else if (4 * inFrameCount == feedSize) {
-		srcBuf_tmp = (uint16 *)srcBuf;
-		int i = 0;
-		if (inFrameCount - 1 != 0) {
-			for (i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[2] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[3] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-
-				mixBufCurCell[4] += (*(int16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096) + *(int16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i + 1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
-				mixBufCurCell[5] += (*(int16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096) + *(int16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i + 1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
-				mixBufCurCell[6] += (*(int16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096) + *(int16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i + 1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
-				mixBufCurCell[7] += (*(int16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096) + *(int16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i + 1] & (int16)0xFFF7) >> 3) + 4096)) >> 1;
-				mixBufCurCell += 8;
-			}
-		}
-		mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[2] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[3] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-
-		mixBufCurCell[4] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[5] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[6] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[7] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[i] & (int16)0xFFF7) >> 3) + 4096);
-	} else {
-		residualLength = -inFrameCount;
-		if (feedSize) {
-			srcBuf_tmp = (uint16 *)srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *(uint16 *)((uint8 *)leftAmpTable  + (((int16)srcBuf_tmp[0] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[1] += *(uint16 *)((uint8 *)rightAmpTable + (((int16)srcBuf_tmp[0] & (int16)0xFFF7) >> 3) + 4096);
-
-				for (residualLength += inFrameCount; residualLength > 0; ++srcBuf_tmp)
-					residualLength -= feedSize;
-
-				mixBufCurCell += 2;
-			}
-		}
-	}
-}
-
-void IMuseDigiInternalMixer::mixBits8Stereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
-	uint16 *mixBufCurCell;
-	uint8 *srcBuf_ptr;
-	int residualLength;
-
-	mixBufCurCell = (uint16 *)(&_mixBuf[4 * mixBufStartIndex]);
-	if (feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-				mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
-				srcBuf_ptr += 2;
-				mixBufCurCell += 2;
-			}
-		}
-	} else if (2 * inFrameCount == feedSize) {
-		srcBuf_ptr = srcBuf;
-		if (inFrameCount - 1 != 0) {
-			for (int i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-				mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
-				mixBufCurCell[2] += (*((int16 *)ampTable + srcBuf_ptr[0]) + *((int16 *)ampTable + srcBuf_ptr[2])) >> 1;
-				mixBufCurCell[3] += (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[3])) >> 1;
-				mixBufCurCell += 4;
-				srcBuf_ptr += 2;
-			}
-		}
-		mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-		mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
-		mixBufCurCell[2] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-		mixBufCurCell[3] += *((uint16 *)ampTable + srcBuf_ptr[1]);
-	} else if (2 * feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-				mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
-				srcBuf_ptr += 4;
-				mixBufCurCell += 2;
-			}
-		}
-	} else if (4 * inFrameCount == feedSize) {
-		srcBuf_ptr = srcBuf;
-		if (inFrameCount - 1 != 0) {
-			for (int i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-				mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
-				mixBufCurCell[2] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-				mixBufCurCell[3] += *((uint16 *)ampTable + srcBuf_ptr[1]);
-
-				mixBufCurCell[4] += (*((int16 *)ampTable + srcBuf_ptr[0]) + *((int16 *)ampTable + srcBuf_ptr[2])) >> 1;
-				mixBufCurCell[5] += (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[3])) >> 1;
-				mixBufCurCell[6] += (*((int16 *)ampTable + srcBuf_ptr[0]) + *((int16 *)ampTable + srcBuf_ptr[2])) >> 1;
-				mixBufCurCell[7] += (*((int16 *)ampTable + srcBuf_ptr[1]) + *((int16 *)ampTable + srcBuf_ptr[3])) >> 1;
-
-				mixBufCurCell += 8;
-				srcBuf_ptr += 2;
-			}
-		}
-		mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-		mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
-		mixBufCurCell[2] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-		mixBufCurCell[3] += *((uint16 *)ampTable + srcBuf_ptr[1]);
-
-		mixBufCurCell[4] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-		mixBufCurCell[5] += *((uint16 *)ampTable + srcBuf_ptr[1]);
-		mixBufCurCell[6] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-		mixBufCurCell[7] += *((uint16 *)ampTable + srcBuf_ptr[1]);
-	} else {
-		residualLength = -inFrameCount;
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + srcBuf_ptr[0]);
-				mixBufCurCell[1] += *((uint16 *)ampTable + srcBuf_ptr[1]);
-				mixBufCurCell += 2;
-				for (residualLength += inFrameCount; residualLength >= 0; srcBuf_ptr += 2)
-					residualLength -= feedSize;
-			}
-		}
-	}
-}
-
-void IMuseDigiInternalMixer::mixBits12Stereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
-	uint16 *mixBufCurCell;
-	uint8 *srcBuf_ptr;
-	int residualLength;
-
-	mixBufCurCell = (uint16 *)(&_mixBuf[4 * mixBufStartIndex]);
-	if (feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-				mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-
-				srcBuf_ptr += 3;
-				mixBufCurCell += 2;
-			}
-		}
-	} else if (2 * inFrameCount == feedSize) {
-		srcBuf_ptr = srcBuf;
-		if (inFrameCount - 1 != 0) {
-			for (int i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-				mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-				mixBufCurCell[2] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)))
-								   + *((int16 *)ampTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
-				mixBufCurCell[3] += (*((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)))
-								   + *((int16 *)ampTable + (srcBuf_ptr[5] | ((srcBuf_ptr[4] & 0xF0) << 4)))) >> 1;
-
-				srcBuf_ptr += 3;
-				mixBufCurCell += 4;
-			}
-		}
-		mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-		mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[2] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-		mixBufCurCell[3] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-	} else if (2 * feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-				mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-
-				srcBuf_ptr += 6;
-				mixBufCurCell += 2;
-			}
-		}
-	} else if (4 * inFrameCount == feedSize) {
-		srcBuf_ptr = srcBuf;
-		if (inFrameCount - 1 != 0) {
-			for (int i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-				mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-				mixBufCurCell[2] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-				mixBufCurCell[3] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-
-				mixBufCurCell[4] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8))) + *((int16 *)ampTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
-				mixBufCurCell[5] += (*((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) + *((int16 *)ampTable + (srcBuf_ptr[5] | ((srcBuf_ptr[4] & 0xF0) << 4)))) >> 1;
-				mixBufCurCell[6] += (*((int16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8))) + *((int16 *)ampTable + (srcBuf_ptr[3] | ((srcBuf_ptr[4] & 0xF)  << 8)))) >> 1;
-				mixBufCurCell[7] += (*((int16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4))) + *((int16 *)ampTable + (srcBuf_ptr[5] | ((srcBuf_ptr[4] & 0xF0) << 4)))) >> 1;
-
-				srcBuf_ptr += 3;
-				mixBufCurCell += 8;
-			}
-		}
-		mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-		mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[2] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-		mixBufCurCell[3] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-
-		mixBufCurCell[4] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-		mixBufCurCell[5] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-		mixBufCurCell[6] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-		mixBufCurCell[7] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-	} else {
-		residualLength = -inFrameCount;
-		if (feedSize) {
-			srcBuf_ptr = srcBuf;
-
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *((uint16 *)ampTable + (srcBuf_ptr[0] | ((srcBuf_ptr[1] & 0xF)  << 8)));
-				mixBufCurCell[1] += *((uint16 *)ampTable + (srcBuf_ptr[2] | ((srcBuf_ptr[1] & 0xF0) << 4)));
-
-				mixBufCurCell += 2;
-				for (residualLength += inFrameCount; residualLength >= 0; srcBuf_ptr += 3)
-					residualLength -= feedSize;
-			}
-		}
-	}
-}
-
-void IMuseDigiInternalMixer::mixBits16Stereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable) {
-	uint16 *mixBufCurCell;
-	uint16 *srcBuf_ptr;
-	int residualLength;
-
-	mixBufCurCell = (uint16 *)(&_mixBuf[4 * mixBufStartIndex]);
-	if (feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = (uint16 *)srcBuf;
-
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-				srcBuf_ptr += 2;
-				mixBufCurCell += 2;
-			}
-		}
-	} else if (2 * inFrameCount == feedSize) {
-		srcBuf_ptr = (uint16 *)srcBuf;
-
-		if (inFrameCount - 1 != 0) {
-			for (int i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[2] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[3] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-
-				mixBufCurCell += 4;
-				srcBuf_ptr += 2;
-			}
-		}
-		mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[2] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[3] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-
-	} else if (2 * feedSize == inFrameCount) {
-		if (feedSize) {
-			srcBuf_ptr = (uint16 *)srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + ((((int16)srcBuf_ptr[0] & (int16)0xFFF7)) >> 3) + 4096);
-				mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + ((((int16)srcBuf_ptr[1] & (int16)0xFFF7)) >> 3) + 4096);
-				mixBufCurCell += 2;
-				srcBuf_ptr += 4;
-			}
-		}
-	} else if (4 * inFrameCount == feedSize) {
-		srcBuf_ptr = (uint16 *)srcBuf;
-
-		if (inFrameCount - 1 != 0) {
-			for (int i = 0; i < inFrameCount - 1; i++) {
-				mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[2] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[3] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-
-				mixBufCurCell[4] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[5] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[6] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[7] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-
-				mixBufCurCell += 8;
-				srcBuf_ptr += 2;
-			}
-		}
-		mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[2] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[3] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-
-		mixBufCurCell[4] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[5] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[6] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-		mixBufCurCell[7] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-
-	} else {
-		residualLength = -inFrameCount;
-		if (feedSize) {
-			srcBuf_ptr = (uint16 *)srcBuf;
-			for (int i = 0; i < feedSize; i++) {
-				mixBufCurCell[0] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[0] & (int16)0xFFF7) >> 3) + 4096);
-				mixBufCurCell[1] += *(uint16 *)((int8 *)ampTable + (((int16)srcBuf_ptr[1] & (int16)0xFFF7) >> 3) + 4096);
-
-				for (residualLength += inFrameCount; residualLength >= 0; srcBuf_ptr += 2)
-					residualLength -= feedSize;
-			}
-		}
-	}
-}
-
 } // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_internalmixer.h b/engines/grim/imuse/dimuse_internalmixer.h
index 65c9da545f4..6aa0a4cea87 100644
--- a/engines/grim/imuse/dimuse_internalmixer.h
+++ b/engines/grim/imuse/dimuse_internalmixer.h
@@ -43,50 +43,34 @@ namespace Grim {
 class IMuseDigiInternalMixer {
 
 private:
-	int32 *_amp8Table = nullptr;
-	int32 *_amp12Table = nullptr;
-	int32 *_softLMID = nullptr;
-	int32 *_softLTable = nullptr;
+	uint8 _mixerTable[17 * 17];
+	int16 *_softLTable = nullptr;
 
-	uint8 *_mixBuf = nullptr;
+	int32 *_mixBuf = nullptr;
 
 	Audio::Mixer *_mixer;
 	Audio::SoundHandle _channelHandle;
 	int _mixBufSize = 0;
-	int _outWordSize = 0;
 	int _outChannelCount = 0;
 	int _sampleRate = 0;
-	int _stereoReverseFlag = 0;
 	bool _lowLatencyMode = false;
 
-	void mixBits8Mono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
-	void mixBits12Mono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
-	void mixBits16Mono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
-
-	void mixBits8ConvertToMono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
-	void mixBits12ConvertToMono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
-	void mixBits16ConvertToMono(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
-
-	void mixBits8ConvertToStereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *leftAmpTable, int32 *rightAmpTable);
-	void mixBits12ConvertToStereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *leftAmpTable, int32 *rightAmpTable);
-	void mixBits16ConvertToStereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *leftAmpTable, int32 *rightAmpTable);
-
-	void mixBits8Stereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
-	void mixBits12Stereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
-	void mixBits16Stereo(uint8 *srcBuf, int32 inFrameCount, int feedSize, int32 mixBufStartIndex, int32 *ampTable);
+	void mix16(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int volume);
+	void mix16Swap(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int volume);
+	void mix16ToStereo(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int leftAmp, int rightAmp);
+	void mix16ToStereoSwap(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int leftAmp, int rightAmp);
 
 public:
 	IMuseDigiInternalMixer(Audio::Mixer *mixer, int sampleRate, bool lowLatencyMode = false);
 	~IMuseDigiInternalMixer();
-	int  init(int bytesPerSample, int numChannels, uint8 *mixBuf, int mixBufSize, int sizeSampleKB, int mixChannelsNum);
+	int  init(int numChannels, int mixBufSize, int mixChannelsNum);
 	int  clearMixerBuffer();
 
-	void mix(uint8 *srcBuf, int32 inFrameCount, int wordSize, int channelCount, int feedSize, int32 mixBufStartIndex, int volume, int pan);
+	void mix(uint8 *srcBuf, int32 inFrameCount, int wordSize, int channelCount, int swapEndiannessFlag, int feedSize, int32 mixBufStartIndex, int volume, int pan);
 	int  loop(uint8 **destBuffer, int len);
 	Audio::QueuingAudioStream *_stream;
 
 	// For low latency audio
-	void setCurrentMixerBuffer(uint8 *newBuf);
 	void endStream(int idx);
 	Audio::QueuingAudioStream *getStream(int idx);
 
diff --git a/engines/grim/imuse/dimuse_tracks.cpp b/engines/grim/imuse/dimuse_tracks.cpp
index 11dd20873a2..c444c3ad13f 100644
--- a/engines/grim/imuse/dimuse_tracks.cpp
+++ b/engines/grim/imuse/dimuse_tracks.cpp
@@ -31,11 +31,8 @@ int IMuseDigital::tracksInit() {
 	if (waveOutInit(&waveOutSettings))
 		return -1;
 
-	if (_internalMixer->init(waveOutSettings.bytesPerSample,
-			waveOutSettings.numChannels,
-			waveOutSettings.mixBuf,
+	if (_internalMixer->init(waveOutSettings.numChannels,
 			waveOutSettings.mixBufSize,
-			waveOutSettings.sizeSampleKB,
 			_trackCount) ||
 			dispatchInit() ||
 		streamerInit()) {
@@ -218,7 +215,6 @@ void IMuseDigital::tracksLowLatencyCallback() {
 
 			if (_outputFeedSize != 0) {
 				// Ordinary audio tracks handling...
-				_internalMixer->setCurrentMixerBuffer(_outputLowLatencyAudioBuffers[idx]);
 				_internalMixer->clearMixerBuffer();
 
 				if (!_tracksPauseTimer) {


Commit: 3b0a8cba6f9140ee399157b7fcf3ae847f6c872e
    https://github.com/scummvm/scummvm/commit/3b0a8cba6f9140ee399157b7fcf3ae847f6c872e
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Port muscript section

Also, some clean-up...

Changed paths:
    engines/grim/imuse/dimuse_cmds.cpp
    engines/grim/imuse/dimuse_dispatch.cpp
    engines/grim/imuse/dimuse_engine.cpp
    engines/grim/imuse/dimuse_engine.h
    engines/grim/imuse/dimuse_fades.cpp
    engines/grim/imuse/dimuse_fades.h
    engines/grim/imuse/dimuse_files.cpp
    engines/grim/imuse/dimuse_internalmixer.cpp
    engines/grim/imuse/dimuse_internalmixer.h
    engines/grim/imuse/dimuse_scripts.cpp
    engines/grim/imuse/dimuse_tables.cpp
    engines/grim/imuse/dimuse_tables.h
    engines/grim/imuse/dimuse_triggers.cpp
    engines/grim/imuse/dimuse_triggers.h


diff --git a/engines/grim/imuse/dimuse_cmds.cpp b/engines/grim/imuse/dimuse_cmds.cpp
index b4a322b4c7a..eea1dc03cca 100644
--- a/engines/grim/imuse/dimuse_cmds.cpp
+++ b/engines/grim/imuse/dimuse_cmds.cpp
@@ -28,18 +28,7 @@ namespace Grim {
 int IMuseDigital::cmdsHandleCmd(int cmd, uint8 *ptr, int a, int b, int c, int d, int e,
 	int f, int g, int h, int i, int j, int k, int l, int m, int n) {
 
-	// Convert the character constant (single quotes '') to string
-	char marker[5];
-	if (cmd == 17 || cmd == 18 || cmd == 19) {
-		for (int index = 0; index < 4; index++) {
-#if defined SCUMM_BIG_ENDIAN
-			marker[index] = (b >> (8 * index)) & 0xff;
-#elif defined SCUMM_LITTLE_ENDIAN
-			marker[3 - index] = (b >> (8 * index)) & 0xff;
-#endif
-		}
-		marker[4] = '\0';
-	}
+	char *marker = (char *)ptr;
 
 	switch (cmd) {
 	case DIMUSE_C_INIT:
@@ -112,8 +101,6 @@ int IMuseDigital::cmdsInit() {
 int IMuseDigital::cmdsDeinit() {
 	waveTerminate();
 	waveOutDeinit();
-	_triggersHandler->deinit();
-	_fadesHandler->deinit();
 	_cmdsPauseCount = 0;
 	_cmdsRunning60HzCount = 0;
 	_cmdsRunning10HzCount = 0;
@@ -176,7 +163,7 @@ void IMuseDigital::cmdsSaveLoad(Common::Serializer &ser) {
 	ser.syncAsSint32LE(_curMusicState, VER(103));
 	ser.syncAsSint32LE(_curMusicSeq, VER(103));
 	ser.syncAsSint32LE(_nextSeqToPlay, VER(103));
-	ser.syncArray(_attributes, 188, Common::Serializer::Sint32LE, VER(103));
+	ser.syncArray(_attributes, ARRAYSIZE(_attributes), Common::Serializer::Sint32LE, VER(103));
 }
 
 int IMuseDigital::cmdsStartSound(int soundId, int priority) {
diff --git a/engines/grim/imuse/dimuse_dispatch.cpp b/engines/grim/imuse/dimuse_dispatch.cpp
index 9306005f47c..ef7f717b76e 100644
--- a/engines/grim/imuse/dimuse_dispatch.cpp
+++ b/engines/grim/imuse/dimuse_dispatch.cpp
@@ -81,6 +81,12 @@ int IMuseDigital::dispatchInit() {
 	return 0;
 }
 
+int IMuseDigital::dispatchTerminate() {
+	free(_dispatchBuffer);
+	_dispatchBuffer = nullptr;
+	return 0;
+}
+
 IMuseDigiDispatch *IMuseDigital::dispatchGetDispatchByTrackId(int trackId) {
 	return &_dispatches[trackId];
 }
diff --git a/engines/grim/imuse/dimuse_engine.cpp b/engines/grim/imuse/dimuse_engine.cpp
index 08c3b69763c..b2b1bdfdf21 100644
--- a/engines/grim/imuse/dimuse_engine.cpp
+++ b/engines/grim/imuse/dimuse_engine.cpp
@@ -68,7 +68,6 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 
 	_dispatchFadeSize = 0;
 
-	_stopSequenceFlag = 0;
 	_scriptInitializedFlag = 0;
 	_callbackInterruptFlag = 0;
 	_spooledMusicEnabled = true;
@@ -134,8 +133,7 @@ IMuseDigital::~IMuseDigital() {
 	delete _filesHandler;
 
 	// Deinit the Dispatch module
-	free(_dispatchBuffer);
-	_dispatchBuffer = nullptr;
+	dispatchTerminate();
 
 	// Deinit the WaveOut module
 	free(_waveOutOutputBuffer);
@@ -490,8 +488,8 @@ int IMuseDigital::diMUSESetHook(int soundId, int hookId) {
 	return cmdsHandleCmd(DIMUSE_C_SET_HOOK, nullptr, soundId, hookId);
 }
 
-int IMuseDigital::diMUSESetTrigger(int soundId, int marker, int opcode, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
-	return cmdsHandleCmd(DIMUSE_C_SET_TRIGGER, nullptr, soundId, marker, opcode, d, e, f, g, h, i, j, k, l, m, n);
+int IMuseDigital::diMUSESetTrigger(int soundId, const char *marker, int opcode, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
+	return cmdsHandleCmd(DIMUSE_C_SET_TRIGGER, (uint8 *)marker, soundId, 0, opcode, d, e, f, g, h, i, j, k, l, m, n);
 }
 
 int IMuseDigital::diMUSEStartStream(int soundId, int priority, int bufferId) {
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/dimuse_engine.h
index 2be1d2e60d7..3fb5845d0d5 100644
--- a/engines/grim/imuse/dimuse_engine.h
+++ b/engines/grim/imuse/dimuse_engine.h
@@ -50,7 +50,7 @@ class QueuingAudioStream;
 
 namespace Grim {
 
-struct imuseComiTable;
+struct IMuseDigiStateTable;
 struct IMuseDigiDispatch;
 struct IMuseDigiTrack;
 struct IMuseDigiStreamZone;
@@ -92,12 +92,11 @@ private:
 	int _currentSpeechVolume, _currentSpeechFrequency, _currentSpeechPan;
 	int _curMixerMusicVolume, _curMixerSpeechVolume, _curMixerSFXVolume;
 
-	int32 _attributes[188];	// internal attributes for each music file to store and check later
+	int32 _attributes[228];	// internal attributes for each music file to store and check later
 	int32 _nextSeqToPlay;
 	int32 _curMusicState;
 	int32 _curMusicSeq;
 
-	int _stopSequenceFlag;
 	int _scriptInitializedFlag;
 	char _emptyMarker[1];
 	bool _spooledMusicEnabled;
@@ -106,9 +105,6 @@ private:
 	int _callbackInterruptFlag;
 	void diMUSEHeartbeat();
 
-	void setComiMusicState(int stateId);
-	void setComiMusicSequence(int seqId);
-	void playComiMusic(const char *songName, const imuseComiTable *table, int attribPos, bool sequence);
 	bool isMusicStreamIdle();
 	bool isMusicCritical();
 
@@ -116,9 +112,11 @@ private:
 	int scriptParse(int cmd, int a, int b);
 	int scriptInit();
 	int scriptTerminate();
+	void scriptDeinit();
 	void scriptRefresh();
 	void scriptSetState(int soundId);
 	void scriptSetSequence(int soundId);
+	void scriptPlayMusic(const IMuseDigiStateTable *tableEntry, int curSongEntryId, int isSequence);
 	void scriptSetCuePoint(int cueId);
 	int scriptSetAttribute(int attrIndex, int attrVal);
 
@@ -209,6 +207,7 @@ private:
 	int _dispatchCurStreamPaused;
 
 	int dispatchInit();
+	int dispatchTerminate();
 	IMuseDigiDispatch *dispatchGetDispatchByTrackId(int trackId);
 	void dispatchSaveLoad(Common::Serializer &ser);
 	int dispatchRestoreStreamZones();
@@ -326,7 +325,7 @@ public:
 	int diMUSEFadeParam(int soundId, int opcode, int destValue, int fadeLength);
 	int diMUSESetHook(int soundId, int hookId);
 
-	int diMUSESetTrigger(int soundId, int marker, int opcode,
+	int diMUSESetTrigger(int soundId, const char *marker, int opcode,
 		int d = -1, int e = -1, int f = -1, int g = -1,
 		int h = -1, int i = -1, int j = -1, int k = -1,
 		int l = -1, int m = -1, int n = -1);
diff --git a/engines/grim/imuse/dimuse_fades.cpp b/engines/grim/imuse/dimuse_fades.cpp
index 21bfacb3706..9746af60820 100644
--- a/engines/grim/imuse/dimuse_fades.cpp
+++ b/engines/grim/imuse/dimuse_fades.cpp
@@ -136,10 +136,6 @@ void IMuseDigiFadesHandler::loop() {
 	}
 }
 
-void IMuseDigiFadesHandler::deinit() {
-	clearAllFades();
-}
-
 void IMuseDigiFadesHandler::saveLoad(Common::Serializer &ser) {
 	for (int l = 0; l < DIMUSE_MAX_FADES; l++) {
 		ser.syncAsSint32LE(_fades[l].status, VER(103));
diff --git a/engines/grim/imuse/dimuse_fades.h b/engines/grim/imuse/dimuse_fades.h
index 15458b3a5e9..f8997edfeea 100644
--- a/engines/grim/imuse/dimuse_fades.h
+++ b/engines/grim/imuse/dimuse_fades.h
@@ -42,7 +42,6 @@ public:
 	~IMuseDigiFadesHandler();
 
 	int init();
-	void deinit();
 	void saveLoad(Common::Serializer &ser);
 	int fadeParam(int soundId, int opcode, int destinationValue, int fadeLength);
 	void clearFadeStatus(int soundId, int opcode);
diff --git a/engines/grim/imuse/dimuse_files.cpp b/engines/grim/imuse/dimuse_files.cpp
index 60db6b6f840..5b26ad88cc1 100644
--- a/engines/grim/imuse/dimuse_files.cpp
+++ b/engines/grim/imuse/dimuse_files.cpp
@@ -244,21 +244,22 @@ void IMuseDigiFilesHandler::getFilenameFromSoundId(int soundId, char *fileName,
 		return;
 	}
 
+	// TODO
 	if (soundId < 2000) {
-		while (_comiStateMusicTable[i].soundId != -1) {
-			if (_comiStateMusicTable[i].soundId == soundId) {
-				Common::strlcpy(fileName, _comiStateMusicTable[i].filename, size);
+		for (i = 0; i < ARRAYSIZE(_grimStateMusicTable); i++) {
+			if (_grimStateMusicTable[i].soundId == soundId) {
+				Common::strlcpy(fileName, _grimStateMusicTable[i].name, size);
+				Common::strlcat(fileName, ".IMC", size);
 				return;
 			}
-			i++;
 		}
 	} else {
-		while (_comiSeqMusicTable[i].soundId != -1) {
-			if (_comiSeqMusicTable[i].soundId == soundId) {
-				Common::strlcpy(fileName, _comiSeqMusicTable[i].filename, size);
+		for (i = 0; i < ARRAYSIZE(_grimSeqMusicTable); i++) {
+			if (_grimSeqMusicTable[i].soundId == soundId) {
+				Common::strlcpy(fileName, _grimSeqMusicTable[i].name, size);
+				Common::strlcat(fileName, ".IMC", size);
 				return;
 			}
-			i++;
 		}
 	}
 }
diff --git a/engines/grim/imuse/dimuse_internalmixer.cpp b/engines/grim/imuse/dimuse_internalmixer.cpp
index 62aa45331ac..a1d2f3566be 100644
--- a/engines/grim/imuse/dimuse_internalmixer.cpp
+++ b/engines/grim/imuse/dimuse_internalmixer.cpp
@@ -47,10 +47,15 @@ IMuseDigiInternalMixer::IMuseDigiInternalMixer(Audio::Mixer *mixer, int sampleRa
 }
 
 IMuseDigiInternalMixer::~IMuseDigiInternalMixer() {
+	terminate();
+}
+
+int IMuseDigiInternalMixer::terminate() {
 	free(_softLTable);
 	free(_mixBuf);
 	_softLTable = nullptr;
 	_mixBuf = nullptr;
+	return 0;
 }
 
 int IMuseDigiInternalMixer::init(int numChannels, int mixBufSize, int mixChannelsNum) {
diff --git a/engines/grim/imuse/dimuse_internalmixer.h b/engines/grim/imuse/dimuse_internalmixer.h
index 6aa0a4cea87..c4852c3be04 100644
--- a/engines/grim/imuse/dimuse_internalmixer.h
+++ b/engines/grim/imuse/dimuse_internalmixer.h
@@ -64,6 +64,7 @@ public:
 	IMuseDigiInternalMixer(Audio::Mixer *mixer, int sampleRate, bool lowLatencyMode = false);
 	~IMuseDigiInternalMixer();
 	int  init(int numChannels, int mixBufSize, int mixChannelsNum);
+	int  terminate();
 	int  clearMixerBuffer();
 
 	void mix(uint8 *srcBuf, int32 inFrameCount, int wordSize, int channelCount, int swapEndiannessFlag, int feedSize, int32 mixBufStartIndex, int volume, int pan);
diff --git a/engines/grim/imuse/dimuse_scripts.cpp b/engines/grim/imuse/dimuse_scripts.cpp
index ad59785eb91..f387f4339bb 100644
--- a/engines/grim/imuse/dimuse_scripts.cpp
+++ b/engines/grim/imuse/dimuse_scripts.cpp
@@ -23,7 +23,9 @@
 
 namespace Grim {
 
-#define COMI_STATE_OFFSET 3
+#define GRIM_STATE_OFFSET   3
+#define GRIM_SEQ_OFFSET     185
+#define GRIM_STOP_SEQ_ATTR  227
 
 int IMuseDigital::scriptParse(int cmd, int a, int b) {
 	if (_scriptInitializedFlag || !cmd) {
@@ -77,7 +79,7 @@ int IMuseDigital::scriptInit() {
 }
 
 int IMuseDigital::scriptTerminate() {
-	diMUSETerminate();
+	scriptDeinit();
 
 	_curMusicState = 0;
 	_curMusicSeq = 0;
@@ -88,290 +90,304 @@ int IMuseDigital::scriptTerminate() {
 
 void IMuseDigital::scriptRefresh() {
 	int soundId;
-	int nextSound;
 
-	if (_stopSequenceFlag) {
+	if (_attributes[GRIM_STOP_SEQ_ATTR]) {
 		scriptSetSequence(0);
-		_stopSequenceFlag = 0;
+		_attributes[GRIM_STOP_SEQ_ATTR] = 0;
 	}
 
-	soundId = 0;
-
-	while (1) {
-		nextSound = diMUSEGetNextSound(soundId);
-		soundId = nextSound;
-
-		if (!nextSound)
+	soundId = diMUSEGetNextSound(0);
+	while (soundId) {
+		if (diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM) && diMUSEGetParam(soundId, DIMUSE_P_STREAM_BUFID) == DIMUSE_BUFFER_MUSIC)
 			break;
 
-		if (diMUSEGetParam(nextSound, DIMUSE_P_SND_HAS_STREAM) && diMUSEGetParam(soundId, DIMUSE_P_STREAM_BUFID) == DIMUSE_BUFFER_MUSIC) {
-			if (soundId)
-				return;
-			break;
-		}
+		soundId = diMUSEGetNextSound(soundId);
 	}
 
-	if (_curMusicSeq)
-		scriptSetSequence(0);
+	if (!soundId) {
+		if (_curMusicSeq)
+			scriptSetSequence(0);
+	}
 
 	flushTracks();
 }
 
-void IMuseDigital::scriptSetState(int soundId) {
-	setComiMusicState(soundId);
-}
-
-void IMuseDigital::scriptSetSequence(int soundId) {
-	setComiMusicSequence(soundId);
-}
-
-void IMuseDigital::scriptSetCuePoint(int cueId) {
-}
+void IMuseDigital::scriptSetState(int stateId) {
+	int num;
 
-int IMuseDigital::scriptSetAttribute(int attrIndex, int attrVal) {
-	return 0;
-}
-
-int IMuseDigital::scriptTriggerCallback(char *marker) {
-	if (marker[0] != '_') {
-		debug(5, "IMuseDigital::scriptTriggerCallback(): got marker != '_end', callback ignored");
-		return -1;
-	}
-	_stopSequenceFlag = 1;
-	return 0;
-}
-
-
-void IMuseDigital::setComiMusicState(int stateId) {
-	int l, num = -1;
-
-	if (stateId == 0)
-		stateId = 1000;
+	if (stateId == -1)
+		return;
 
-	for (l = 0; _comiStateMusicTable[l].soundId != -1; l++) {
-		if ((_comiStateMusicTable[l].soundId == stateId)) {
-			debug(5, "IMuseDigital::setComiMusicState(): Set music state: %s, %s", _comiStateMusicTable[l].name, _comiStateMusicTable[l].filename);
-			num = l;
+	for (num = 0; num < ARRAYSIZE(_grimStateMusicTable); num++) {
+		if (_grimStateMusicTable[num].soundId == stateId)
 			break;
-		}
 	}
 
-	if (num == -1)
+	if (num == ARRAYSIZE(_grimStateMusicTable))
 		return;
 
-	if (_curMusicState == num)
-		return;
+	debug(5, "IMuseDigital::scriptSetState(): Set music state: %s", _grimStateMusicTable[num].internalName);
 
-	if (_curMusicSeq == 0) {
-		if (num == 0)
-			playComiMusic(nullptr, &_comiStateMusicTable[0], num, false);
-		else
-			playComiMusic(_comiStateMusicTable[num].name, &_comiStateMusicTable[num], num, false);
-	}
+	if (num != _curMusicState) {
+		if (!_curMusicSeq)
+			scriptPlayMusic(num ? &_grimStateMusicTable[num] : nullptr, num, false);
 
-	_curMusicState = num;
+		_curMusicState = num;
+	}
 }
 
-void IMuseDigital::setComiMusicSequence(int seqId) {
-	int l, num = -1;
+void IMuseDigital::scriptSetSequence(int seqId) {
+	int num;
+
+	if (seqId == -1)
+		return;
 
 	if (seqId == 0)
 		seqId = 2000;
 
-	for (l = 0; _comiSeqMusicTable[l].soundId != -1; l++) {
-		if ((_comiSeqMusicTable[l].soundId == seqId)) {
-			debug(5, "IMuseDigital::setComiMusicSequence(): Set music sequence: %s, %s", _comiSeqMusicTable[l].name, _comiSeqMusicTable[l].filename);
-			num = l;
+	for (num = 0; num < ARRAYSIZE(_grimSeqMusicTable); num++) {
+		if (_grimSeqMusicTable[num].soundId == seqId)
 			break;
-		}
 	}
 
-	if (num == -1)
+	if (num == ARRAYSIZE(_grimSeqMusicTable)) {
+		debug(5, "IMuseDigital::scriptSetSequence(): bogus sequence");
 		return;
+	}
+
+	debug(5, "IMuseDigital::scriptSetSequence(): Set music sequence: %s", _grimSeqMusicTable[num].internalName);
 
-	if (_curMusicSeq == num)
+	if (num == _curMusicSeq)
 		return;
 
-	if (num != 0) {
-		if (_curMusicSeq && ((_comiSeqMusicTable[_curMusicSeq].transitionType == 4)
-			|| (_comiSeqMusicTable[_curMusicSeq].transitionType == 6))) {
+	if (num) {
+		if (_curMusicSeq && (_grimSeqMusicTable[_curMusicSeq].transitionId == 4 || _grimSeqMusicTable[_curMusicSeq].transitionId == 6)) {
 			_nextSeqToPlay = num;
 			return;
-		} else {
-			playComiMusic(_comiSeqMusicTable[num].name, &_comiSeqMusicTable[num], 0, true);
-			_nextSeqToPlay = 0;
 		}
+
+		scriptPlayMusic(&_grimSeqMusicTable[num], 0, true);
+		_nextSeqToPlay = 0;
+		_attributes[GRIM_SEQ_OFFSET + num] = 1;
+		_curMusicSeq = num;
 	} else {
-		if (_nextSeqToPlay != 0) {
-			playComiMusic(_comiSeqMusicTable[_nextSeqToPlay].name, &_comiSeqMusicTable[_nextSeqToPlay], 0, true);
-			num = _nextSeqToPlay;
+		if (_nextSeqToPlay) {
+			scriptPlayMusic(&_grimSeqMusicTable[_nextSeqToPlay], 0, true);
+			_curMusicSeq = _nextSeqToPlay;
 			_nextSeqToPlay = 0;
-		} else {
-			if (_curMusicState != 0) {
-				playComiMusic(_comiStateMusicTable[_curMusicState].name, &_comiStateMusicTable[_curMusicState], _curMusicState, true);
-			} else {
-				playComiMusic(nullptr, &_comiStateMusicTable[0], _curMusicState, true);
-			}
-			num = 0;
+			_attributes[GRIM_SEQ_OFFSET + _curMusicSeq] = 1;
+			return;
+		}
+
+		scriptPlayMusic(_curMusicState ? &_grimStateMusicTable[_curMusicState] : nullptr, _curMusicState, true);
+		_curMusicSeq = 0;
+	}
+}
+
+void IMuseDigital::scriptSetCuePoint(int cueId) {
+}
+
+int IMuseDigital::scriptSetAttribute(int attrIndex, int attrVal) {
+	if (attrIndex == -1) {
+		if (attrVal == 0) {
+			diMUSEPause();
+		} else if (attrVal == 1) {
+			diMUSEResume();
+		} else if (attrVal == -1) {
+			memset(_attributes, 0, sizeof(_attributes));
+		}
+	} else if (attrIndex == 10000) {
+		char *dest = (char *)(intptr)attrVal;
+
+		for (int i = 0; i < ARRAYSIZE(_grimStateMusicTable); i++) {
+			memcpy(dest, _grimStateMusicTable[i].name, strlen(_grimStateMusicTable[i].name) + 1);
+			dest += strlen(_grimStateMusicTable[i].name) + 1;
 		}
+
+		for (int i = 0; i < ARRAYSIZE(_grimSeqMusicTable); i++) {
+			memcpy(dest, _grimSeqMusicTable[i].name, strlen(_grimSeqMusicTable[i].name) + 1);
+			dest += strlen(_grimSeqMusicTable[i].name) + 1;
+		}
+	} else if ((uint32)attrIndex >= ARRAYSIZE(_attributes)) {
+		debug(5, "IMuseDigital::scriptSetAttribute(): bogus attribute");
+	} else if (attrVal != -1) {
+		debug(5, "IMuseDigital::scriptSetAttribute(): Set attr %u to %u", attrIndex, attrVal);
+		_attributes[attrIndex] = attrVal;
 	}
 
-	_curMusicSeq = num;
+	return 0;
 }
 
-void IMuseDigital::playComiMusic(const char *songName, const imuseComiTable *table, int attribPos, bool sequence) {
+void IMuseDigital::scriptDeinit() {
+	diMUSEStopAllSounds();
+	_filesHandler->closeAllSounds();
+}
+
+int IMuseDigital::scriptTriggerCallback(char *marker) {
+	if (marker[0] != '_') {
+		debug(5, "IMuseDigital::scriptTriggerCallback(): got marker != '_end', callback ignored");
+		return -1;
+	}
+	_attributes[GRIM_STOP_SEQ_ATTR] = 1;
+	return 0;
+}
+
+void IMuseDigital::scriptPlayMusic(const IMuseDigiStateTable *tableEntry, int curSongEntryId, int isSequence) {
 	int hookId = 0;
-	int fadeDelay = 0;
+	int attribPos, oldSoundId, newSoundId, soundId;
+	int fadeTime, fadeDelay, fadeLength;
 
-	// This flag is not set in the original,
-	// but since we're not using DirectSound and this is pretty much timing related
-	// please see IMuseDigital::waveOutWrite() for more context...
 	Common::StackLock lock(*_mutex);
-	_waveOutXorTrigger = 1;
 
-	if ((songName != nullptr) && (attribPos != 0)) {
-		if (table->attribPos != 0)
-			attribPos = table->attribPos;
-		hookId = _attributes[COMI_STATE_OFFSET + attribPos];
+	if (tableEntry) {
+		attribPos = curSongEntryId;
+		if (curSongEntryId) {
+			if (tableEntry->attribPos)
+				attribPos = tableEntry->attribPos;
 
-		if (table->hookId != 0) {
-			if ((hookId != 0) && (table->hookId > 1)) {
-				_attributes[COMI_STATE_OFFSET + attribPos] = 2;
-			} else {
-				_attributes[COMI_STATE_OFFSET + attribPos] = hookId + 1;
-				if (table->hookId < hookId + 1)
-					_attributes[COMI_STATE_OFFSET + attribPos] = 1;
+			hookId = _attributes[GRIM_STATE_OFFSET + attribPos];
+
+			if (tableEntry->hookId) {
+				if (hookId || tableEntry->hookId <= 1) {
+					_attributes[GRIM_STATE_OFFSET + attribPos] = hookId + 1;
+					if (hookId + 1 > tableEntry->hookId)
+						_attributes[GRIM_STATE_OFFSET + attribPos] = 1;
+				} else {
+					_attributes[GRIM_STATE_OFFSET + attribPos] = 2;
+				}
 			}
 		}
 	}
 
-	int nextSoundId = 0;
-	while (1) {
-		nextSoundId = diMUSEGetNextSound(nextSoundId);
-		if (!nextSoundId)
-			break;
+	if (!hookId)
+		hookId = 100;
 
-		// If a sound is found (and its stream is active), fade it out if it's a music track
-		if (diMUSEGetParam(nextSoundId, DIMUSE_P_GROUP) == DIMUSE_GROUP_MUSICEFF && !diMUSEGetParam(nextSoundId, DIMUSE_P_SND_HAS_STREAM))
-			diMUSEFadeParam(nextSoundId, DIMUSE_P_VOLUME, 0, 120);
+	// Fade out any music track which is not streamed
+	for (soundId = diMUSEGetNextSound(0); soundId; soundId = diMUSEGetNextSound(soundId)) {
+		if (diMUSEGetParam(soundId, DIMUSE_P_GROUP) == DIMUSE_GROUP_MUSICEFF && !diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM))
+			diMUSEFadeParam(soundId, DIMUSE_P_VOLUME, 0, 120);
 	}
 
-	int oldSoundId = 0;
-	nextSoundId = 0;
-	while (1) {
-		nextSoundId = diMUSEGetNextSound(nextSoundId);
-		if (!nextSoundId)
-			break;
-
-		if (diMUSEGetParam(nextSoundId, DIMUSE_P_SND_HAS_STREAM) && (diMUSEGetParam(nextSoundId, DIMUSE_P_STREAM_BUFID) == DIMUSE_BUFFER_MUSIC)) {
-			oldSoundId = nextSoundId;
+	oldSoundId = 0;
+	for (soundId = diMUSEGetNextSound(0); soundId; soundId = diMUSEGetNextSound(soundId)) {
+		if (diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM) && diMUSEGetParam(soundId, DIMUSE_P_STREAM_BUFID) == DIMUSE_BUFFER_MUSIC) {
+			oldSoundId = soundId;
 			break;
 		}
 	}
 
-	if (!songName) {
+	if (!tableEntry) {
 		if (oldSoundId)
 			diMUSEFadeParam(oldSoundId, DIMUSE_P_VOLUME, 0, 120);
 		return;
 	}
 
-	switch (table->transitionType) {
-	case 0:
-		debug(5, "IMuseDigital::playComiMusic(): NULL transition, ignored");
-		break;
-	case 1:
-		if (_filesHandler->openSound(table->soundId))
-			return;
+	fadeTime = tableEntry->fadeTime;
+	if (!fadeTime)
+		fadeTime = 1000;
 
-		if (table->soundId) {
-			if (diMUSEStartSound(table->soundId, 126))
-				debug(5, "IMuseDigital::playComiMusic(): transition 1, failed to start the sound (%d)", table->soundId);
-			diMUSESetParam(table->soundId, DIMUSE_P_VOLUME, 1);
-			diMUSEFadeParam(table->soundId, DIMUSE_P_VOLUME, 127, 120);
-			_filesHandler->closeSound(table->soundId);
-			diMUSESetParam(table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-		} else {
-			debug(5, "IMuseDigital::playComiMusic(): transition 1, empty soundId, ignored");
-		}
+	fadeDelay = fadeTime;
+	fadeLength = (3 * fadeTime) / 50;
+
+	switch (tableEntry->transitionId) {
+	case 0:
+		debug(5, "IMuseDigital::scriptPlayMusic(): NULL transition, ignored");
 		break;
 	case 2:
 	case 3:
 	case 4:
+	case 10:
+	case 11:
 	case 12:
-		if (_filesHandler->openSound(table->soundId))
-			return;
+		// TODO
+		// newSoundId = diMUSEOpenSound(fileName, 0);
+		newSoundId = _filesHandler->openSound(tableEntry->soundId) ? 0 : tableEntry->soundId;
 
-		if (table->filename[0] == 0 || table->soundId == 0) {
+		if (!newSoundId) {
+			debug(5, "IMuseDigital::scriptPlayMusic(): unable to open sound %d", tableEntry->soundId);
 			if (oldSoundId)
 				diMUSEFadeParam(oldSoundId, DIMUSE_P_VOLUME, 0, 60);
-			break;
+			return;
 		}
 
-		if (table->transitionType == 4) {
-			_stopSequenceFlag = 0;
-			diMUSESetTrigger(table->soundId, MKTAG('_', 'e', 'n', 'd'), DIMUSE_C_SCRIPT_CALLBACK);
+		if (tableEntry->transitionId == 4) {
+			_attributes[GRIM_STOP_SEQ_ATTR] = 0;
+			diMUSESetTrigger(newSoundId, "_end", DIMUSE_C_SCRIPT_CALLBACK);
 		}
 
-		if (oldSoundId) {
-			fadeDelay = table->fadeOutDelay;
-			if (!fadeDelay)
-				fadeDelay = 1000;
-			else
-				fadeDelay = (fadeDelay * 100) / 6; // Set dimuse_table fade out time to millisecond scale
-
-			if (table->transitionType == 2) {
-				diMUSESwitchStream(oldSoundId, table->soundId, fadeDelay, 0, 0);
-				diMUSESetParam(table->soundId, DIMUSE_P_VOLUME, 127);
-				diMUSESetParam(table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-				diMUSESetHook(table->soundId, table->hookId);
-				diMUSEProcessStreams();
-			} else if (oldSoundId != table->soundId) {
-				if ((!sequence) && (table->attribPos != 0) &&
-					(table->attribPos == _comiStateMusicTable[_curMusicState].attribPos)) {
-
-					debug(5, "IMuseDigital::playComiMusic(): Starting new sound (%s) with same attribute as old sound (%s)",
-						table->name, _comiStateMusicTable[_curMusicState].name);
-
-					diMUSESwitchStream(oldSoundId, table->soundId, fadeDelay, 0, 1);
-					diMUSESetParam(table->soundId, DIMUSE_P_VOLUME, 127);
-					diMUSESetParam(table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-					diMUSEProcessStreams();
-				} else {
-					switch (table->transitionType) {
-					case 12:
-						diMUSESetHook(oldSoundId, table->hookId);
-						diMUSESetTrigger(oldSoundId, MKTAG('e', 'x', 'i', 't'), DIMUSE_C_SWITCH_STREAM, oldSoundId, table->soundId, fadeDelay, 1, 0);
-						diMUSESetTrigger(oldSoundId, MKTAG('e', 'x', 'i', 't'), DIMUSE_C_SET_PARAM, table->soundId, DIMUSE_P_VOLUME, 127);
-						diMUSESetTrigger(oldSoundId, MKTAG('e', 'x', 'i', 't'), DIMUSE_C_SET_PARAM, table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-						diMUSESetTrigger(oldSoundId, MKTAG('e', 'x', 'i', 't'), DIMUSE_C_SET_HOOK, table->soundId, hookId);
-						diMUSEProcessStreams();
-						break;
-					default:
-						diMUSESwitchStream(oldSoundId, table->soundId, fadeDelay, 0, 0);
-						diMUSESetParam(table->soundId, DIMUSE_P_VOLUME, 127);
-						diMUSESetParam(table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-						diMUSESetHook(table->soundId, hookId);
-						diMUSEProcessStreams();
-						break;
-					}
-				}
+		debug(5, "IMuseDigital::scriptPlayMusic(): HOOK=%d", hookId);
+
+		if (!oldSoundId) {
+			debug(5, "IMuseDigital::scriptPlayMusic(): no stream sound");
+			if (diMUSEStartStream(newSoundId, 126, DIMUSE_BUFFER_MUSIC))
+				debug(5, "IMuseDigital::scriptPlayMusic(): failed to start the stream for sound %d", newSoundId);
+
+			diMUSESetParam(newSoundId, DIMUSE_P_VOLUME, 0);
+			diMUSEFadeParam(newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			diMUSESetParam(newSoundId, DIMUSE_P_PAN, tableEntry->pan);
+			diMUSESetParam(newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+			diMUSESetHook(newSoundId, hookId);
+		} else if (tableEntry->transitionId == 2) {
+			diMUSESwitchStream(oldSoundId, newSoundId, fadeDelay, 0, 0);
+			debug(5, "IMuseDigital::scriptPlayMusic(): FADE=%d, vol=%d", fadeDelay, tableEntry->volume);
+			diMUSEFadeParam(newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			diMUSEFadeParam(newSoundId, DIMUSE_P_PAN, tableEntry->pan, fadeLength);
+			diMUSESetParam(newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+			diMUSESetHook(newSoundId, hookId);
+			diMUSEProcessStreams();
+		} else if (oldSoundId == newSoundId) {
+			diMUSEFadeParam(newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			debug(5, "IMuseDigital::scriptPlayMusic(): fading VOL=%d", tableEntry->volume);
+			if (tableEntry->pan) {
+				diMUSEFadeParam(newSoundId, DIMUSE_P_PAN, tableEntry->pan, fadeLength);
+				debug(5, "IMuseDigital::scriptPlayMusic(): and PAN=%d", tableEntry->pan);
+			}
+		} else if (!isSequence && tableEntry->attribPos && tableEntry->attribPos == _grimStateMusicTable[_curMusicState].attribPos) {
+			diMUSESwitchStream(oldSoundId, newSoundId, fadeDelay, 0, 1);
+			diMUSEFadeParam(newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			diMUSEFadeParam(newSoundId, DIMUSE_P_PAN, tableEntry->pan, fadeLength);
+			diMUSESetParam(newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+			if (hookId == 100)
+				diMUSESetHook(newSoundId, 100);
+			diMUSEProcessStreams();
+		} else if (tableEntry->transitionId == 10 || tableEntry->transitionId == 12) {
+			if (tableEntry->transitionId == 12) {
+				diMUSESetHook(oldSoundId, 99);
+				diMUSESetTrigger(oldSoundId, "clear", DIMUSE_C_SET_HOOK, oldSoundId, 128);
 			}
+
+			diMUSESetTrigger(oldSoundId, "exit", DIMUSE_C_SWITCH_STREAM, oldSoundId, newSoundId, fadeDelay, 1, 0);
+			diMUSESetTrigger(oldSoundId, "exit", DIMUSE_C_FADE_PARAM, newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			diMUSESetTrigger(oldSoundId, "exit", DIMUSE_C_FADE_PARAM, newSoundId, DIMUSE_P_PAN, tableEntry->pan, fadeLength);
+			diMUSESetTrigger(oldSoundId, "exit", DIMUSE_C_SET_PARAM, newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+			diMUSESetTrigger(oldSoundId, "exit", DIMUSE_C_SET_HOOK, newSoundId, hookId);
+			diMUSEProcessStreams();
+		} else if (tableEntry->transitionId == 11) {
+			diMUSESetTrigger(oldSoundId, "exit2", DIMUSE_C_SWITCH_STREAM, oldSoundId, newSoundId, fadeDelay, 1, 0);
+			diMUSESetTrigger(oldSoundId, "exit2", DIMUSE_C_FADE_PARAM, newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			diMUSESetTrigger(oldSoundId, "exit2", DIMUSE_C_FADE_PARAM, newSoundId, DIMUSE_P_PAN, tableEntry->pan, fadeLength);
+			diMUSESetTrigger(oldSoundId, "exit2", DIMUSE_C_SET_PARAM, newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+			diMUSESetTrigger(oldSoundId, "exit2", DIMUSE_C_SET_HOOK, newSoundId, hookId);
+			diMUSEProcessStreams();
 		} else {
-			if (diMUSEStartStream(table->soundId, 126, DIMUSE_BUFFER_MUSIC))
-				debug(5, "IMuseDigital::playComiMusic(): failed to start the stream for sound %d", table->soundId);
-			diMUSESetParam(table->soundId, DIMUSE_P_VOLUME, 127);
-			diMUSESetParam(table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-			diMUSESetHook(table->soundId, hookId);
+			diMUSESwitchStream(oldSoundId, newSoundId, fadeDelay, 0, 0);
+			debug(5, "IMuseDigital::scriptPlayMusic(): FADE=%d, vol=%d", fadeDelay, tableEntry->volume);
+			diMUSEFadeParam(newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			diMUSEFadeParam(newSoundId, DIMUSE_P_PAN, tableEntry->pan, fadeLength);
+			debug(5, "IMuseDigital::scriptPlayMusic(): set pan=%d", tableEntry->pan);
+			diMUSESetParam(newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+			diMUSESetHook(newSoundId, hookId);
+			diMUSEProcessStreams();
 		}
-		_filesHandler->closeSound(table->soundId);
-		diMUSESetParam(table->soundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
+
+		_filesHandler->closeSound(newSoundId);
+		diMUSESetParam(newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
 		break;
 	case 5:
-		debug(5, "IMuseDigital::playComiMusic(): no-op transition type (5), ignored");
 		break;
 	case 6:
-		_stopSequenceFlag = 0;
-		diMUSESetTrigger(DIMUSE_SMUSH_SOUNDID + DIMUSE_BUFFER_MUSIC, MKTAG('_', 'e', 'n', 'd'), DIMUSE_C_SCRIPT_CALLBACK);
+		_attributes[GRIM_STOP_SEQ_ATTR] = 0;
+		diMUSESetTrigger(DIMUSE_SMUSH_SOUNDID + DIMUSE_BUFFER_MUSIC, "_end", DIMUSE_C_SCRIPT_CALLBACK);
 		break;
 	case 7:
 		if (oldSoundId)
@@ -379,16 +395,17 @@ void IMuseDigital::playComiMusic(const char *songName, const imuseComiTable *tab
 		break;
 	case 8:
 		if (oldSoundId)
-			diMUSESetHook(oldSoundId, table->hookId);
+			diMUSESetHook(oldSoundId, 100);
 		break;
 	case 9:
 		if (oldSoundId)
-			diMUSESetHook(oldSoundId, table->hookId);
-		_stopSequenceFlag = 0;
-		diMUSESetTrigger(oldSoundId, MKTAG('_', 'e', 'n', 'd'), DIMUSE_C_SCRIPT_CALLBACK);
+			diMUSESetHook(oldSoundId, 99);
+
+		_attributes[GRIM_STOP_SEQ_ATTR] = 0;
+		diMUSESetTrigger(oldSoundId, "_end", DIMUSE_C_SCRIPT_CALLBACK);
 		break;
 	default:
-		debug(5, "IMuseDigital::playComiMusic(): bogus transition type, ignored");
+		debug(5, "IMuseDigital::scriptPlayMusic(): bogus transition type, ignored");
 		break;
 	}
 }
diff --git a/engines/grim/imuse/dimuse_tables.cpp b/engines/grim/imuse/dimuse_tables.cpp
index 14e990e67bd..21be3913401 100644
--- a/engines/grim/imuse/dimuse_tables.cpp
+++ b/engines/grim/imuse/dimuse_tables.cpp
@@ -23,194 +23,232 @@
 
 namespace Grim {
 
-const imuseComiTable _comiStateMusicTable[] = {
-	{0, 1000, "STATE_NULL",         0, 0,    0, ""            }, /* 00 */
-	{0, 1001, "stateNoChange",      0, 0,    0, ""            }, /* 01 */
-	{3, 1098, "stateCredits1",      0, 0,   60, "1098-C~1.IMX"}, /* 02 */
-	{3, 1099, "stateMenu",          0, 0,   60, "1099-M~1.IMX"}, /* 03 */
-	{3, 1100, "stateHold1",         4, 0,   60, "1100-H~1.IMX"}, /* 04 */
-	{3, 1101, "stateWaterline1",    4, 0,   60, "1101-W~1.IMX"}, /* 05 */
-	{3, 1102, "stateHold2",         6, 1,   60, "1102-H~1.IMX"}, /* 06 */
-	{3, 1103, "stateWaterline2",    6, 0,   60, "1103-W~1.IMX"}, /* 07 */
-	{3, 1104, "stateCannon",        0, 0,   60, "1104-C~1.IMX"}, /* 08 */
-	{3, 1105, "stateTreasure",      0, 0,   60, "1105-T~1.IMX"}, /* 09 */
-	{3, 1200, "stateFortBase",     10, 1,   60, "1200-F~1.IMX"}, /* 10 */
-	{3, 1201, "statePreFort",      10, 1,   60, "1201-P~1.IMX"}, /* 11 */
-	{3, 1202, "statePreVooOut",    12, 0,   60, "1202-P~1.IMX"}, /* 12 */
-	{3, 1203, "statePreVooIn",     12, 0,   60, "1203-P~1.IMX"}, /* 13 */
-	{3, 1204, "statePreVooLady",   12, 0,   60, "1204-P~1.IMX"}, /* 14 */
-	{3, 1205, "stateVoodooOut",     0, 0,   60, "1205-V~1.IMX"}, /* 15 */
-	{3, 1210, "stateVoodooIn",      0, 0,   60, "1210-V~1.IMX"}, /* 16 */
-	{12,1212, "stateVoodooInAlt",   0, 1,   42, "1210-V~1.IMX"}, /* 17 */
-	{3, 1215, "stateVoodooLady",    0, 0,   60, "1215-V~1.IMX"}, /* 18 */
-	{3, 1219, "statePrePlundermap", 0, 0,   60, "1219-P~1.IMX"}, /* 19 */
-	{3, 1220, "statePlundermap",    0, 0,   60, "1220-P~1.IMX"}, /* 20 */
-	{3, 1222, "statePreCabana",     0, 0,   60, "1222-P~1.IMX"}, /* 21 */
-	{3, 1223, "stateCabana",        0, 0,   60, "1223-C~1.IMX"}, /* 22 */
-	{3, 1224, "statePostCabana",   23, 0,   60, "1224-P~1.IMX"}, /* 23 */
-	{3, 1225, "stateBeachClub",    23, 0,   60, "1225-B~1.IMX"}, /* 24 */
-	{3, 1230, "stateCliff",         0, 0,   60, "1230-C~1.IMX"}, /* 25 */
-	{3, 1232, "stateBelly",         0, 0,   48, "1232-B~1.IMX"}, /* 26 */
-	{3, 1235, "stateQuicksand",     0, 0,   60, "1235-Q~1.IMX"}, /* 27 */
-	{3, 1240, "stateDangerBeach",   0, 0,   48, "1240-D~1.IMX"}, /* 28 */
-	{12,1241, "stateDangerBeachAlt",0, 2,   48, "1240-D~1.IMX"}, /* 29 */
-	{3, 1245, "stateRowBoat",       0, 0,   60, "1245-R~1.IMX"}, /* 30 */
-	{3, 1247, "stateAlongside",     0, 0,   48, "1247-A~1.IMX"}, /* 31 */
-	{12,1248, "stateAlongsideAlt",  0, 1,   48, "1247-A~1.IMX"}, /* 32 */
-	{3, 1250, "stateChimpBoat",     0, 0,   30, "1250-C~1.IMX"}, /* 33 */
-	{3, 1255, "stateMrFossey",      0, 0,   48, "1255-M~1.IMX"}, /* 34 */
-	{3, 1259, "statePreTown",       0, 0,   60, "1259-P~1.IMX"}, /* 35 */
-	{3, 1260, "stateTown",          0, 0,   60, "1260-T~1.IMX"}, /* 36 */
-	{3, 1264, "statePreMeadow",     0, 0,   60, "1264-P~1.IMX"}, /* 37 */
-	{3, 1265, "stateMeadow",        0, 0,   60, "1265-M~1.IMX"}, /* 38 */
-	{3, 1266, "stateMeadowAmb",     0, 0,   60, "1266-M~1.IMX"}, /* 39 */
-	{3, 1270, "stateWardrobePre",  40, 0,   60, "1270-W~1.IMX"}, /* 40 */
-	{3, 1272, "statePreShow",      40, 0,   60, "1272-P~1.IMX"}, /* 41 */
-	{3, 1274, "stateWardrobeShow", 42, 0,   60, "1274-W~1.IMX"}, /* 42 */
-	{3, 1276, "stateShow",         42, 0,   60, "1276-S~1.IMX"}, /* 43 */
-	{3, 1277, "stateWardrobeJug",  44, 0,   60, "1277-W~1.IMX"}, /* 44 */
-	{3, 1278, "stateJuggling",     44, 0,   60, "1278-J~1.IMX"}, /* 45 */
-	{3, 1279, "statePostShow",      0, 0,   60, "1279-P~1.IMX"}, /* 46 */
-	{3, 1280, "stateChickenShop",   0, 0,   60, "1280-C~1.IMX"}, /* 47 */
-	{3, 1285, "stateBarberShop",   48, 0,   60, "1285-B~1.IMX"}, /* 48 */
-	{3, 1286, "stateVanHelgen",    48, 0,   60, "1286-V~1.IMX"}, /* 49 */
-	{3, 1287, "stateBill",         48, 0,   60, "1287-B~1.IMX"}, /* 50 */
-	{3, 1288, "stateHaggis",       48, 0,   60, "1288-H~1.IMX"}, /* 51 */
-	{3, 1289, "stateRottingham",   48, 0,   60, "1289-R~1.IMX"}, /* 52 */
-	{3, 1305, "stateDeck",          0, 0,   60, "1305-D~1.IMX"}, /* 53 */
-	{3, 1310, "stateCombatMap",     0, 0,   60, "1310-C~1.IMX"}, /* 54 */
-	{3, 1320, "stateShipCombat",    0, 0,   60, "1320-S~1.IMX"}, /* 55 */
-	{3, 1325, "stateSwordfight",    0, 0,   60, "1325-S~1.IMX"}, /* 56 */
-	{3, 1327, "stateSwordRott",     0, 0,   60, "1327-S~1.IMX"}, /* 57 */
-	{3, 1330, "stateTownEdge",      0, 0,   60, "1330-T~1.IMX"}, /* 58 */
-	{3, 1335, "stateSwordLose",     0, 0,   60, "1335-S~1.IMX"}, /* 59 */
-	{3, 1340, "stateSwordWin",      0, 0,   60, "1340-S~1.IMX"}, /* 60 */
-	{3, 1345, "stateGetMap",        0, 0,   60, "1345-G~1.IMX"}, /* 61 */
-	{3, 1400, "stateWreckBeach",    0, 0,   60, "1400-W~1.IMX"}, /* 62 */
-	{3, 1405, "stateBloodMap",     63, 0,   60, "1405-B~1.IMX"}, /* 63 */
-	{3, 1410, "stateClearing",      0, 0,   60, "1410-C~1.IMX"}, /* 64 */
-	{3, 1415, "stateLighthouse",   63, 0,   60, "1415-L~1.IMX"}, /* 65 */
-	{3, 1420, "stateVillage",      66, 0,   60, "1420-V~1.IMX"}, /* 66 */
-	{3, 1423, "stateVolcano",      66, 0,   60, "1423-V~1.IMX"}, /* 67 */
-	{3, 1425, "stateAltar",        66, 0,   60, "1425-A~1.IMX"}, /* 68 */
-	{3, 1430, "stateHotelOut",      0, 0,   60, "1430-H~1.IMX"}, /* 69 */
-	{3, 1435, "stateHotelBar",     70, 0,   60, "1435-H~1.IMX"}, /* 70 */
-	{3, 1440, "stateHotelIn",      70, 0,   60, "1440-H~1.IMX"}, /* 71 */
-	{3, 1445, "stateTarotLady",    70, 0,   60, "1445-T~1.IMX"}, /* 72 */
-	{3, 1447, "stateGoodsoup",     70, 0,   60, "1447-G~1.IMX"}, /* 73 */
-	{3, 1448, "stateGuestRoom",     0, 0,   60, "1448-G~1.IMX"}, /* 74 */
-	{3, 1450, "stateWindmill",     63, 0,   60, "1450-W~1.IMX"}, /* 75 */
-	{3, 1455, "stateCemetary",      0, 0,   60, "1455-C~1.IMX"}, /* 76 */
-	{3, 1460, "stateCrypt",        77, 0,   60, "1460-C~1.IMX"}, /* 77 */
-	{3, 1463, "stateGraveDigger",  77, 0,   60, "1463-G~1.IMX"}, /* 78 */
-	{3, 1465, "stateMonkey1",       0, 0,   60, "1465-M~1.IMX"}, /* 79 */
-	{3, 1475, "stateStanDark",      0, 0,   60, "1475-S~1.IMX"}, /* 80 */
-	{3, 1477, "stateStanLight",     0, 0,   60, "1477-S~1.IMX"}, /* 81 */
-	{3, 1480, "stateEggBeach",     63, 0,   60, "1480-E~1.IMX"}, /* 82 */
-	{3, 1485, "stateSkullIsland",   0, 0,   60, "1485-S~1.IMX"}, /* 83 */
-	{3, 1490, "stateSmugglersCave", 0, 0,   60, "1490-S~1.IMX"}, /* 84 */
-	{3, 1500, "stateLeChuckTalk",   0, 0,   60, "1500-L~1.IMX"}, /* 85 */
-	{3, 1505, "stateCarnival",      0, 0,   60, "1505-C~1.IMX"}, /* 86 */
-	{3, 1511, "stateHang",         87, 0,   60, "1511-H~1.IMX"}, /* 87 */
-	{3, 1512, "stateRum",          87, 0,   60, "1512-RUM.IMX"}, /* 88 */
-	{3, 1513, "stateTorture",      87, 0,   60, "1513-T~1.IMX"}, /* 89 */
-	{3, 1514, "stateSnow",         87, 0,   60, "1514-S~1.IMX"}, /* 90 */
-	{3, 1515, "stateCredits",       0, 0,   60, "1515-C~1.IMX"}, /* 91 */
-	{3, 1520, "stateCarnAmb",       0, 0,   60, "1520-C~1.IMX"}, /* 92 */
-	{0,   -1, "",                   0, 0,    0, "",           }
+const IMuseDigiStateTable _grimStateMusicTable[181] = {
+	{"",                        0, 1000, "STATE_NULL",           0,  0,   0, 127, 0}, /* 000 */
+	{"",                        0, 1999, "stateNoChange",        0,  0,   0, 127, 0}, /* 001 */
+	{"1001 - Manny's Office",   3, 1001, "stateMO",              0,  0,   0, 127, 0}, /* 002 */
+	{"1002 - Mr. Frustration",  3, 1002, "stateHA_INTLS",        3,  8,   0,  20, 50}, /* 003 */
+	{"1002 - Mr. Frustration",  3, 1003, "stateHA_REVLS",        3,  8,   0,  80, 12}, /* 004 */
+	{"1002 - Mr. Frustration",  3, 1004, "stateHA_ELVOS",        3,  8,   0,  90, 110}, /* 005 */
+	{"1002 - Mr. Frustration",  3, 1005, "stateHA_MNYCU",        3,  8,   0,  60, 110}, /* 006 */
+	{"1002 - Mr. Frustration",  3, 1006, "stateHA_EVACU",        3,  8,   0,  80, 64}, /* 007 */
+	{"1002 - Mr. Frustration",  3, 1007, "stateHA_EVAWS",        3,  8,   0,  60, 60}, /* 008 */
+	{"1008 - Domino's Office",  3, 1008, "stateDO",              0,  0,   0, 127, 0}, /* 009 */
+	{"1009 - Copal's Office",   3, 1009, "stateCO",              0,  0,   0, 127, 0}, /* 010 */
+	{"1010 - Ledge",            3, 1010, "stateLE",              0,  0,   0, 127, 0}, /* 011 */
+	{"1011 - Roof",             3, 1011, "stateRF",              0,  0,   0, 127, 0}, /* 012 */
+	{"1020 - Tube Room",        3, 1020, "stateTU",              0,  0,   0, 127, 0}, /* 013 */
+	{"1021 - Brennis",          3, 1021, "stateTU_BRENNIS",      0,  0,   0, 127, 0}, /* 014 */
+	{"1022 - Lobby",            3, 1022, "stateLO",              0,  0,   0, 127, 0}, /* 015 */
+	{"1023 - Packing Room",     3, 1023, "statePK",              0,  0,   0, 127, 0}, /* 016 */
+	{"1030 - Garage",           3, 1030, "stateGA",              0,  0,   0, 127, 0}, /* 017 */
+	{"1031 - Glottis' Shop",    3, 1031, "stateGS",              0,  0,   0, 127, 0}, /* 018 */
+	{"1030 - Garage",           3, 1032, "stateGS_JAIL",         0,  0,   0, 127, 0}, /* 019 */
+	{"1040 - Festival Wet",     3, 1040, "stateAL",             21,  4, 500,  60, 0}, /* 020 */
+	{"1041 - Festival Dry",     3, 1041, "stateFE",             21,  4, 200, 127, 0}, /* 021 */
+	{"1041 - Festival Dry",     3, 1042, "stateST",             21,  4, 200,  60, 0}, /* 022 */
+	{"1041 - Festival Dry",     3, 1043, "stateOS",             21,  4, 200,  46, 0}, /* 023 */
+	{"1040 - Festival Wet",     3, 1044, "stateRP",             21,  4, 200,  85, 0}, /* 024 */
+	{"1050 - Headquarters",     3, 1050, "stateHQ",              0,  0,   0, 127, 0}, /* 025 */
+	{"1060 - Real World",       2, 1060, "stateLR",              0,  0, 300,  80, 0}, /* 026 */
+	{"1070 - Stump Room",       2, 1070, "stateSM",              0,  0,   0, 127, 0}, /* 027 */
+	{"1071 - Signpost Room",    2, 1071, "stateSG",              0,  3,   0, 127, 0}, /* 028 */
+	{"1072 - Navigation",       2, 1072, "stateNA",              0,  0,   0, 127, 0}, /* 029 */
+	{"1071 - Signpost Room",    2, 1073, "stateNA_SOLVED",       0,  3,   0, 127, 0}, /* 030 */
+	{"1074 - Bone Wagon",       2, 1074, "stateOO_BONE",         0,  0,   0, 127, 0}, /* 031 */
+	{"1075 - Spider's Eye",     2, 1075, "stateSP_ENTLA",        0,  0,   0, 127, 0}, /* 032 */
+	{"1076 - Spider Room",      2, 1076, "stateSP_WEBWS",        0,  0,   0, 127, 0}, /* 033 */
+	{"1077 - Tree Pump Amb",    2, 1077, "stateTR_PMPWS",        0,  0,   0, 127, 0}, /* 034 */
+	{"1078 - Tree Pump",        2, 1078, "stateTR_ESTHA",        0,  0,   0, 127, 0}, /* 035 */
+	{"1071 - Signpost Room",    2, 1079, "stateTR_SOLVED",       0,  3,   0, 127, 0}, /* 036 */
+	{"1080 - Beaver Room Lbby", 2, 1080, "stateLB",              0,  0,   0, 127, 0}, /* 037 */
+	{"1081 - Beaver Dam",       2, 1081, "stateBD",              0,  0,   0, 127, 0}, /* 038 */
+	{"1083 - Beaver Room",      2, 1082, "stateBD_SOLVED",       0,  0,   0, 127, 0}, /* 039 */
+	{"1083 - Beaver Room",      2, 1083, "stateBV",              0,  0,   0, 127, 0}, /* 040 */
+	{"1084 - Foggy Cactus",     2, 1084, "stateFC",              0,  0,   0,  80, 0}, /* 041 */
+	{"1085 - Rubamat Exterior", 2, 1085, "stateRE",              0,  0,   0, 105, 0}, /* 042 */
+	{"1087 - Blue Hector",      2, 1086, "stateRI",              0,  4,   0,  80, 30}, /* 043 */
+	{"1109 - Cafe Exterior",    2, 1100, "stateCB",              0,  0,   0, 127, 0}, /* 044 */
+	{"1101 - Cafe Office",      3, 1101, "stateCF",             45,  5, 400,  60, 0}, /* 045 */
+	{"1102 - Cafe Intercom",    3, 1102, "stateCF_INTRCM",      45,  0, 400, 127, 0}, /* 046 */
+	{"1103 - Coat Check",       3, 1103, "stateCC",             49,  4, 400,  60, 100}, /* 047 */
+	{"1104 - Lupe",             2, 1104, "stateCC_LUPE",         0,  0, 300, 127, 0}, /* 048 */
+	{"1106 - Glottis Noodle",   3, 1105, "stateCI",             49,  4, 400, 127, 75}, /* 049 */
+	{"1106 - Glottis Noodle",   3, 1106, "stateCI_NOODLE",      49,  4, 400, 127, 75}, /* 050 */
+	{"1106 - Glottis Noodle",   3, 1190, "stateCI_WIDHA",       49,  4, 400,  80, 45}, /* 051 */
+	{"1106 - Glottis Noodle",   3, 1191, "stateCI_BARWS",       49,  4, 400, 127, 127}, /* 052 */
+	{"1101 - Cafe Office",      3, 1107, "stateCI_EMPTY",       45,  5, 400, 127, 0}, /* 053 */
+	{"1108 - Casino Interior",  3, 1108, "stateCN",             45,  6, 400, 127, 0}, /* 054 */
+	{"1109 - Cafe Exterior",    2, 1109, "stateCE",              0,  0, 400, 127, 0}, /* 055 */
+	{"1110 - Cafe Ledge",       2, 1110, "stateCL",              0,  0, 400, 105, 0}, /* 056 */
+	{"1108 - Casino Interior",  3, 1111, "stateCN_QUIET",        0,  0, 400,  60, 0}, /* 057 */
+	{"1112 - Rusty Sans Vox",   2, 1112, "stateCI_SONG",         0,  0, 400, 127, 68}, /* 058 */
+	{"1120 - Elevator Station", 2, 1120, "stateEV",              0,  0,   0, 127, 0}, /* 059 */
+	{"1122 - Blue Exterior",    3, 1121, "stateBW",              0,  0, 400, 127, 0}, /* 060 */
+	{"1122 - Blue Exterior",    3, 1122, "stateBE",              0,  0, 400, 127, 0}, /* 061 */
+	{"1123 - Blue Casket Ins",  2, 1123, "stateBI",              0,  4, 700, 127, 0}, /* 062 */
+	{"1124 - Blue Casket Amb",  2, 1124, "stateBI_POE",          0,  0,   0, 127, 0}, /* 063 */
+	{"1125 - Smooth Hector",    2, 1125, "stateBK",              0,  4,   0,  80, 75}, /* 064 */
+	{"1122 - Blue Exterior",    3, 1126, "stateHB",              0,  0, 400, 127, 0}, /* 065 */
+	{"1127 - Limbo Dock",       3, 1127, "stateLM",             66,  0,   0, 127, 0}, /* 066 */
+	{"1128 - Limbo Talk",       2, 1128, "stateLM_TALK",         0,  0, 400, 127, 0}, /* 067 */
+	{"1129 - Limbo Poem",       3, 1129, "stateLM_POEM",        66,  0,   0, 127, 0}, /* 068 */
+	{"1130 - Dry Dock",         2, 1130, "stateDD",              0,  0, 400, 127, 0}, /* 069 */
+	{"1131 - Dry Dock Strike",  2, 1131, "stateDD_STRIKE",       0,  0, 400, 127, 0}, /* 070 */
+	{"1132 - Lighthouse Ext",   2, 1132, "stateLX",              0,  0,   0, 127, 0}, /* 071 */
+	{"1133 - Lola's Last",      2, 1133, "stateLX_LOLA",         0,  0,   0, 127, 0}, /* 072 */
+	{"1140 - Police Station",   3, 1140, "statePC",              0,  0,   0, 127, 0}, /* 073 */
+	{"1141 - Police Interior",  2, 1141, "statePI",              0,  0,   0, 105, 0}, /* 074 */
+	{"1141 - Police Interior",  2, 1142, "statePI_MALLOY",       0,  0,   0, 105, 0}, /* 075 */
+	{"1143 - Morgue",           2, 1143, "stateMG",              0,  0,   0, 105, 0}, /* 076 */
+	{"1140 - Police Station",   3, 1144, "stateBP",              0,  0,   0, 105, 0}, /* 077 */
+	{"1145 - Bridge Blimp",     2, 1145, "stateBB",              0,  0,   0, 127, 0}, /* 078 */
+	{"1146 - LOL Security Ext", 2, 1146, "stateGT",              0,  0,   0,  80, 0}, /* 079 */
+	{"1147 - LOL Security Int", 2, 1147, "stateSL",              0,  0,   0, 127, 0}, /* 080 */
+	{"1148 - Carla's Life",     2, 1148, "stateSL_TALK",         0,  0,   0, 127, 0}, /* 081 */
+	{"1149 - Bomb",             2, 1149, "stateSL_BOMB",         0,  0, 400, 127, 0}, /* 082 */
+	{"1152 - Track Stairs",     3, 1150, "stateTB",             83,  0,   0, 105, 0}, /* 083 */
+	{"1152 - Track Stairs",     3, 1151, "stateTW",             83,  0,   0, 105, 0}, /* 084 */
+	{"1152 - Track Stairs",     3, 1152, "stateTS",             83,  0,   0, 105, 0}, /* 085 */
+	{"1153 - Track Base",       2, 1153, "stateTX",              0,  0, 400, 127, 0}, /* 086 */
+	{"1154 - Kitty Hall",       2, 1154, "stateKH",              0,  0,   0, 127, 0}, /* 087 */
+	{"1155 - Sanspoof",         2, 1155, "stateKH_SANS",         0,  0,   0, 127, 0}, /* 088 */
+	{"1156 - Kitty Stables",    2, 1156, "stateKS",              0,  0,   0, 127, 0}, /* 089 */
+	{"1160 - High Roller Hall", 2, 1160, "stateHH",              0,  0,   0, 127, 0}, /* 090 */
+	{"1161 - High Roller Lnge", 3, 1161, "stateHL",              0,  0, 400, 127, 0}, /* 091 */
+	{"1162 - Glottis Gambling", 2, 1162, "stateHL_GLOT",         0,  0,   0, 127, 0}, /* 092 */
+	{"1163 - Max's Office",     3, 1163, "stateMX",              0,  0, 400, 127, 0}, /* 093 */
+	{"1125 - Hector Steps Out", 3, 1164, "stateHK",             94,  4, 200, 127, 80}, /* 094 */
+	{"1125 - Hector Steps Out", 3, 1165, "stateHP",             94,  4, 200,  20, 64}, /* 095 */
+	{"1125 - Hector Steps Out", 3, 1166, "stateHE",             94,  4, 200, 127, 10}, /* 096 */
+	{"1167 - Dillopede Elev",   3, 1167, "stateDE",              0,  0,   0, 127, 0}, /* 097 */
+	{"1167 - Dillopede Elev",   3, 1168, "stateDH",              0,  0,   0, 127, 0}, /* 098 */
+	{"1167 - Dillopede Elev",   3, 1169, "stateWC",              0,  0,   0, 127, 0}, /* 099 */
+	{"1170 - Extendo Bridge",   3, 1170, "stateXB",              0,  0, 400, 105, 0}, /* 100 */
+	{"1170 - Extendo Bridge",   3, 1171, "stateSD",              0,  0, 400, 105, 0}, /* 101 */
+	{"1170 - Extendo Bridge",   3, 1172, "stateSE",              0,  0, 400, 105, 0}, /* 102 */
+	{"1173 - Scrimshaw Int",    2, 1173, "stateSI",              0,  0, 400, 127, 0}, /* 103 */
+	{"1174 - Scrim Sleep",      2, 1174, "stateSI_SLEEP",        0,  0, 400, 127, 0}, /* 104 */
+	{"1180 - Note to Manny",    2, 1180, "stateNT",              0,  0,   0,  72, 0}, /* 105 */
+	{"1155 - Sanspoof",         2, 1181, "statePF",              0,  0,   0, 127, 0}, /* 106 */
+	{"1201 - Lola Zapata",      2, 1201, "stateLZ",              0,  0,   0, 127, 0}, /* 107 */
+	{"1202 - Inside The Lola",  2, 1202, "stateIL",              0,  0,   0, 127, 0}, /* 108 */
+	{"1203 - Engine Room",      2, 1203, "stateEI",              0,  0,   0, 127, 0}, /* 109 */
+	{"1204 - Porthole",         2, 1204, "stateDP",              0,  0,   0, 127, 0}, /* 110 */
+	{"1204 - Porthole",         2, 1205, "stateOP",              0,  0,   0, 127, 0}, /* 111 */
+	{"1210 - Sunken Lola",      2, 1210, "stateSU",              0,  0,   0, 127, 0}, /* 112 */
+	{"1211 - Pearl Crater Sub", 2, 1211, "statePS",              0,  0,   0, 127, 0}, /* 113 */
+	{"1220 - Miner's Room",     3, 1220, "stateMN",              0,  0,   0, 127, 0}, /* 114 */
+	{"1220 - Miner's Room",     3, 1221, "stateMN_CHEPITO",      0,  0,   0, 127, 0}, /* 115 */
+	{"1222 - Exterior Airlock", 2, 1222, "stateEA",              0,  0,   0, 127, 0}, /* 116 */
+	{"1223 - Factory Hub",      2, 1223, "stateFH",              0,  4,   0, 127, 0}, /* 117 */
+	{"1224 - Foreman's Office", 2, 1224, "stateFO",              0,  0,   0, 127, 0}, /* 118 */
+	{"1230 - Vault Door",       2, 1230, "stateVD",              0,  0,   0, 127, 0}, /* 119 */
+	{"1231 - Outer Vault",      2, 1231, "stateVO",              0,  0,   0, 127, 0}, /* 120 */
+	{"1232 - Inner Vault",      2, 1232, "stateVI",              0,  0,   0, 127, 0}, /* 121 */
+	{"1233 - Ashtray Room",     2, 1233, "stateAR",              0,  0,   0, 127, 0}, /* 122 */
+	{"1234 - Ashtray Scary",    2, 1234, "stateAR_SCARY",        0,  0,   0, 127, 0}, /* 123 */
+	{"1235 - Ashtray Pensive",  2, 1235, "stateAR_PENSV",        0,  0,   0, 127, 0}, /* 124 */
+	{"1236 - Domino's Room",    2, 1236, "stateDR",              0,  0,   0, 127, 0}, /* 125 */
+	{"1240 - Conveyor Under",   3, 1240, "stateCY",              0,  4,   0, 127, 0}, /* 126 */
+	{"1240 - Conveyor Under",   3, 1241, "stateCW",              0,  0,   0, 127, 0}, /* 127 */
+	{"1241 - Crane Intro",      2, 1242, "stateCV",              0,  0,   0, 127, 0}, /* 128 */
+	{"1243 - Anchor Room",      3, 1243, "stateAC",              0,  0,   0, 127, 0}, /* 129 */
+	{"1244 - Glottis Hanging",  2, 1244, "stateGH",              0,  0,   0, 127, 0}, /* 130 */
+	{"1245 - End of the World", 2, 1245, "stateEW",              0,  0,   0, 127, 0}, /* 131 */
+	{"1246 - End World Later",  2, 1246, "stateEW_LATER",        0,  0,   0, 127, 0}, /* 132 */
+	{"1241 - Crane Intro",      2, 1247, "stateCU",              0,  0,   0, 127, 0}, /* 133 */
+	{"1250 - Upper Beach",      3, 1250, "stateBU",              0,  0,   0, 127, 0}, /* 134 */
+	{"1250 - Upper Beach",      3, 1251, "stateBL",              0,  0,   0, 127, 0}, /* 135 */
+	{"1252 - Lower Beach Boat", 3, 1252, "stateBL_BOAT",         0,  0,   0, 127, 0}, /* 136 */
+	{"1253 - Lamancha Sub",     2, 1253, "stateLU",              0,  0,   0, 127, 0}, /* 137 */
+	{"1254 - Crane Later",      2, 1254, "stateCUV_LATER",       0,  0,   0, 127, 0}, /* 138 */
+	{"1301 - Temple Gate",      3, 1301, "stateTG",              0,  0,   0, 127, 0}, /* 139 */
+	{"1301 - Temple Gate",      3, 1302, "stateBS",              0,  0,   0, 127, 0}, /* 140 */
+	{"1303 - Truck Depot",      2, 1303, "stateTD",              0,  0,   0, 105, 0}, /* 141 */
+	{"1306 - Mayan Train Pad",  3, 1306, "stateMT_CHEPITO",    143,  0,   0, 127, 0}, /* 142 */
+	{"1304 - Mayan Train Sta",  3, 1304, "stateMT",            143,  0,   0, 127, 0}, /* 143 */
+	{"1305 - Mayan Workshop",   2, 1305, "stateMY",              0,  0,   0, 127, 0}, /* 144 */
+	{"1307 - Mechanic's Kitch", 2, 1307, "stateMK",              0,  4,   0,  40, 64}, /* 145 */
+	{"1310 - Jello Bomb",       3, 1310, "stateJB",              0,  0,   0, 127, 0}, /* 146 */
+	{"1310 - Jello Bomb",       3, 1311, "stateXB_YEAR4",        0,  0,   0, 127, 0}, /* 147 */
+	{"1125 - Smooth Hector",    3, 1312, "stateBI_CLBYR4",     150,  4, 200,  20, 64}, /* 148 */
+	{"1125 - Smooth Hector",    3, 1313, "stateBI_KITYR4",     150,  4, 200,  50, 32}, /* 149 */
+	{"1125 - Smooth Hector",    3, 1314, "stateBK_YR4",        150,  4, 200, 105, 75}, /* 150 */
+	{"1122 - Blue Exterior",    3, 1315, "stateHB_YR4",          0,  0,   0, 127, 0}, /* 151 */
+	{"1122 - Blue Exterior",    3, 1316, "stateBW_YR4",          0,  0,   0, 127, 0}, /* 152 */
+	{"1122 - Blue Exterior",    3, 1317, "stateBE_YR4",          0,  0,   0, 127, 0}, /* 153 */
+	{"1332 - Hector's Foyer",   3, 1318, "stateHN",              0,  0,   0, 127, 0}, /* 154 */
+	{"1319 - Florist Video",    2, 1319, "stateFVID",            0,  0,   0, 127, 0}, /* 155 */
+	{"1320 - New LSA HQ",       2, 1320, "stateNQ",              0,  0,   0, 127, 0}, /* 156 */
+	{"1321 - LSA Sewer",        3, 1321, "stateLW",              0,  0,   0, 127, 0}, /* 157 */
+	{"1321 - LSA Sewer",        3, 1322, "stateSH",              0,  0,   0, 127, 0}, /* 158 */
+	{"1323 - Sewer Maze",       3, 1323, "stateZW",              0,  2,   0, 127, 0}, /* 159 */
+	{"1324 - Albinozod",        3, 1324, "stateAT",              0,  0,   0, 127, 0}, /* 160 */
+	{"1334 - Albino Trap",      3, 1334, "stateAT_TRAP",         0,  0,   0, 127, 0}, /* 161 */
+	{"1325 - Florist Shop",     3, 1325, "stateFP",            162,  0,   0, 127, 0}, /* 162 */
+	{"1326 - Florist Shop Int", 3, 1326, "stateFI",            162,  0,   0, 127, 0}, /* 163 */
+	{"1327 - Florist OK",       2, 1327, "stateFI_OK",           0,  0,   0, 127, 0}, /* 164 */
+	{"1323 - Sewer Maze",       3, 1328, "stateTE",              0,  2,   0, 127, 0}, /* 165 */
+	{"1329 - Theater Backstag", 2, 1329, "stateTH",              0,  4,   0, 127, 0}, /* 166 */
+	{"1330 - Lemans Lobby",     2, 1330, "stateLY",              0,  0,   0, 127, 0}, /* 167 */
+	{"1330 - Lemans Lobby",     2, 1331, "stateLY_CHOW",         0,  0,   0,  60, 0}, /* 168 */
+	{"1333 - Brennis Talk",     2, 1333, "stateLY_BREN",         0,  0,   0, 127, 0}, /* 169 */
+	{"1332 - Hector's Foyer",   3, 1332, "stateHF",              0,  0,   0, 127, 0}, /* 170 */
+	{"1342 - Neon Ledge",       2, 1340, "stateNL",              0,  0,   0, 127, 0}, /* 171 */
+	{"1350 - Meadow Flowers",   2, 1350, "stateMF",              0,  0,   0, 127, 0}, /* 172 */
+	{"1351 - Meadow",           2, 1351, "stateME",              0,  0,   0, 127, 0}, /* 173 */
+	{"1352 - Car Head",         2, 1352, "stateHI",              0,  0,   0, 127, 0}, /* 174 */
+	{"1353 - Greenhouse Appr",  2, 1353, "stateGE",              0,  0,   0, 127, 0}, /* 175 */
+	{"1355 - Shootout",         2, 1355, "stateSHOOT",           0,  0,   0, 127, 0}, /* 176 */
+	{"1354 - Game Ending",      2, 1354, "stateEND",             0,  0,   0, 127, 0}, /* 177 */
+	{"1400 - Start Credits",    2, 1400, "stateOPEN_CRED",       0,  0,   0, 127, 0}, /* 178 */
+	{"1401 - Smooth Hector",    2, 1401, "stateEND_CRED",        0,  0,  20, 105, 0}, /* 179 */
+	{"",                        0, 1500, "stateMenu",            0,  0,   0, 127, 0}, /* 180 */
 };
 
-const imuseComiTable _comiSeqMusicTable[] = {
-	{0, 2000, "SEQ_NULL",        0, 0,    0, ""            },
-	{0, 2100, "seqINTRO",        0, 0,    0, ""            },
-	{3, 2105, "seqInterlude1",   0, 0,   60, "2105-I~1.IMX"},
-	{8, 2110, "seqLastBoat",     0, 1,    0, ""            },
-	{0, 2115, "seqSINK_SHIP",    0, 0,    0, ""            },
-	{0, 2120, "seqCURSED_RING",  0, 0,   60, ""            },
-	{3, 2200, "seqInterlude2",   0, 0,   60, "2200-I~1.IMX"},
-	{3, 2210, "seqKidnapped",    0, 0,   60, "2210-K~1.IMX"},
-	{8, 2220, "seqSnakeVomits",  0, 1,    0, ""            },
-	{8, 2222, "seqPopBalloon",   0, 1,    0, ""            },
-	{3, 2225, "seqDropBalls",    0, 0,   60, "2225-D~1.IMX"},
-	{4, 2232, "seqArriveBarber", 0, 0,   60, "2232-A~1.IMX"},
-	{3, 2233, "seqAtonal",       0, 0,   60, "2233-A~1.IMX"},
-	{3, 2235, "seqShaveHead1",   0, 0,   60, "2235-S~1.IMX"},
-	{2, 2236, "seqShaveHead2",   0, 2,   60, "2235-S~1.IMX"},
-	{3, 2245, "seqCaberLose",    0, 0,   60, "2245-C~1.IMX"},
-	{3, 2250, "seqCaberWin",     0, 0,   60, "2250-C~1.IMX"},
-	{3, 2255, "seqDuel1",        0, 0,   60, "2255-D~1.IMX"},
-	{2, 2256, "seqDuel2",        0, 2,   60, "2255-D~1.IMX"},
-	{2, 2257, "seqDuel3",        0, 3,   60, "2255-D~1.IMX"},
-	{3, 2260, "seqBlowUpTree1",  0, 0,   60, "2260-B~1.IMX"},
-	{2, 2261, "seqBlowUpTree2",  0, 2,   60, "2260-B~1.IMX"},
-	{3, 2275, "seqMonkeys",      0, 0,   60, "2275-M~1.IMX"},
-	{9, 2277, "seqAttack",       0, 1,    0, ""            },
-	{3, 2285, "seqSharks",       0, 0,   60, "2285-S~1.IMX"},
-	{3, 2287, "seqTowelWalk",    0, 0,   60, "2287-T~1.IMX"},
-	{0, 2293, "seqNICE_BOOTS",   0, 0,    0, ""            },
-	{0, 2295, "seqBIG_BONED",    0, 0,    0, ""            },
-	{3, 2300, "seqToBlood",      0, 0,   60, "2300-T~1.IMX"},
-	{3, 2301, "seqInterlude3",   0, 0,   60, "2301-I~1.IMX"},
-	{3, 2302, "seqRott1",        0, 0,   60, "2302-R~1.IMX"},
-	{2, 2304, "seqRott2",        0, 2,   60, "2302-R~1.IMX"},
-	{2, 2305, "seqRott2b",       0,21,   60, "2302-R~1.IMX"},
-	{2, 2306, "seqRott3",        0, 3,   60, "2302-R~1.IMX"},
-	{2, 2308, "seqRott4",        0, 4,   60, "2302-R~1.IMX"},
-	{2, 2309, "seqRott5",        0, 5,   60, "2302-R~1.IMX"},
-	{3, 2311, "seqVerse1",       0, 0,   60, "2311-S~1.IMX"},
-	{2, 2312, "seqVerse2",       0, 2,   60, "2311-S~1.IMX"},
-	{2, 2313, "seqVerse3",       0, 3,   60, "2311-S~1.IMX"},
-	{2, 2314, "seqVerse4",       0, 4,   60, "2311-S~1.IMX"},
-	{2, 2315, "seqVerse5",       0, 5,   60, "2311-S~1.IMX"},
-	{2, 2316, "seqVerse6",       0, 6,   60, "2311-S~1.IMX"},
-	{2, 2317, "seqVerse7",       0, 7,   60, "2311-S~1.IMX"},
-	{2, 2318, "seqVerse8",       0, 8,   60, "2311-S~1.IMX"},
-	{2, 2319, "seqSongEnd",      0, 9,   60, "2311-S~1.IMX"},
-	{2, 2336, "seqRiposteLose",  0, 0,   60, "2336-R~1.IMX"},
-	{2, 2337, "seqRiposteWin",   0, 0,   60, "2337-R~1.IMX"},
-	{2, 2338, "seqInsultLose",   0, 0,   60, "2338-I~1.IMX"},
-	{2, 2339, "seqInsultWin",    0, 0,   60, "2339-I~1.IMX"},
-	{3, 2340, "seqSwordLose",    0, 0,   60, "1335-S~1.IMX"},
-	{3, 2345, "seqSwordWin",     0, 0,   60, "1340-S~1.IMX"},
-	{3, 2347, "seqGetMap",       0, 0,   60, "1345-G~1.IMX"},
-	{3, 2400, "seqInterlude4",   0, 0,   60, "2400-I~1.IMX"},
-	{0, 2405, "seqSHIPWRECK",    0, 0,    0, ""            },
-	{3, 2408, "seqFakeCredits",  0, 0,   60, "2408-F~1.IMX"},
-	{3, 2410, "seqPassOut",      0, 0,   60, "2410-P~1.IMX"},
-	{3, 2414, "seqGhostTalk",    0, 0,   60, "2414-G~1.IMX"},
-	{2, 2415, "seqGhostWedding", 0, 1,   60, "2414-G~1.IMX"},
-	{3, 2420, "seqEruption",     0, 0,   60, "2420-E~1.IMX"},
-	{3, 2425, "seqSacrifice",    0, 0,   60, "2425-S~1.IMX"},
-	{2, 2426, "seqSacrificeEnd", 0, 1,   60, "2425-S~1.IMX"},
-	{3, 2430, "seqScareDigger",  0, 0,   60, "2430-S~1.IMX"},
-	{3, 2445, "seqSkullArrive",  0, 0,   60, "2445-S~1.IMX"},
-	{3, 2450, "seqFloat",        0, 0,   60, "2450-C~1.IMX"},
-	{2, 2451, "seqFall",         0, 1,   60, "2450-C~1.IMX"},
-	{2, 2452, "seqUmbrella",     0, 2,   60, "2450-C~1.IMX"},
-	{3, 2460, "seqFight",        0, 0,   60, "2460-F~1.IMX"},
-	{0, 2465, "seqLAVE_RIDE",    0, 0,    0, ""            },
-	{0, 2470, "seqMORE_SLAW",    0, 0,    0, ""            },
-	{0, 2475, "seqLIFT_CURSE",   0, 0,    0, ""            },
-	{3, 2500, "seqInterlude5",   0, 0,   60, "2500-I~1.IMX"},
-	{3, 2502, "seqExitSkycar",   0, 0,   60, "2502-E~1.IMX"},
-	{3, 2504, "seqGrow1",        0, 0,   60, "2504-G~1.IMX"},
-	{2, 2505, "seqGrow2",        0, 1,   60, "2504-G~1.IMX"},
-	{3, 2508, "seqInterlude6",   0, 0,   60, "2508-I~1.IMX"},
-	{0, 2515, "seqFINALE",       0, 0,    0, ""            },
-	{3, 2520, "seqOut",          0, 0,   60, "2520-OUT.IMX"},
-	{3, 2530, "seqZap1a",        0, 0,   60, "2530-Z~1.IMX"},
-	{2, 2531, "seqZap1b",        0, 1,   60, "2530-Z~1.IMX"},
-	{2, 2532, "seqZap1c",        0, 2,   60, "2530-Z~1.IMX"},
-	{2, 2540, "seqZap2a",        0, 0,   60, "2540-Z~1.IMX"},
-	{2, 2541, "seqZap2b",        0, 1,   60, "2540-Z~1.IMX"},
-	{2, 2542, "seqZap2c",        0, 2,   60, "2540-Z~1.IMX"},
-	{3, 2550, "seqZap3a",        0, 0,   60, "2550-Z~1.IMX"},
-	{2, 2551, "seqZap3b",        0, 1,   60, "2550-Z~1.IMX"},
-	{2, 2552, "seqZap3c",        0, 2,   60, "2550-Z~1.IMX"},
-	{3, 2560, "seqZap4a",        0, 0,   60, "2560-Z~1.IMX"},
-	{2, 2561, "seqZap4b",        0, 1,   60, "2560-Z~1.IMX"},
-	{2, 2562, "seqZap4c",        0, 2,   60, "2560-Z~1.IMX"},
-	{0,   -1, "",                0, 0,    0, ""            }
+const IMuseDigiStateTable _grimSeqMusicTable[41] = {
+	{"",                        0, 2000, "SEQ_NULL",             0,  0, 300, 127, 0}, /* 000 */
+	{"2001 - Climb Rope",       2, 2001, "seqClimbRope",         0,  0, 300, 127, 0}, /* 001 */
+	{"2010 - Glottis OK",       2, 2010, "seqGlottisOK",         0,  0, 300, 127, 0}, /* 002 */
+	{"2020 - Reap Bruno",       2, 2020, "seqReapBruno",         0,  0, 300, 127, 0}, /* 003 */
+	{"2030 - Ledgepeckers",     2, 2030, "seqLedgepeckers",      0,  0, 300, 127, 0}, /* 004 */
+	{"2050 - Glottis Heart",    2, 2050, "seqGlottisHeart",      0,  0, 300, 105, 0}, /* 005 */
+	{"2055 - Slingshot Bone",   2, 2055, "seqSlingshotBone",     0,  0, 300, 127, 0}, /* 006 */
+	{"2060 - Glott Tree Fall",  2, 2060, "seqGlottTreeFall",     0,  0, 300, 127, 0}, /* 007 */
+	{"2070 - Beaver Fly",       2, 2070, "seqBeaverFly",         0,  0, 300, 127, 0}, /* 008 */
+	{"2071 - Beaver Sink",      2, 2071, "seqBeaverSink",        0,  0, 300, 127, 0}, /* 009 */
+	{"2080 - Meet Velasco",     2, 2080, "seqMeetVelasco",       0,  0, 300, 127, 0}, /* 010 */
+	{"2140 - Ooo Bonewagon",    2, 2140, "seqGlottSingBone",     0,  0, 300, 127, 75}, /* 011 */
+	{"2141 - Ooo Meche",        2, 2141, "seqMannySingMeche",    0,  0, 300, 127, 75}, /* 012 */
+	{"2155 - Find Detector",    2, 2155, "seqFindDetector",      0,  0, 300, 127, 0}, /* 013 */
+	{"2156 - Glott Drink Wine", 2, 2156, "seqGlottDrinkWine",    0,  0, 300, 127, 0}, /* 014 */
+	{"2157 - Glott No Wine",    2, 2157, "seqGlottNoWine",       0,  0, 300, 127, 0}, /* 015 */
+	{"2161 - Raoul Appears",    2, 2161, "seqRaoulAppears",      0,  0, 300, 127, 0}, /* 016 */
+	{"2162 - Raoul KO",         2, 2162, "seqRaoulKO",           0,  0, 300, 127, 0}, /* 017 */
+	{"2163 - Raoul Dissed",     2, 2163, "seqRaoulDissed",       0,  0, 300, 127, 0}, /* 018 */
+	{"2165 - Fake Tix",         2, 2165, "seqFakeTix",           0,  0, 300, 127, 0}, /* 019 */
+	{"2180 - Befriend Commies", 2, 2180, "seqBefriendCommies",   0,  0, 300, 127, 0}, /* 020 */
+	{"2186 - Nick Punchout",    2, 2186, "seqNickPunchout",      0,  0, 300, 127, 0}, /* 021 */
+	{"2200 - Yr 3 Iris",        2, 2200, "seqYr3Iris",           0,  0, 300, 127, 0}, /* 022 */
+	{"2210 - Hit Men",          2, 2210, "seqHitMen",            0,  0, 700, 127, 0}, /* 023 */
+	{"2230 - Open Vault",       2, 2230, "seqOpenVault",         0,  0, 300, 127, 0}, /* 024 */
+	{"2235 - Dead Tix",         2, 2235, "seqDeadTix",           0,  0, 300, 127, 0}, /* 025 */
+	{"2240 - Sprinkler",        2, 2240, "seqSprinkler",         0,  0, 500, 127, 0}, /* 026 */
+	{"2250 - Crane Track",      2, 2250, "seqCraneTrack",        0,  0, 300, 127, 0}, /* 027 */
+	{"2255 - Crane Fall",       2, 2255, "seqCraneFall",         0,  0, 300, 127, 0}, /* 028 */
+	{"2300 - Yr 4 Iris",        2, 2300, "seqYr4Iris",           0,  0, 300, 127, 0}, /* 029 */
+	{"2301 - Pop Bruno Casket", 2, 2301, "seqPopBrunoCasket",    0,  0, 300, 127, 0}, /* 030 */
+	{"2310 - Rocket Idea",      2, 2310, "seqRocketIdea",        0,  0, 300, 127, 0}, /* 031 */
+	{"2320 - Jello Suspense",   2, 2320, "seqJelloSuspense",     0,  0, 300, 127, 0}, /* 032 */
+	{"2325 - Lumbago Lemo",     2, 2325, "seqLumbagoLemo",       0,  0, 300, 127, 0}, /* 033 */
+	{"2327 - Breath Mint",      2, 2327, "seqBreathMint",        0,  0, 300, 127, 0}, /* 034 */
+	{"2330 - Pigeon Fly",       2, 2330, "seqPigeonFly",         0,  0, 300, 127, 0}, /* 035 */
+	{"2340 - Coffee On Boys",   2, 2340, "seqCoffeeOnBoys",      0,  0, 300, 127, 0}, /* 036 */
+	{"2350 - Sprout Aha",       2, 2350, "seqSproutAha",         0,  0, 300, 127, 0}, /* 037 */
+	{"2360 - Chowchilla Bye",   2, 2360, "seqChowchillaBye",     0,  0, 300, 127, 0}, /* 038 */
+	{"2370 - Salvador Death",   2, 2370, "seqSalvadorDeath",     0,  0, 300, 127, 0}, /* 039 */
+	{"2399 - End Credits",      2, 2399, "seqEndCredits",        0,  0, 200, 127, 0}, /* 040 */
 };
 
 } // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_tables.h b/engines/grim/imuse/dimuse_tables.h
index e9c4ae0fad9..809565cbdc0 100644
--- a/engines/grim/imuse/dimuse_tables.h
+++ b/engines/grim/imuse/dimuse_tables.h
@@ -26,18 +26,20 @@
 
 namespace Grim {
 
-struct imuseComiTable {
-	byte transitionType;
-	int16 soundId;
-	char name[20];
-	byte attribPos;
-	byte hookId;
-	int16 fadeOutDelay;
-	char filename[13];
+struct IMuseDigiStateTable {
+	char name[32];
+	int transitionId;
+	int soundId;
+	char internalName[24];
+	int attribPos;
+	int hookId;
+	int fadeTime;
+	int volume;
+	int pan;
 };
 
-extern const imuseComiTable _comiStateMusicTable[];
-extern const imuseComiTable _comiSeqMusicTable[];
+extern const IMuseDigiStateTable _grimStateMusicTable[181];
+extern const IMuseDigiStateTable _grimSeqMusicTable[41];
 
 } // End of namespace Grim
 
diff --git a/engines/grim/imuse/dimuse_triggers.cpp b/engines/grim/imuse/dimuse_triggers.cpp
index 725143e8aad..8d9a4e9a259 100644
--- a/engines/grim/imuse/dimuse_triggers.cpp
+++ b/engines/grim/imuse/dimuse_triggers.cpp
@@ -36,10 +36,6 @@ int IMuseDigiTriggersHandler::init() {
 	return clearAllTriggers();
 }
 
-int IMuseDigiTriggersHandler::deinit() {
-	return clearAllTriggers();
-}
-
 int IMuseDigiTriggersHandler::clearAllTriggers() {
 	Common::StackLock lock(*_mutex);
 
diff --git a/engines/grim/imuse/dimuse_triggers.h b/engines/grim/imuse/dimuse_triggers.h
index 6f8515f193d..abea39fa17e 100644
--- a/engines/grim/imuse/dimuse_triggers.h
+++ b/engines/grim/imuse/dimuse_triggers.h
@@ -56,7 +56,6 @@ public:
 	int  deferCommand(int count, int opcode, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n);
 	void loop();
 	int  countPendingSounds(int soundId);
-	int  deinit();
 
 };
 


Commit: 0379af169d82ea1e8f18e59a2ef283a436a9be3b
    https://github.com/scummvm/scummvm/commit/0379af169d82ea1e8f18e59a2ef283a436a9be3b
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Simplify iMUSE calls

This matches what's done on IMUSE.DLL: there are no
Cmd or Wave abstraction layers, unlike on SCUMM.

Changed paths:
    engines/grim/imuse/dimuse_cmds.cpp
    engines/grim/imuse/dimuse_defs.h
    engines/grim/imuse/dimuse_engine.cpp
    engines/grim/imuse/dimuse_engine.h
    engines/grim/imuse/dimuse_groups.cpp
    engines/grim/imuse/dimuse_scripts.cpp
    engines/grim/imuse/dimuse_tracks.cpp
    engines/grim/imuse/dimuse_wave.cpp


diff --git a/engines/grim/imuse/dimuse_cmds.cpp b/engines/grim/imuse/dimuse_cmds.cpp
index eea1dc03cca..5f0eb0bef96 100644
--- a/engines/grim/imuse/dimuse_cmds.cpp
+++ b/engines/grim/imuse/dimuse_cmds.cpp
@@ -23,224 +23,68 @@
 
 namespace Grim {
 
-// We have some uintptr arguments as commands 28, 29 and 30 actually require pointer arguments
+// We have some uintptr arguments as commands 17, 18, 19 and 29 actually require pointer arguments
 // Unfortunately this makes function calls for other command a little less pretty...
 int IMuseDigital::cmdsHandleCmd(int cmd, uint8 *ptr, int a, int b, int c, int d, int e,
 	int f, int g, int h, int i, int j, int k, int l, int m, int n) {
 
 	char *marker = (char *)ptr;
 
+	if (!_initialized)
+		return -1;
+
 	switch (cmd) {
 	case DIMUSE_C_INIT:
-		return cmdsInit();
+		return diMUSEInitialize();
+	case DIMUSE_C_TERMINATE:
+		return diMUSETerminate();
+	case 2:
+		return cmd;
 	case DIMUSE_C_PAUSE:
-		return cmdsPause();
+		diMUSEPause();
+		return cmd;
 	case DIMUSE_C_RESUME:
-		return cmdsResume();
+		diMUSEResume();
+		return cmd;
 	case DIMUSE_C_SET_GRP_VOL:
-		return _groupsHandler->setGroupVol(a, b);
+		return diMUSESetGroupVol(a, b);
 	case DIMUSE_C_START_SND:
-		cmdsStartSound(a, b);
-		break;
+		return diMUSEStartSound(a, b);
 	case DIMUSE_C_STOP_SND:
-		cmdsStopSound(a);
-		break;
+		return diMUSEStopSound(a);
 	case DIMUSE_C_STOP_ALL_SNDS:
-		cmdsStopAllSounds();
-		break;
+		return diMUSEStopAllSounds();
 	case DIMUSE_C_GET_NEXT_SND:
-		return cmdsGetNextSound(a);
+		return diMUSEGetNextSound(a);
 	case DIMUSE_C_SET_PARAM:
-		cmdsSetParam(a, b, c);
-		break;
+		return diMUSESetParam(a, b, c);
 	case DIMUSE_C_GET_PARAM:
-		return cmdsGetParam(a, b);
+		return diMUSEGetParam(a, b);
 	case DIMUSE_C_FADE_PARAM:
-		return _fadesHandler->fadeParam(a, b, c, d);
+		return diMUSEFadeParam(a, b, c, d);
 	case DIMUSE_C_SET_HOOK:
-		return cmdsSetHook(a, b);
+		return diMUSESetHook(a, b);
 	case DIMUSE_C_GET_HOOK:
-		return cmdsGetHook(a);
+		return diMUSEGetHook(a);
 	case DIMUSE_C_SET_TRIGGER:
-		return _triggersHandler->setTrigger(a, marker, c, d, e, f, g, h, i, j, k, l, m, n);
+		return diMUSESetTrigger(a, marker, c, d, e, f, g, h, i, j, k, l, m, n);
 	case DIMUSE_C_CHECK_TRIGGER:
-		return _triggersHandler->checkTrigger(a, marker, c);
+		return diMUSECheckTrigger(a, marker, c);
 	case DIMUSE_C_CLEAR_TRIGGER:
-		return _triggersHandler->clearTrigger(a, marker, c);
+		return diMUSEClearTrigger(a, marker, c);
 	case DIMUSE_C_DEFER_CMD:
-		return _triggersHandler->deferCommand(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
+		return diMUSEDeferCommand(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
 	case DIMUSE_C_START_STREAM:
-		return waveStartStream(a, b, c);
+		return diMUSEStartStream(a, b, c);
 	case DIMUSE_C_SWITCH_STREAM:
-		return waveSwitchStream(a, b, c, d, e);
+		return diMUSESwitchStream(a, b, c, d, e);
 	case DIMUSE_C_PROCESS_STREAMS:
-		return waveProcessStreams();
+		return diMUSEProcessStreams();
 	case DIMUSE_C_FEED_STREAM:
-		return waveFeedStream(a, ptr, c, d);
+		return diMUSEFeedStream(a, ptr, c, d);
 	default:
-		debug(5, "IMuseDigital::cmdsHandleCmd(): bogus/unused opcode ignored (%d).", cmd);
 		return -1;
 	}
-
-	return 0;
-}
-
-int IMuseDigital::cmdsInit() {
-	_cmdsRunning60HzCount = 0;
-	_cmdsRunning10HzCount = 0;
-
-	if (_groupsHandler->init() || _fadesHandler->init() ||
-		_triggersHandler->init() || waveInit()) {
-		return -1;
-	}
-
-	_cmdsPauseCount = 0;
-	return 48;
-}
-
-int IMuseDigital::cmdsDeinit() {
-	waveTerminate();
-	waveOutDeinit();
-	_cmdsPauseCount = 0;
-	_cmdsRunning60HzCount = 0;
-	_cmdsRunning10HzCount = 0;
-
-	return 0;
-}
-
-int IMuseDigital::cmdsTerminate() {
-	return 0;
-}
-
-int IMuseDigital::cmdsPause() {
-	int result = 0;
-
-	if (_cmdsPauseCount == 0) {
-		result = wavePause();
-	}
-
-	if (!result) {
-		result = _cmdsPauseCount + 1;
-	}
-	_cmdsPauseCount++;
-
-	return result;
-}
-
-int IMuseDigital::cmdsResume() {
-	int result = 0;
-
-	if (_cmdsPauseCount == 1) {
-		result = waveResume();
-	}
-
-	if (_cmdsPauseCount != 0) {
-		_cmdsPauseCount--;
-	}
-
-	if (!result) {
-		result = _cmdsPauseCount;
-	}
-
-	return result;
-}
-
-void IMuseDigital::cmdsSaveLoad(Common::Serializer &ser) {
-	// Serialize in this order:
-	// - Open files
-	// - Fades
-	// - Triggers
-	// - Pass the control to waveSaveLoad and then tracksSaveLoad, which will serialize:
-	//     - Dispatches
-	//     - Tracks (with SYNCs, if the game is COMI)
-	// - State and sequence info
-	// - Attributes
-
-	_filesHandler->saveLoad(ser);
-	_fadesHandler->saveLoad(ser);
-	_triggersHandler->saveLoad(ser);
-	waveSaveLoad(ser);
-	ser.syncAsSint32LE(_curMusicState, VER(103));
-	ser.syncAsSint32LE(_curMusicSeq, VER(103));
-	ser.syncAsSint32LE(_nextSeqToPlay, VER(103));
-	ser.syncArray(_attributes, ARRAYSIZE(_attributes), Common::Serializer::Sint32LE, VER(103));
-}
-
-int IMuseDigital::cmdsStartSound(int soundId, int priority) {
-	uint8 *src = _filesHandler->getSoundAddrData(soundId);
-
-	if (src == nullptr) {
-		debug(5, "IMuseDigital::cmdsStartSound(): ERROR: resource address for sound %d is NULL", soundId);
-		return -1;
-	}
-
-	// Check for the "iMUS" header
-	if (READ_BE_UINT32(src) == MKTAG('i', 'M', 'U', 'S'))
-		return waveStartSound(soundId, priority);
-
-	return -1;
-}
-
-int IMuseDigital::cmdsStopSound(int soundId) {
-	int result = _filesHandler->getNextSound(soundId);
-
-	if (result != 2)
-		return -1;
-
-	return waveStopSound(soundId);
-}
-
-int IMuseDigital::cmdsStopAllSounds() {
-	return _triggersHandler->clearAllTriggers() | waveStopAllSounds();
-}
-
-int IMuseDigital::cmdsGetNextSound(int soundId) {
-	return waveGetNextSound(soundId);
-}
-
-int IMuseDigital::cmdsSetParam(int soundId, int subCmd, int value) {
-	int result = _filesHandler->getNextSound(soundId);
-
-	if (result != 2)
-		return -1;
-
-	return waveSetParam(soundId, subCmd, value);
-}
-
-int IMuseDigital::cmdsGetParam(int soundId, int subCmd) {
-	int result = _filesHandler->getNextSound(soundId);
-
-	if (subCmd != 0) {
-		if (subCmd == DIMUSE_P_TRIGS_SNDS) {
-			return _triggersHandler->countPendingSounds(soundId);
-		}
-
-		if (result == 2) {
-			return waveGetParam(soundId, subCmd);
-		}
-
-		result = (subCmd == DIMUSE_P_SND_TRACK_NUM) - 1;
-	}
-
-	return result;
-}
-
-int IMuseDigital::cmdsSetHook(int soundId, int hookId) {
-	int result = _filesHandler->getNextSound(soundId);
-
-	if (result != 2)
-		return -1;
-
-	return waveSetHook(soundId, hookId);
-}
-
-int IMuseDigital::cmdsGetHook(int soundId) {
-	int result = _filesHandler->getNextSound(soundId);
-
-	if (result != 2)
-		return -1;
-
-	return waveGetHook(soundId);
 }
 
 } // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_defs.h b/engines/grim/imuse/dimuse_defs.h
index 891f5d0e3e9..b96f2aaf9c1 100644
--- a/engines/grim/imuse/dimuse_defs.h
+++ b/engines/grim/imuse/dimuse_defs.h
@@ -60,8 +60,8 @@ enum {
 
 #define DIMUSE_TIMER_BASE_RATE_HZ       50
 #define DIMUSE_TIMER_BASE_RATE_USEC     20000  // 1000000 / 50Hz
-#define DIMUSE_TIMER_GAIN_RED_RATE_USEC 100000 // 1000000 / 10Hz
-#define DIMUSE_TIMER_FADES_RATE_USEC    16667  // 1000000 / 60Hz
+#define DIMUSE_TIMER_GAIN_RED_RATE_USEC 200000 // 1000000 / 5Hz
+#define DIMUSE_TIMER_FADES_RATE_USEC    20000  // 1000000 / 50Hz
 
 // Parameters IDs
 #define DIMUSE_P_BOGUS_ID       0x0
@@ -107,6 +107,7 @@ enum {
 
 // Internal command IDs
 #define DIMUSE_C_INIT             0
+#define DIMUSE_C_TERMINATE        1
 #define DIMUSE_C_PAUSE            3
 #define DIMUSE_C_RESUME           4
 #define DIMUSE_C_SET_GRP_VOL      7
diff --git a/engines/grim/imuse/dimuse_engine.cpp b/engines/grim/imuse/dimuse_engine.cpp
index b2b1bdfdf21..7f22004e5d9 100644
--- a/engines/grim/imuse/dimuse_engine.cpp
+++ b/engines/grim/imuse/dimuse_engine.cpp
@@ -35,7 +35,7 @@ namespace Grim {
 
 void IMuseDigital::timer_handler(void *refCon) {
 	IMuseDigital *diMUSE = (IMuseDigital *)refCon;
-	diMUSE->callback();
+	diMUSE->diMUSEHeartbeat();
 }
 
 IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode)
@@ -68,6 +68,7 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 
 	_dispatchFadeSize = 0;
 
+	_initialized = 0;
 	_scriptInitializedFlag = 0;
 	_callbackInterruptFlag = 0;
 	_spooledMusicEnabled = true;
@@ -121,20 +122,17 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 
 IMuseDigital::~IMuseDigital() {
 	g_system->getTimerManager()->removeTimerProc(timer_handler);
+	diMUSETerminateScript();
+	diMUSETerminate();
 	_filesHandler->deallocSoundBuffer(DIMUSE_BUFFER_SPEECH);
 	_filesHandler->deallocSoundBuffer(DIMUSE_BUFFER_MUSIC);
 	_filesHandler->deallocSoundBuffer(DIMUSE_BUFFER_SFX);
-	cmdsDeinit();
-	diMUSETerminate();
 	delete _internalMixer;
 	delete _groupsHandler;
 	delete _fadesHandler;
 	delete _triggersHandler;
 	delete _filesHandler;
 
-	// Deinit the Dispatch module
-	dispatchTerminate();
-
 	// Deinit the WaveOut module
 	free(_waveOutOutputBuffer);
 	_waveOutOutputBuffer = nullptr;
@@ -172,25 +170,13 @@ int IMuseDigital::isSoundRunning(int soundId) {
 	return diMUSEGetParam(soundId, DIMUSE_P_SND_TRACK_NUM) > 0;
 }
 
-void IMuseDigital::callback() {
-	if (_cmdsPauseCount)
-		return;
-
-	if (!_callbackInterruptFlag) {
-		_callbackInterruptFlag = 1;
-		diMUSEHeartbeat();
-		_callbackInterruptFlag = 0;
-	}
-}
-
 void IMuseDigital::diMUSEHeartbeat() {
-	// This is what happens:
-	// - Usual audio stuff like fetching and playing sound (and everything
-	//   within waveOutCallback()) happens at a base 50Hz rate;
-	// - Triggers and fades handling happens at a (somewhat hacky) 60Hz rate;
-	// - Music gain reduction happens at a 10Hz rate.
+	int soundId, musicTargetVolume, musicEffVol, musicVol, tempVol, tempEffVol;
+
+	if (_callbackInterruptFlag)
+		return;
 
-	int soundId, foundGroupId, musicTargetVolume, musicEffVol, musicVol, tempVol, tempEffVol, factor, step;
+	_callbackInterruptFlag = 1;
 
 	waveOutCallback();
 
@@ -214,74 +200,59 @@ void IMuseDigital::diMUSEHeartbeat() {
 	// 	}
 	// }
 
-	// Handle fades and triggers
-
-	_cmdsRunning60HzCount += _usecPerInt;
-	while (_cmdsRunning60HzCount >= DIMUSE_TIMER_FADES_RATE_USEC) {
-		_cmdsRunning60HzCount -= DIMUSE_TIMER_FADES_RATE_USEC;
-		_fadesHandler->loop();
-		_triggersHandler->loop();
-	}
-
-	_cmdsRunning10HzCount += _usecPerInt;
-	if (_cmdsRunning10HzCount < DIMUSE_TIMER_GAIN_RED_RATE_USEC)
-		return;
-
-	do {
-		// SPEECH GAIN REDUCTION 10Hz
-		_cmdsRunning10HzCount -= DIMUSE_TIMER_GAIN_RED_RATE_USEC;
-		soundId = 0;
-		musicTargetVolume = _groupsHandler->setGroupVol(DIMUSE_GROUP_MUSIC, -1);
-		while (1) { // Check all tracks to see if there's a speech file playing
-			soundId = waveGetNextSound(soundId);
-			if (!soundId)
-				break;
-
-			foundGroupId = -1;
-			if (_filesHandler->getNextSound(soundId) == 2) {
-				foundGroupId = waveGetParam(soundId, DIMUSE_P_GROUP); // Check the groupId of this sound
-			}
-
-			if (foundGroupId == DIMUSE_GROUP_SPEECH) {
-				// Remember: when a speech file stops playing this block stops
-				// being executed, so musicTargetVolume returns back to its original value
-				factor = 80;
-				musicTargetVolume = (musicTargetVolume * factor) / 128;
-				break;
-			}
+	if (!_cmdsPauseCount) {
+		// Handle fades and triggers
+		_cmdsRunning50HzCount += _usecPerInt;
+		while (_cmdsRunning50HzCount >= DIMUSE_TIMER_FADES_RATE_USEC) {
+			_cmdsRunning50HzCount -= DIMUSE_TIMER_FADES_RATE_USEC;
+			_fadesHandler->loop();
+			_triggersHandler->loop();
 		}
 
-		musicEffVol = _groupsHandler->setGroupVol(DIMUSE_GROUP_MUSICEFF, -1); // MUSIC EFFECTIVE VOLUME GROUP (used for gain reduction)
-		musicVol = _groupsHandler->setGroupVol(DIMUSE_GROUP_MUSIC, -1); // MUSIC VOLUME SUBGROUP (keeps track of original music volume)
-
-		if (musicEffVol < musicTargetVolume) { // If there is gain reduction already going on...
-			tempEffVol = musicEffVol + 3;
-			if (tempEffVol < musicTargetVolume) {
-				if (musicVol <= tempEffVol) {
-					musicVol = tempEffVol;
-				}
-			} else if (musicVol <= musicTargetVolume) { // Bring up the music volume immediately when speech stops playing
-				musicVol = musicTargetVolume;
-			}
-			_groupsHandler->setGroupVol(DIMUSE_GROUP_MUSICEFF, musicVol);
-		} else if (musicEffVol > musicTargetVolume) {
-			// Bring music volume down to target volume with a -18 step
-		    // if there's speech playing or else, just cap it to the target if it's out of range
-			step = 18;
-			tempVol = musicEffVol - step;
-			if (tempVol <= musicTargetVolume) {
-				if (musicVol >= musicTargetVolume) {
-					musicVol = musicTargetVolume;
+		// Music gain reduction while speech is playing
+		_cmdsRunning5HzCount += _usecPerInt;
+		if (_cmdsRunning5HzCount >= DIMUSE_TIMER_GAIN_RED_RATE_USEC) {
+			while (1) {
+				_cmdsRunning5HzCount -= DIMUSE_TIMER_GAIN_RED_RATE_USEC;
+
+				musicTargetVolume = _groupsHandler->setGroupVol(DIMUSE_GROUP_MUSIC, -1);
+				for (soundId = diMUSEGetNextSound(0); soundId; soundId = diMUSEGetNextSound(soundId)) {
+					if (diMUSEGetParam(soundId, DIMUSE_P_GROUP) == DIMUSE_GROUP_SPEECH) {
+						musicTargetVolume = (77 * musicTargetVolume) >> 7;
+						break;
+					}
 				}
-			} else {
-				if (musicVol >= tempVol) {
-					musicVol = tempVol;
+
+				musicEffVol = _groupsHandler->setGroupVol(DIMUSE_GROUP_MUSICEFF, -1);
+				musicVol = _groupsHandler->setGroupVol(DIMUSE_GROUP_MUSIC, -1);
+
+				if (musicEffVol > musicTargetVolume) {
+					tempVol = musicEffVol - 36;
+					if (tempVol <= musicTargetVolume) {
+						if (musicTargetVolume < musicVol)
+							musicVol = musicTargetVolume;
+					} else if (tempVol < musicVol) {
+						musicVol = tempVol;
+					}
+					_groupsHandler->setGroupVol(DIMUSE_GROUP_MUSICEFF, musicVol);
+				} else if (musicEffVol < musicTargetVolume) {
+					tempEffVol = musicEffVol + 1;
+					if (tempEffVol < musicTargetVolume) {
+						if (tempEffVol > musicVol)
+							musicVol = tempEffVol;
+					} else if (musicTargetVolume > musicVol) {
+						musicVol = musicTargetVolume;
+					}
+					_groupsHandler->setGroupVol(DIMUSE_GROUP_MUSICEFF, musicVol);
 				}
+
+				if (_cmdsRunning5HzCount < DIMUSE_TIMER_GAIN_RED_RATE_USEC)
+					break;
 			}
-			_groupsHandler->setGroupVol(DIMUSE_GROUP_MUSICEFF, musicVol);
 		}
+	}
 
-	} while (_cmdsRunning10HzCount >= DIMUSE_TIMER_GAIN_RED_RATE_USEC);
+	_callbackInterruptFlag = 0;
 }
 
 void IMuseDigital::setPriority(int soundId, int priority) {
@@ -426,90 +397,176 @@ int IMuseDigital::getFeedSize() {
 }
 
 int IMuseDigital::diMUSETerminate() {
-	if (_scriptInitializedFlag) {
-		diMUSEStopAllSounds();
-		_filesHandler->closeAllSounds();
-	}
-
-	return 0;
+	return tracksDeinit();
 }
 
 int IMuseDigital::diMUSEInitialize() {
-	return cmdsHandleCmd(DIMUSE_C_INIT);
+	if (_initialized)
+		return -1;
+
+	_cmdsRunning50HzCount = 0;
+	_cmdsRunning5HzCount = 0;
+
+	if (_groupsHandler->init() || _fadesHandler->init() ||
+		_triggersHandler->init() || tracksInit()) {
+		return -1;
+	}
+
+	_callbackInterruptFlag = 0;
+	_cmdsPauseCount = 0;
+	_initialized = 1;
+	return 49;
 }
 
-int IMuseDigital::diMUSEPause() {
-	return cmdsHandleCmd(DIMUSE_C_PAUSE);
+void IMuseDigital::diMUSEPause() {
+	Common::StackLock lock(*_mutex);
+
+	if (_cmdsPauseCount++ == 0)
+		tracksPause();
 }
 
-int IMuseDigital::diMUSEResume() {
-	return cmdsHandleCmd(DIMUSE_C_RESUME);
+void IMuseDigital::diMUSEResume() {
+	Common::StackLock lock(*_mutex);
+
+	if (--_cmdsPauseCount) {
+		if (_cmdsPauseCount < 0)
+			_cmdsPauseCount = 0;
+	} else {
+		tracksResume();
+	}
 }
 
-void IMuseDigital::diMUSESaveLoad(Common::Serializer &ser) {
-	cmdsSaveLoad(ser);
+int IMuseDigital::diMUSESaveLoad(Common::Serializer &ser) {
+	Common::StackLock lock(*_mutex);
+
+	if (ser.isLoading())
+		diMUSEStopAllSounds();
+
+	_fadesHandler->saveLoad(ser);
+	_triggersHandler->saveLoad(ser);
+	tracksSaveLoad(ser);
+	return 0;
 }
 
 int IMuseDigital::diMUSESetGroupVol(int groupId, int volume) {
-	return cmdsHandleCmd(DIMUSE_C_SET_GRP_VOL, nullptr, groupId, volume);
+	return _groupsHandler->setGroupVol(groupId, volume);
 }
 
 int IMuseDigital::diMUSEStartSound(int soundId, int priority) {
-	return cmdsHandleCmd(DIMUSE_C_START_SND, nullptr, soundId, priority);
+	uint8 *src = _filesHandler->getSoundAddrData(soundId);
+
+	if (src == nullptr) {
+		debug(5, "IMuseDigital::diMUSEStartSound(): ERROR: resource address for sound %d is NULL", soundId);
+		return -1;
+	}
+
+	// Check for the "iMUS" header
+	if (READ_BE_UINT32(src) == MKTAG('i', 'M', 'U', 'S')) {
+		Common::StackLock lock(*_mutex);
+		return tracksStartSound(soundId, priority, 0);
+	}
+
+	return -1;
 }
 
 int IMuseDigital::diMUSEStopSound(int soundId) {
 	debug(5, "IMuseDigital::diMUSEStopSound(): %d", soundId);
-	return cmdsHandleCmd(DIMUSE_C_STOP_SND, nullptr, soundId);
+	Common::StackLock lock(*_mutex);
+	return tracksStopSound(soundId);
 }
 
 int IMuseDigital::diMUSEStopAllSounds() {
 	debug(5, "IMuseDigital::diMUSEStopAllSounds()");
-	return cmdsHandleCmd(DIMUSE_C_STOP_ALL_SNDS);
+	Common::StackLock lock(*_mutex);
+	return tracksStopAllSounds();
 }
 
 int IMuseDigital::diMUSEGetNextSound(int soundId) {
-	return cmdsHandleCmd(DIMUSE_C_GET_NEXT_SND, nullptr, soundId);
+	return tracksGetNextSound(soundId);
 }
 
 int IMuseDigital::diMUSESetParam(int soundId, int paramId, int value) {
-	return cmdsHandleCmd(DIMUSE_C_SET_PARAM, nullptr, soundId, paramId, value);
+	Common::StackLock lock(*_mutex);
+	return tracksSetParam(soundId, paramId, value);
 }
 
 int IMuseDigital::diMUSEGetParam(int soundId, int paramId) {
-	return cmdsHandleCmd(DIMUSE_C_GET_PARAM, nullptr, soundId, paramId);
+	int param;
+
+	if (!paramId)
+		return 2;
+
+	if (paramId == DIMUSE_P_TRIGS_SNDS)
+		return _triggersHandler->countPendingSounds(soundId);
+
+	{
+		Common::StackLock lock(*_mutex);
+		param = tracksGetParam(soundId, paramId);
+	}
+
+	if (param < 0 && paramId == DIMUSE_P_SND_TRACK_NUM)
+		return 0;
+
+	return param;
 }
 
 int IMuseDigital::diMUSEFadeParam(int soundId, int opcode, int destValue, int fadeLength) {
-	return cmdsHandleCmd(DIMUSE_C_FADE_PARAM, nullptr, soundId, opcode, destValue, fadeLength);
+	return _fadesHandler->fadeParam(soundId, opcode, destValue, fadeLength);
 }
 
 int IMuseDigital::diMUSESetHook(int soundId, int hookId) {
-	return cmdsHandleCmd(DIMUSE_C_SET_HOOK, nullptr, soundId, hookId);
+	return tracksSetHook(soundId, hookId);
+}
+
+int IMuseDigital::diMUSEGetHook(int soundId) {
+	return tracksGetHook(soundId);
 }
 
 int IMuseDigital::diMUSESetTrigger(int soundId, const char *marker, int opcode, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
-	return cmdsHandleCmd(DIMUSE_C_SET_TRIGGER, (uint8 *)marker, soundId, 0, opcode, d, e, f, g, h, i, j, k, l, m, n);
+	return _triggersHandler->setTrigger(soundId, (char *)marker, opcode, d, e, f, g, h, i, j, k, l, m, n);
+}
+
+int IMuseDigital::diMUSECheckTrigger(int soundId, const char *marker, int opcode) {
+	return _triggersHandler->checkTrigger(soundId, (char *)marker, opcode);
+}
+
+int IMuseDigital::diMUSEClearTrigger(int soundId, const char *marker, int opcode) {
+	return _triggersHandler->clearTrigger(soundId, (char *)marker, opcode);
+}
+
+int IMuseDigital::diMUSEDeferCommand(int count, int opcode, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
+	return _triggersHandler->deferCommand(count, opcode, c, d, e, f, g, h, i, j, k, l, m, n);
 }
 
 int IMuseDigital::diMUSEStartStream(int soundId, int priority, int bufferId) {
-	return cmdsHandleCmd(DIMUSE_C_START_STREAM, nullptr, soundId, priority, bufferId);
+	// TODO
+	// if (!filesCheckRange(soundId))
+	// 	return -1;
+	if (soundId == 0)
+		return -1;
+
+	Common::StackLock lock(*_mutex);
+	return tracksStartSound(soundId, priority, bufferId);
 }
 
 int IMuseDigital::diMUSESwitchStream(int oldSoundId, int newSoundId, int fadeDelay, int fadeSyncFlag2, int fadeSyncFlag1) {
-	return cmdsHandleCmd(DIMUSE_C_SWITCH_STREAM, nullptr, oldSoundId, newSoundId, fadeDelay, fadeSyncFlag2, fadeSyncFlag1);
+	Common::StackLock lock(*_mutex);
+	return dispatchSwitchStream(oldSoundId, newSoundId, fadeDelay, fadeSyncFlag2, fadeSyncFlag1);
 }
 
 int IMuseDigital::diMUSEProcessStreams() {
-	return cmdsHandleCmd(DIMUSE_C_PROCESS_STREAMS);
+	Common::StackLock lock(*_mutex);
+	return streamerProcessStreams();
 }
 
 int IMuseDigital::diMUSEQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
-	return waveQueryStream(soundId, bufSize, criticalSize, freeSpace, paused);
+	Common::StackLock lock(*_mutex);
+	return tracksQueryStream(soundId, bufSize, criticalSize, freeSpace, paused);
 }
 
 int IMuseDigital::diMUSEFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused) {
-	return cmdsHandleCmd(DIMUSE_C_FEED_STREAM, srcBuf, soundId, -1, sizeToFeed, paused);
+	Common::StackLock lock(*_mutex);
+	return tracksFeedStream(soundId, srcBuf, sizeToFeed, paused);
 }
 
 int IMuseDigital::diMUSEGetMusicGroupVol() {
@@ -557,14 +614,18 @@ int IMuseDigital::diMUSESetVoiceGroupVol(int volume) {
 	return diMUSESetGroupVol(DIMUSE_GROUP_SPEECH, volume);
 }
 
-void IMuseDigital::diMUSEUpdateGroupVolumes() {
-	waveUpdateGroupVolumes();
-}
-
 int IMuseDigital::diMUSEInitializeScript() {
 	return scriptParse(DIMUSE_C_SCRIPT_INIT, -1, -1);
 }
 
+int IMuseDigital::diMUSETerminateScript() {
+	return scriptParse(DIMUSE_C_SCRIPT_TERMINATE, -1, -1);
+}
+
+void IMuseDigital::diMUSESaveLoadScript(Common::Serializer &ser) {
+	scriptSaveLoad(ser);
+}
+
 void IMuseDigital::diMUSERefreshScript() {
 	scriptParse(DIMUSE_C_SCRIPT_REFRESH, -1, -1);
 }
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/dimuse_engine.h
index 3fb5845d0d5..78a4fa1feec 100644
--- a/engines/grim/imuse/dimuse_engine.h
+++ b/engines/grim/imuse/dimuse_engine.h
@@ -68,7 +68,6 @@ private:
 
 	int _callbackFps;
 	static void timer_handler(void *refConf);
-	void callback();
 
 	bool _isEngineDisabled;
 	bool _checkForUnderrun;
@@ -112,6 +111,7 @@ private:
 	int scriptParse(int cmd, int a, int b);
 	int scriptInit();
 	int scriptTerminate();
+	void scriptSaveLoad(Common::Serializer &ser);
 	void scriptDeinit();
 	void scriptRefresh();
 	void scriptSetState(int soundId);
@@ -121,24 +121,10 @@ private:
 	int scriptSetAttribute(int attrIndex, int attrVal);
 
 	// CMDs
+	int _initialized;
 	int _cmdsPauseCount;
-	int _cmdsRunning60HzCount;
-	int _cmdsRunning10HzCount;
-
-	int cmdsInit();
-	int cmdsDeinit();
-	int cmdsTerminate();
-	int cmdsPause();
-	int cmdsResume();
-	void cmdsSaveLoad(Common::Serializer &ser);
-	int cmdsStartSound(int soundId, int priority);
-	int cmdsStopSound(int soundId);
-	int cmdsStopAllSounds();
-	int cmdsGetNextSound(int soundId);
-	int cmdsSetParam(int soundId, int opcode, int value);
-	int cmdsGetParam(int soundId, int opcode);
-	int cmdsSetHook(int soundId, int hookId);
-	int cmdsGetHook(int soundId);
+	int _cmdsRunning50HzCount;
+	int _cmdsRunning5HzCount;
 
 	// Streamer
 	IMuseDigiStream _streams[DIMUSE_MAX_STREAMS];
@@ -171,7 +157,6 @@ private:
 	void tracksPause();
 	void tracksResume();
 	void tracksSaveLoad(Common::Serializer &ser);
-	void tracksSetGroupVol();
 	void tracksCallback();
 	void tracksLowLatencyCallback();
 	int tracksStartSound(int soundId, int tryPriority, int group);
@@ -186,7 +171,7 @@ private:
 	int tracksSetHook(int soundId, int hookId);
 	int tracksGetHook(int soundId);
 	IMuseDigiTrack *tracksReserveTrack(int priority);
-	void tracksDeinit();
+	int tracksDeinit();
 
 	// Dispatch
 	IMuseDigiDispatch _dispatches[DIMUSE_MAX_DISPATCHES];
@@ -232,27 +217,6 @@ private:
 	int dispatchUpdateFadeMixVolume(IMuseDigiDispatch *dispatchPtr, int32 remainingFade);
 	int dispatchUpdateFadeSlope(IMuseDigiDispatch *dispatchPtr);
 
-	// Wave (mainly a wrapper for Tracks functions)
-	int waveInit();
-	int waveTerminate();
-	int wavePause();
-	int waveResume();
-	void waveSaveLoad(Common::Serializer &ser);
-	void waveUpdateGroupVolumes();
-	int waveStartSound(int soundId, int priority);
-	int waveStopSound(int soundId);
-	int waveStopAllSounds();
-	int waveGetNextSound(int soundId);
-	int waveSetParam(int soundId, int opcode, int value);
-	int waveGetParam(int soundId, int opcode);
-	int waveSetHook(int soundId, int hookId);
-	int waveGetHook(int soundId);
-	int waveStartStream(int soundId, int priority, int groupId);
-	int waveSwitchStream(int oldSoundId, int newSoundId, int fadeLengthMs, int fadeSyncFlag2, int fadeSyncFlag1);
-	int waveProcessStreams();
-	int waveQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
-	int waveFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused);
-
 	// Waveapi
 	waveOutParamsStruct waveOutSettings;
 
@@ -309,12 +273,15 @@ public:
 	int32 getCurMusicPosInMs();
 	int32 getSoundElapsedTimeInMs(int soundId);
 
+	// Called by the Groups module
+	void tracksSetGroupVol();
+
 	// General engine functions
 	int diMUSETerminate();
 	int diMUSEInitialize();
-	int diMUSEPause();
-	int diMUSEResume();
-	void diMUSESaveLoad(Common::Serializer &ser);
+	void diMUSEPause();
+	void diMUSEResume();
+	int diMUSESaveLoad(Common::Serializer &ser);
 	int diMUSESetGroupVol(int groupId, int volume);
 	int diMUSEStartSound(int soundId, int priority);
 	int diMUSEStopSound(int soundId);
@@ -324,11 +291,15 @@ public:
 	int diMUSEGetParam(int soundId, int paramId);
 	int diMUSEFadeParam(int soundId, int opcode, int destValue, int fadeLength);
 	int diMUSESetHook(int soundId, int hookId);
+	int diMUSEGetHook(int soundId);
 
 	int diMUSESetTrigger(int soundId, const char *marker, int opcode,
 		int d = -1, int e = -1, int f = -1, int g = -1,
 		int h = -1, int i = -1, int j = -1, int k = -1,
 		int l = -1, int m = -1, int n = -1);
+	int diMUSECheckTrigger(int soundId, const char *marker, int opcode);
+	int diMUSEClearTrigger(int soundId, const char *marker, int opcode);
+	int diMUSEDeferCommand(int count, int opcode, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n);
 
 	int diMUSEStartStream(int soundId, int priority, int groupId);
 	int diMUSESwitchStream(int oldSoundId, int newSoundId, int fadeDelay, int fadeSyncFlag2, int fadeSyncFlag1);
@@ -341,8 +312,9 @@ public:
 	int diMUSESetMusicGroupVol(int volume);
 	int diMUSESetSFXGroupVol(int volume);
 	int diMUSESetVoiceGroupVol(int volume);
-	void diMUSEUpdateGroupVolumes();
 	int diMUSEInitializeScript();
+	int diMUSETerminateScript();
+	void diMUSESaveLoadScript(Common::Serializer &ser);
 	void diMUSERefreshScript();
 	int diMUSESetState(int soundId);
 	int diMUSESetSequence(int soundId);
diff --git a/engines/grim/imuse/dimuse_groups.cpp b/engines/grim/imuse/dimuse_groups.cpp
index 79e95c8c152..6f7de12b1b9 100644
--- a/engines/grim/imuse/dimuse_groups.cpp
+++ b/engines/grim/imuse/dimuse_groups.cpp
@@ -69,7 +69,7 @@ int IMuseDigiGroupsHandler::setGroupVol(uint32 id, int volume) {
 		}
 	}
 
-	_engine->diMUSEUpdateGroupVolumes();
+	_engine->tracksSetGroupVol();
 	return oldVolume;
 }
 
diff --git a/engines/grim/imuse/dimuse_scripts.cpp b/engines/grim/imuse/dimuse_scripts.cpp
index f387f4339bb..bc0b9e99842 100644
--- a/engines/grim/imuse/dimuse_scripts.cpp
+++ b/engines/grim/imuse/dimuse_scripts.cpp
@@ -218,6 +218,17 @@ int IMuseDigital::scriptSetAttribute(int attrIndex, int attrVal) {
 	return 0;
 }
 
+void IMuseDigital::scriptSaveLoad(Common::Serializer &ser) {
+	if (ser.isLoading())
+		_filesHandler->closeAllSounds();
+
+	ser.syncAsSint32LE(_curMusicState, VER(103));
+	ser.syncAsSint32LE(_curMusicSeq, VER(103));
+	ser.syncAsSint32LE(_nextSeqToPlay, VER(103));
+	ser.syncArray(_attributes, ARRAYSIZE(_attributes), Common::Serializer::Sint32LE, VER(103));
+	_filesHandler->saveLoad(ser);
+}
+
 void IMuseDigital::scriptDeinit() {
 	diMUSEStopAllSounds();
 	_filesHandler->closeAllSounds();
diff --git a/engines/grim/imuse/dimuse_tracks.cpp b/engines/grim/imuse/dimuse_tracks.cpp
index c444c3ad13f..44e859e601f 100644
--- a/engines/grim/imuse/dimuse_tracks.cpp
+++ b/engines/grim/imuse/dimuse_tracks.cpp
@@ -561,8 +561,11 @@ IMuseDigiTrack *IMuseDigital::tracksReserveTrack(int priority) {
 	return nullptr;
 }
 
-void IMuseDigital::tracksDeinit() {
+int IMuseDigital::tracksDeinit() {
 	tracksStopAllSounds();
+	waveOutDeinit();
+	dispatchTerminate();
+	return _internalMixer->terminate();
 }
 
 } // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_wave.cpp b/engines/grim/imuse/dimuse_wave.cpp
index cd343b0559a..9f5d17d4f33 100644
--- a/engines/grim/imuse/dimuse_wave.cpp
+++ b/engines/grim/imuse/dimuse_wave.cpp
@@ -23,101 +23,4 @@
 
 namespace Grim {
 
-int IMuseDigital::waveInit() {
-	if (tracksInit())
-		return -1;
-	return 0;
-}
-
-int IMuseDigital::waveTerminate() {
-	return 0;
-}
-
-int IMuseDigital::wavePause() {
-	Common::StackLock lock(*_mutex);
-	tracksPause();
-	return 0;
-}
-
-int IMuseDigital::waveResume() {
-	Common::StackLock lock(*_mutex);
-	tracksResume();
-	return 0;
-}
-
-void IMuseDigital::waveSaveLoad(Common::Serializer &ser) {
-	Common::StackLock lock(*_mutex);
-	tracksSaveLoad(ser);
-}
-
-void IMuseDigital::waveUpdateGroupVolumes() {
-	Common::StackLock lock(*_mutex);
-	tracksSetGroupVol();
-}
-
-int IMuseDigital::waveStartSound(int soundId, int priority) {
-	Common::StackLock lock(*_mutex);
-	return tracksStartSound(soundId, priority, 0);
-}
-
-int IMuseDigital::waveStopSound(int soundId) {
-	Common::StackLock lock(*_mutex);
-	return tracksStopSound(soundId);
-}
-
-int IMuseDigital::waveStopAllSounds() {
-	Common::StackLock lock(*_mutex);
-	return tracksStopAllSounds();
-}
-
-int IMuseDigital::waveGetNextSound(int soundId) {
-	return tracksGetNextSound(soundId);
-}
-
-int IMuseDigital::waveSetParam(int soundId, int opcode, int value) {
-	Common::StackLock lock(*_mutex);
-	return tracksSetParam(soundId, opcode, value);
-}
-
-int IMuseDigital::waveGetParam(int soundId, int opcode) {
-	Common::StackLock lock(*_mutex);
-	return tracksGetParam(soundId, opcode);
-}
-
-int IMuseDigital::waveSetHook(int soundId, int hookId) {
-	return tracksSetHook(soundId, hookId);
-}
-
-int IMuseDigital::waveGetHook(int soundId) {
-	return tracksGetHook(soundId);
-}
-
-int IMuseDigital::waveStartStream(int soundId, int priority, int bufferId) {
-	if (soundId == 0)
-		return -1;
-
-	Common::StackLock lock(*_mutex);
-	return tracksStartSound(soundId, priority, bufferId);
-}
-
-int IMuseDigital::waveSwitchStream(int oldSoundId, int newSoundId, int fadeLengthMs, int fadeSyncFlag2, int fadeSyncFlag1) {
-	Common::StackLock lock(*_mutex);
-	return dispatchSwitchStream(oldSoundId, newSoundId, fadeLengthMs, fadeSyncFlag2, fadeSyncFlag1);
-}
-
-int IMuseDigital::waveProcessStreams() {
-	Common::StackLock lock(*_mutex);
-	return streamerProcessStreams();
-}
-
-int  IMuseDigital::waveQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
-	Common::StackLock lock(*_mutex);
-	return tracksQueryStream(soundId, bufSize, criticalSize, freeSpace, paused);
-}
-
-int IMuseDigital::waveFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused) {
-	Common::StackLock lock(*_mutex);
-	return tracksFeedStream(soundId, srcBuf, sizeToFeed, paused);
-}
-
 } // End of namespace Grim


Commit: 26455cd32348e6966c3b1b5cb2c06cfa5982f80b
    https://github.com/scummvm/scummvm/commit/26455cd32348e6966c3b1b5cb2c06cfa5982f80b
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Begin porting original file layer

Changed paths:
    engines/grim/imuse/dimuse_defs.h
    engines/grim/imuse/dimuse_dispatch.cpp
    engines/grim/imuse/dimuse_engine.cpp
    engines/grim/imuse/dimuse_engine.h
    engines/grim/imuse/dimuse_files.cpp
    engines/grim/imuse/dimuse_files.h
    engines/grim/imuse/dimuse_scripts.cpp
    engines/grim/imuse/dimuse_streamer.cpp
    engines/grim/imuse/dimuse_tracks.cpp


diff --git a/engines/grim/imuse/dimuse_defs.h b/engines/grim/imuse/dimuse_defs.h
index b96f2aaf9c1..6596a49bd24 100644
--- a/engines/grim/imuse/dimuse_defs.h
+++ b/engines/grim/imuse/dimuse_defs.h
@@ -22,6 +22,10 @@
 #ifndef GRIM_IMUSE_DEFS_H
 #define GRIM_IMUSE_DEFS_H
 
+namespace Common {
+class SeekableReadStream;
+}
+
 namespace Grim {
 
 #define DIMUSE_MAX_GROUPS      16
@@ -34,6 +38,8 @@ namespace Grim {
 #define DIMUSE_MAX_STREAMZONES 50
 #define DIMUSE_MAX_FADE_VOLUME 8323072
 #define DIMUSE_MAX_STREAMS     3
+#define DIMUSE_MAX_SOUND_LIST  10
+#define DIMUSE_MAX_OPEN_FILES  5
 
 #define DIMUSE_LARGE_FADES    1
 #define DIMUSE_SMALL_FADES    4
@@ -233,6 +239,38 @@ typedef struct {
 	int32 criticalSize;
 } IMuseDigiSndBuffer;
 
+struct IMuseDigiSoundList {
+	IMuseDigiSoundList *prev;
+	IMuseDigiSoundList *next;
+	int soundId;
+	char filename[36];
+	int refCount;
+};
+
+struct IMuseDigiResource {
+	Common::SeekableReadStream *resId;
+	bool hasMcmp;
+	int32 resSize;
+	int32 fileCurOffset;
+	int32 compBlocksNum;
+	uint8 *mcmpBlockPtr;
+	uint8 **compBlockPtr;
+	int32 *decompBlockSize;
+	int32 *compBlockOffset;
+	int32 *compBlockSize;
+	int32 *vimaOffsets;
+	int32 curProcessedCompBlock;
+	int32 curDecompBlockSize;
+	uint8 *decompDataBuffer;
+	char filename[80];
+};
+
+struct IMuseDigiOpenAudioFile {
+	IMuseDigiResource *resourcePtr;
+	char soundName[32];
+	int refCount;
+};
+
 struct IMuseDigiDispatch {
 	IMuseDigiTrack *trackPtr;
 	int wordSize;
diff --git a/engines/grim/imuse/dimuse_dispatch.cpp b/engines/grim/imuse/dimuse_dispatch.cpp
index ef7f717b76e..7495cabc078 100644
--- a/engines/grim/imuse/dimuse_dispatch.cpp
+++ b/engines/grim/imuse/dimuse_dispatch.cpp
@@ -524,11 +524,12 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 
 				return;
 			}
+
 			dispatchPtr->streamZoneList->offset += effRemainingAudio;
 			dispatchPtr->streamZoneList->size -= effRemainingAudio;
 			dispatchPtr->streamErrFlag = 0;
 		} else {
-			soundAddrData = _filesHandler->getSoundAddrData(trackPtr->soundId);
+			soundAddrData = filesGetSoundAddrData(trackPtr->soundId);
 			if (!soundAddrData) {
 				debug(5, "IMuseDigital::dispatchProcessDispatches(): ERROR: soundAddrData for sound %d is NULL", trackPtr->soundId);
 				return;
@@ -822,7 +823,7 @@ int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
 
 		} else {
 			// Otherwise, this is a SFX and we must load it using its resource pointer
-			soundAddrData = _filesHandler->getSoundAddrData(dispatchPtr->trackPtr->soundId);
+			soundAddrData = filesFetchMap(dispatchPtr->trackPtr->soundId);
 
 			if (!soundAddrData) {
 				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: couldn't get sound address");
diff --git a/engines/grim/imuse/dimuse_engine.cpp b/engines/grim/imuse/dimuse_engine.cpp
index 7f22004e5d9..e92e0c47c3a 100644
--- a/engines/grim/imuse/dimuse_engine.cpp
+++ b/engines/grim/imuse/dimuse_engine.cpp
@@ -28,6 +28,8 @@
 #include "engines/grim/imuse/dimuse_sndmgr.h"
 #include "engines/grim/imuse/dimuse_tables.h"
 
+#include "engines/grim/movie/codecs/vima.h"
+
 #include "audio/audiostream.h"
 #include "audio/mixer.h"
 
@@ -68,9 +70,12 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 
 	_dispatchFadeSize = 0;
 
-	_initialized = 0;
-	_scriptInitializedFlag = 0;
-	_callbackInterruptFlag = 0;
+	_initialized = false;
+	_fileListInitialized = false;
+	_loadedSoundList = nullptr;
+	_openedSoundsList = nullptr;
+	_scriptInitializedFlag = false;
+	_callbackInterruptFlag = false;
 	_spooledMusicEnabled = true;
 
 	_isEngineDisabled = false;
@@ -82,14 +87,15 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 	_groupsHandler = new IMuseDigiGroupsHandler(this, mutex);
 	_fadesHandler = new IMuseDigiFadesHandler(this, mutex);
 	_triggersHandler = new IMuseDigiTriggersHandler(this, mutex);
-	_filesHandler = new IMuseDigiFilesHandler(this);
+
+	memset(_openAudioFiles, 0, sizeof(_openAudioFiles));
+	memset(_soundBuffers, 0, sizeof(_soundBuffers));
+	vimaInit(_imuseDestTable);
 
 	diMUSEInitialize();
+	soundsAllocateBuffer(DIMUSE_BUFFER_MUSIC, 528000, 44000, 352000);
+	soundsAllocateBuffer(DIMUSE_BUFFER_SPEECH, 176000, 44000, 88000);
 	diMUSEInitializeScript();
-	_filesHandler->allocSoundBuffer(DIMUSE_BUFFER_SPEECH, 176000, 44000, 88000);
-	_filesHandler->allocSoundBuffer(DIMUSE_BUFFER_MUSIC, 528000, 44000, 352000);
-
-	_filesHandler->allocSoundBuffer(DIMUSE_BUFFER_SFX, 198000, 0, 0);
 
 	if (_mixer->getOutputBufSize() != 0) {
 		// Let's find the optimal value for the maximum number of streams which can stay in the queue at once;
@@ -124,14 +130,14 @@ IMuseDigital::~IMuseDigital() {
 	g_system->getTimerManager()->removeTimerProc(timer_handler);
 	diMUSETerminateScript();
 	diMUSETerminate();
-	_filesHandler->deallocSoundBuffer(DIMUSE_BUFFER_SPEECH);
-	_filesHandler->deallocSoundBuffer(DIMUSE_BUFFER_MUSIC);
-	_filesHandler->deallocSoundBuffer(DIMUSE_BUFFER_SFX);
+
+	soundsDeallocateBuffer(DIMUSE_BUFFER_SPEECH);
+	soundsDeallocateBuffer(DIMUSE_BUFFER_MUSIC);
+
 	delete _internalMixer;
 	delete _groupsHandler;
 	delete _fadesHandler;
 	delete _triggersHandler;
-	delete _filesHandler;
 
 	// Deinit the WaveOut module
 	free(_waveOutOutputBuffer);
@@ -176,7 +182,7 @@ void IMuseDigital::diMUSEHeartbeat() {
 	if (_callbackInterruptFlag)
 		return;
 
-	_callbackInterruptFlag = 1;
+	_callbackInterruptFlag = true;
 
 	waveOutCallback();
 
@@ -252,7 +258,7 @@ void IMuseDigital::diMUSEHeartbeat() {
 		}
 	}
 
-	_callbackInterruptFlag = 0;
+	_callbackInterruptFlag = false;
 }
 
 void IMuseDigital::setPriority(int soundId, int priority) {
@@ -289,10 +295,6 @@ int IMuseDigital::getCurSpeechFrequency() const {
 	return _currentSpeechFrequency;
 }
 
-void IMuseDigital::flushTracks() {
-	_filesHandler->flushSounds();
-}
-
 // This is used in order to avoid crash everything
 // if a compressed audio resource file is found
 void IMuseDigital::disableEngine() {
@@ -358,7 +360,7 @@ void IMuseDigital::fillStreamsWhileMusicCritical(int fillTimesAfter) {
 bool IMuseDigital::isMusicStreamIdle() {
 	int32 bufSize, criticalSize, freeSpace;
 	int paused;
-	IMuseDigiSndBuffer *bufInfo = _filesHandler->getBufInfo(DIMUSE_BUFFER_MUSIC);
+	IMuseDigiSndBuffer *bufInfo = filesGetBufInfo(DIMUSE_BUFFER_MUSIC);
 
 	if (!queryNextSoundFile(bufSize, criticalSize, freeSpace, paused))
 		return true;
@@ -412,9 +414,10 @@ int IMuseDigital::diMUSEInitialize() {
 		return -1;
 	}
 
-	_callbackInterruptFlag = 0;
+	_callbackInterruptFlag = false;
 	_cmdsPauseCount = 0;
-	_initialized = 1;
+	_initialized = true;
+
 	return 49;
 }
 
@@ -453,10 +456,10 @@ int IMuseDigital::diMUSESetGroupVol(int groupId, int volume) {
 }
 
 int IMuseDigital::diMUSEStartSound(int soundId, int priority) {
-	uint8 *src = _filesHandler->getSoundAddrData(soundId);
+	uint8 *src = filesFetchMap(soundId);
 
 	if (src == nullptr) {
-		debug(5, "IMuseDigital::diMUSEStartSound(): ERROR: resource address for sound %d is NULL", soundId);
+		debug(5, "IMuseDigital::diMUSEStartSound(): ERROR: map address for sound %d is NULL", soundId);
 		return -1;
 	}
 
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/dimuse_engine.h
index 78a4fa1feec..cca2bcceea2 100644
--- a/engines/grim/imuse/dimuse_engine.h
+++ b/engines/grim/imuse/dimuse_engine.h
@@ -64,7 +64,6 @@ private:
 	IMuseDigiGroupsHandler *_groupsHandler;
 	IMuseDigiFadesHandler *_fadesHandler;
 	IMuseDigiTriggersHandler *_triggersHandler;
-	IMuseDigiFilesHandler *_filesHandler;
 
 	int _callbackFps;
 	static void timer_handler(void *refConf);
@@ -96,12 +95,12 @@ private:
 	int32 _curMusicState;
 	int32 _curMusicSeq;
 
-	int _scriptInitializedFlag;
+	bool _scriptInitializedFlag;
 	char _emptyMarker[1];
 	bool _spooledMusicEnabled;
 
 	int _usecPerInt; // Microseconds between each callback (will be set to 50 Hz)
-	int _callbackInterruptFlag;
+	bool _callbackInterruptFlag;
 	void diMUSEHeartbeat();
 
 	bool isMusicStreamIdle();
@@ -121,7 +120,7 @@ private:
 	int scriptSetAttribute(int attrIndex, int attrVal);
 
 	// CMDs
-	int _initialized;
+	bool _initialized;
 	int _cmdsPauseCount;
 	int _cmdsRunning50HzCount;
 	int _cmdsRunning5HzCount;
@@ -217,6 +216,54 @@ private:
 	int dispatchUpdateFadeMixVolume(IMuseDigiDispatch *dispatchPtr, int32 remainingFade);
 	int dispatchUpdateFadeSlope(IMuseDigiDispatch *dispatchPtr);
 
+	// Files
+	IMuseDigiSoundList _mainSoundList[DIMUSE_MAX_SOUND_LIST];
+	IMuseDigiSoundList *_loadedSoundList;
+	IMuseDigiSoundList *_openedSoundsList;
+	bool _fileListInitialized;
+	uint16 _imuseDestTable[5786];
+	IMuseDigiOpenAudioFile _openAudioFiles[DIMUSE_MAX_OPEN_FILES];
+	IMuseDigiSndBuffer _soundBuffers[4];
+
+	int diMUSEInitFilelist();
+	void diMUSESaveLoadFilelist(Common::Serializer &ser);
+	int diMUSELoadSound(const char *soundName, int requestedSoundId);
+	void diMUSEUnloadSound(int soundId);
+	void diMUSEUnloadAll();
+	int diMUSEOpenSound(const char *filename, int requestedSoundId);
+	void diMUSECloseSound(int soundId);
+	void diMUSECloseAll();
+	int diMUSEFindSound(const char *soundName);
+	void diMUSEFlushSounds();
+	int diMUSEAddSoundToList(IMuseDigiSoundList **listPtr, IMuseDigiSoundList *item);
+	int diMUSERemoveSoundFromList(IMuseDigiSoundList **listPtr, IMuseDigiSoundList *item);
+
+	bool filesCheckRange(int soundId);
+	uint8 *filesGetSoundAddrData(int soundId);
+	uint8 *filesFetchMap(int soundId);
+	int filesSeek(int soundId, int32 offset, int mode);
+	int filesRead(int soundId, uint8 *buf, int32 size);
+	IMuseDigiSndBuffer *filesGetBufInfo(int bufId);
+
+	int ihostLoadSound(const char *soundName, int requestedSoundId);
+	int ihostUnloadSound(int soundId);
+	int ihostOpenSound(const char *filename, int requestedSoundId);
+	int ihostCloseSound(int soundId);
+	uint8 *ihostGetMapAddr(int soundId);
+	uint8 *ihostGetSoundAddr(int soundId);
+	IMuseDigiSndBuffer *ihostGetBufferInfo(int bufId);
+	int ihostFseek(int soundId, int32 offset, int mode);
+	int ihostRead(int soundId, uint8 *destBuf, int32 size);
+
+	void soundsAllocateBuffer(int bufferId, int32 bufSize, int32 loadSize, int32 criticalSize);
+	void soundsDeallocateBuffer(int bufferId);
+	IMuseDigiResource *soundsOpenFile(const char *filename);
+	void soundsCloseFile(IMuseDigiResource *res);
+	void soundsFileSeek(IMuseDigiResource *res, int32 offset, int mode);
+	int32 soundsFileTell(IMuseDigiResource *res);
+	int soundsGetCompBlockId(IMuseDigiResource *res, int32 offset);
+	int32 copyDataFromResource(IMuseDigiResource *res, uint8 *dest, int32 size);
+
 	// Waveapi
 	waveOutParamsStruct waveOutSettings;
 
@@ -261,7 +308,6 @@ public:
 	int  getCurSpeechPan() const;
 	int  getCurSpeechFrequency() const;
 	void pause(bool pause);
-	void flushTracks();
 	void disableEngine();
 	bool isEngineDisabled();
 	void floodMusicBuffer();
diff --git a/engines/grim/imuse/dimuse_files.cpp b/engines/grim/imuse/dimuse_files.cpp
index 5b26ad88cc1..008b0c7a34e 100644
--- a/engines/grim/imuse/dimuse_files.cpp
+++ b/engines/grim/imuse/dimuse_files.cpp
@@ -19,297 +19,744 @@
  *
  */
 
+#include "common/stream.h"
+
+#include "engines/grim/resource.h"
+#include "engines/grim/movie/codecs/vima.h"
 #include "engines/grim/imuse/dimuse_engine.h"
-#include "engines/grim/imuse/dimuse_files.h"
 
 namespace Grim {
 
-IMuseDigiFilesHandler::IMuseDigiFilesHandler(IMuseDigital *engine) {
-	_engine = engine;
-	_sound = new ImuseDigiSndMgr();
-	assert(_sound);
-
-	for (int i = 0; i < 4; i++) {
-		IMuseDigiSndBuffer *selectedSoundBuf = &_soundBuffers[i];
-		selectedSoundBuf->buffer = nullptr;
-		selectedSoundBuf->bufSize = 0;
-		selectedSoundBuf->loadSize = 0;
-		selectedSoundBuf->criticalSize = 0;
+int IMuseDigital::diMUSEInitFilelist() {
+	for (int i = 0; i < DIMUSE_MAX_SOUND_LIST; i++) {
+		_mainSoundList[i].prev = nullptr;
+		_mainSoundList[i].next = nullptr;
+		_mainSoundList[i].soundId = 0;
 	}
-}
 
-IMuseDigiFilesHandler::~IMuseDigiFilesHandler() {
-	delete _sound;
+	_fileListInitialized = true;
+	return 0;
 }
 
-void IMuseDigiFilesHandler::saveLoad(Common::Serializer &ser) {
-	int curSound = 0;
-	ImuseDigiSndMgr::SoundDesc *sounds = _sound->getSounds();
+void IMuseDigital::diMUSESaveLoadFilelist(Common::Serializer &ser) {
+	IMuseDigiSoundList *sound;
+	int loadedCount = 0;
+	int openedCount = 0;
+	int soundId = 0;
+	int refCount = 0;
+	char filename[36] = {};
 
-	ser.syncArray(_currentSpeechFilename, 60, Common::Serializer::SByte, VER(103));
 	if (ser.isSaving()) {
-		for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
-			ser.syncAsSint32LE(sounds[l].soundId, VER(103));
+		for (sound = _loadedSoundList; sound; sound = sound->next)
+			loadedCount++;
+
+		for (sound = _openedSoundsList; sound; sound = sound->next)
+			openedCount++;
+	} else {
+		for (int i = 0; i < DIMUSE_MAX_SOUND_LIST; i++) {
+			_mainSoundList[i].prev = nullptr;
+			_mainSoundList[i].next = nullptr;
+			_mainSoundList[i].soundId = 0;
 		}
 	}
 
-	if (ser.isLoading()) {
-		// Close prior sounds if we're reloading (needed for edge cases like the recipe book in COMI)
-		for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
-			_sound->closeSound(&sounds[l]);
+	ser.syncAsSint32LE(loadedCount, VER(103));
+	ser.syncAsSint32LE(openedCount, VER(103));
+
+	sound = _loadedSoundList;
+	for (int i = 0; i < loadedCount; i++) {
+		if (ser.isSaving()) {
+			soundId = sound->soundId;
+			refCount = sound->refCount;
+			Common::strlcpy(filename, sound->filename, sizeof(filename));
+			sound = sound->next;
 		}
 
-		for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
-			ser.syncAsSint32LE(curSound, VER(103));
-			if (curSound) {
-				openSound(curSound);
-				if (curSound != kTalkSoundID)
-					closeSound(curSound);
+		ser.syncAsSint32LE(soundId, VER(103));
+		ser.syncArray(filename, sizeof(filename), Common::Serializer::SByte, VER(103));
+		ser.syncAsSint32LE(refCount, VER(103));
+
+		if (ser.isLoading()) {
+			if (!diMUSELoadSound(filename, soundId)) {
+				debug(5, "IMuseDigital::diMUSESaveLoadFilelist(): ERROR: couldn't load file %s", filename);
+				return;
+			}
+
+			if (soundId != _loadedSoundList->soundId) {
+				debug(5, "IMuseDigital::diMUSESaveLoadFilelist(): ERROR: detected modified sound number");
+				return;
 			}
+
+			_loadedSoundList->refCount = refCount;
 		}
 	}
-}
 
-uint8 *IMuseDigiFilesHandler::getSoundAddrData(int soundId) {
-	if (_engine->isEngineDisabled())
-		return nullptr;
+	sound = _openedSoundsList;
+	for (int i = 0; i < openedCount; i++) {
+		if (ser.isSaving()) {
+			soundId = sound->soundId;
+			refCount = sound->refCount;
+			Common::strlcpy(filename, sound->filename, sizeof(filename));
+			sound = sound->next;
+		}
 
-	// This function is always used for SFX (tracks which do not
-	// have a stream pointer), hence the use of the resource address
-	if (soundId != 0) {
-		// TODO
-		// _vm->_res->lock(rtSound, soundId);
-		// byte *ptr = _vm->getResourceAddress(rtSound, soundId);
-		// if (!ptr) {
-		// 	_vm->_res->unlock(rtSound, soundId);
-		// 	return nullptr;
-		// }
-		// return ptr;
-	}
-	debug(5, "IMuseDigiFilesHandler::getSoundAddrData(): soundId is 0 or out of range");
-	return nullptr;
+		ser.syncAsSint32LE(soundId, VER(103));
+		ser.syncArray(filename, sizeof(filename), Common::Serializer::SByte, VER(103));
+		ser.syncAsSint32LE(refCount, VER(103));
+
+		if (ser.isLoading()) {
+			if (!diMUSEOpenSound(filename, soundId)) {
+				debug(5, "IMuseDigital::diMUSESaveLoadFilelist(): ERROR: couldn't open file %s", filename);
+			}
+
+			if (soundId != _openedSoundsList->soundId) {
+				debug(5, "IMuseDigital::diMUSESaveLoadFilelist(): ERROR: detected modified sound number");
+				return;
+			}
+
+			_openedSoundsList->refCount = refCount;
+		}
+	}
 }
 
-int IMuseDigiFilesHandler::getSoundAddrDataSize(int soundId, bool hasStream) {
-	if (_engine->isEngineDisabled())
+int IMuseDigital::diMUSELoadSound(const char *soundName, int requestedSoundId) {
+	IMuseDigiSoundList *sound;
+	int soundId;
+	int nameIndex;
+
+	if (!_fileListInitialized || !*soundName)
 		return 0;
 
-	if (hasStream) {
-		ImuseDigiSndMgr::SoundDesc *s = _sound->findSoundById(soundId);
-		if (s) {
-			if (soundId != kTalkSoundID) {
-				return s->resSize;
-			}
+	soundId = diMUSEFindSound(soundName);
+	if (soundId && _loadedSoundList) {
+		sound = _loadedSoundList;
+		while (soundId != sound->soundId) {
+			sound = sound->next;
+
+			if (!sound)
+				break;
+		}
+
+		if (sound) {
+			sound->refCount++;
+			return soundId;
+		}
+	}
+
+	sound = _mainSoundList;
+	while (sound->soundId) {
+		if (++sound >= &_mainSoundList[DIMUSE_MAX_SOUND_LIST]) {
+			debug(5, "IMuseDigital::diMUSELoadSound(): Sound List FULL!");
+			return 0;
 		}
+	}
+
+	soundId = ihostLoadSound(soundName, requestedSoundId);
+	if (soundId) {
+		for (nameIndex = 0; nameIndex < 32; ) {
+			sound->filename[nameIndex] = soundName[nameIndex];
+			if (!soundName[++nameIndex])
+				break;
+		}
+
+		if (!soundName[nameIndex]) {
+			sound->filename[nameIndex] = 0;
+			sound->soundId = soundId;
+			sound->refCount = 1;
+			diMUSEAddSoundToList(&_loadedSoundList, sound);
+			return soundId;
+		}
+
+		debug(5, "IMuseDigital::diMUSELoadSound(): Name too long: %s", soundName);
 	} else {
-		// TODO
-		// return _vm->getResourceSize(rtSound, soundId);
+		debug(5, "IMuseDigital::diMUSELoadSound(): Host couldn't load sound %s", soundName);
 	}
 
 	return 0;
 }
 
-int IMuseDigiFilesHandler::getNextSound(int soundId) {
-	int foundSoundId = 0;
-	do {
-		foundSoundId = _engine->diMUSEGetNextSound(foundSoundId);
-		if (!foundSoundId)
-			return -1;
-	} while (foundSoundId != soundId);
-	return 2;
+void IMuseDigital::diMUSEUnloadSound(int soundId) {
+	IMuseDigiSoundList *sound;
+
+	if (_fileListInitialized) {
+		sound = _loadedSoundList;
+		while (sound) {
+			if (sound->soundId == soundId) {
+				if (sound->refCount)
+					sound->refCount--;
+
+				break;
+			}
+
+			sound = sound->next;
+		}
+
+		diMUSEFlushSounds();
+	}
 }
 
-int IMuseDigiFilesHandler::seek(int soundId, int32 offset, int mode, int bufId) {
-	// This function and files_read() are used for sounds for which a stream is needed (speech
-	// and music), therefore they will always refer to sounds in a bundle file for DIG and COMI
-	// The seek'd position is in reference to the decompressed sound
+void IMuseDigital::diMUSEUnloadAll() {
+	IMuseDigiSoundList *sound;
 
-	if (_engine->isEngineDisabled())
+	if (_fileListInitialized) {
+		for (sound = _loadedSoundList; sound; sound = sound->next)
+			sound->refCount = 0;
+
+		diMUSEFlushSounds();
+	}
+}
+
+int IMuseDigital::diMUSEOpenSound(const char *filename, int requestedSoundId) {
+	IMuseDigiSoundList *sound;
+	int soundId;
+	int nameIndex;
+
+	if (!_fileListInitialized || !*filename)
 		return 0;
 
-	char fileName[60] = "";
-	getFilenameFromSoundId(soundId, fileName, sizeof(fileName));
+	soundId = diMUSEFindSound(filename);
+	if (soundId && _openedSoundsList) {
+		sound = _openedSoundsList;
+		while (soundId != sound->soundId) {
+			sound = sound->next;
+			if (!sound)
+				break;
+		}
 
-	ImuseDigiSndMgr::SoundDesc *s = _sound->findSoundById(soundId);
-	if (s) {
-		if (soundId != 0) {
-			return s->bundle->seekFile(offset, mode);
-		} else {
-			debug(5, "IMuseDigiFilesHandler::seek(): soundId is 0 or out of range");
+		if (sound) {
+			sound->refCount++;
+			return soundId;
+		}
+	}
+
+	sound = _mainSoundList;
+	while (sound->soundId) {
+		if (++sound >= &_mainSoundList[DIMUSE_MAX_SOUND_LIST]) {
+			debug(5, "IMuseDigital::diMUSEOpenSound(): Sound List FULL!");
+			return 0;
 		}
+	}
+
+	soundId = ihostOpenSound(filename, requestedSoundId);
+	if (soundId) {
+		for (nameIndex = 0; nameIndex < 32; ) {
+			sound->filename[nameIndex] = filename[nameIndex];
+
+			if (!filename[++nameIndex])
+				break;
+		}
+
+		if (!filename[nameIndex]) {
+			sound->filename[nameIndex] = 0;
+			sound->soundId = soundId;
+			sound->refCount = 1;
+			diMUSEAddSoundToList(&_openedSoundsList, sound);
+			return soundId;
+		}
+
+		debug(5, "IMuseDigital::diMUSEOpenSound(): Name too long: %s", filename);
 	} else {
-		debug(5, "IMuseDigiFilesHandler::seek(): can't find sound %d (%s); did you forget to open it?", soundId, fileName);
+		debug(5, "IMuseDigital::diMUSEOpenSound(): Host couldn't open sound %s", filename);
 	}
 
 	return 0;
 }
 
-int IMuseDigiFilesHandler::read(int soundId, uint8 *buf, int32 size, int bufId) {
-	// This function and files_seek() are used for sounds for which a stream is needed (speech
-	// and music), therefore they will always refer to sounds in a bundle file for DIG and COMI
+void IMuseDigital::diMUSECloseSound(int soundId) {
+	IMuseDigiSoundList *sound;
 
-	if (_engine->isEngineDisabled())
-		return 0;
+	if (_fileListInitialized) {
+		sound = _openedSoundsList;
+		while (sound) {
+			if (sound->soundId == soundId) {
+				if (sound->refCount)
+					sound->refCount--;
+				break;
+			}
+			sound = sound->next;
+		}
 
-	if (soundId != 0) {
-		uint8 *tmpBuf = nullptr;
-		int32 resultingSize;
+		diMUSEFlushSounds();
+	}
+}
 
-		char fileName[60] = "";
-		getFilenameFromSoundId(soundId, fileName, sizeof(fileName));
+void IMuseDigital::diMUSECloseAll() {
+	IMuseDigiSoundList *sound;
 
-		ImuseDigiSndMgr::SoundDesc *s = _sound->getSounds();
-		ImuseDigiSndMgr::SoundDesc *curSnd = nullptr;
-		for (int i = 0; i < MAX_IMUSE_SOUNDS; i++) {
-			curSnd = &s[i];
-			if (curSnd->inUse) {
-				if (curSnd->soundId == soundId) {
-					resultingSize = curSnd->bundle->readFile(fileName, size, &tmpBuf, true);
+	if (_fileListInitialized) {
+		for (sound = _openedSoundsList; sound; sound = sound->next)
+			sound->refCount = 0;
 
-					if (resultingSize != size)
-						debug(5, "IMuseDigiFilesHandler::read(): WARNING: tried to read %d bytes, got %d instead (soundId %d (%s))", size, resultingSize, soundId, fileName);
+		diMUSEFlushSounds();
+	}
+}
 
-					memcpy(buf, tmpBuf, resultingSize);
-					free(tmpBuf);
-					return resultingSize;
-				}
-			}
+int IMuseDigital::diMUSEFindSound(const char *soundName) {
+	IMuseDigiSoundList *sound;
+
+	for (sound = _loadedSoundList; sound; sound = sound->next) {
+		if (*soundName && !strcmp(sound->filename, soundName))
+			return sound->soundId;
+	}
+
+	for (sound = _openedSoundsList; sound; sound = sound->next) {
+		if (*soundName && !strcmp(sound->filename, soundName))
+			return sound->soundId;
+	}
+
+	return 0;
+}
+
+void IMuseDigital::diMUSEFlushSounds() {
+	IMuseDigiSoundList *sound, *next;
+
+	for (sound = _loadedSoundList; sound; sound = next) {
+		next = sound->next;
+		if (!sound->refCount && !diMUSEGetParam(sound->soundId, DIMUSE_P_SND_TRACK_NUM) && !diMUSEGetParam(sound->soundId, DIMUSE_P_TRIGS_SNDS)) {
+			ihostUnloadSound(sound->soundId);
+			sound->soundId = 0;
+			diMUSERemoveSoundFromList(&_loadedSoundList, sound);
 		}
+	}
 
-		debug(5, "IMuseDigiFilesHandler::read(): can't find sound %d (%s); did you forget to open it?", soundId, fileName);
+	for (sound = _openedSoundsList; sound; sound = next) {
+		next = sound->next;
+		if (!sound->refCount && !diMUSEGetParam(sound->soundId, DIMUSE_P_SND_TRACK_NUM) && !diMUSEGetParam(sound->soundId, DIMUSE_P_TRIGS_SNDS)) {
+			ihostCloseSound(sound->soundId);
+			sound->soundId = 0;
+			diMUSERemoveSoundFromList(&_openedSoundsList, sound);
+		}
+	}
+}
 
-	} else {
-		debug(5, "IMuseDigiFilesHandler::read(): soundId is 0 or out of range");
+int IMuseDigital::diMUSEAddSoundToList(IMuseDigiSoundList **listPtr, IMuseDigiSoundList *item) {
+	if (!item || item->prev || item->next) {
+		debug(5, "IMuseDigital::diMUSEAddSoundToList(): ERROR: list arg err when adding");
+		return -5;
 	}
 
+	item->next = *listPtr;
+
+	if (*listPtr)
+		(*listPtr)->prev = item;
+
+	item->prev = nullptr;
+	*listPtr = item;
+
 	return 0;
 }
 
-IMuseDigiSndBuffer *IMuseDigiFilesHandler::getBufInfo(int bufId) {
-	if (bufId > 0 && bufId <= 4) {
-		return &_soundBuffers[bufId];
+int IMuseDigital::diMUSERemoveSoundFromList(IMuseDigiSoundList **listPtr, IMuseDigiSoundList *item) {
+	IMuseDigiSoundList *curItem = *listPtr;
+
+	if (item && curItem) {
+		while (curItem) {
+			if (curItem == item)
+				break;
+			curItem = curItem->next;
+		}
+
+		if (curItem) {
+			if (item->next)
+				item->next->prev = item->prev;
+
+			if (item->prev)
+				item->prev->next = item->next;
+			else
+				*listPtr = item->next;
+
+			item->next = nullptr;
+			item->prev = nullptr;
+
+			return 0;
+		} else {
+			debug(5, "IMuseDigital::diMUSERemoveSoundFromList(): ERROR: item not on list");
+			return -3;
+		}
+	} else {
+		debug(5, "IMuseDigital::diMUSERemoveSoundFromList(): ERROR: list arg err when removing");
+		return -5;
 	}
+}
+
+bool IMuseDigital::filesCheckRange(int soundId) {
+	return soundId && (uint32)soundId < 0xFFFFFFF0;
+}
+
+uint8 *IMuseDigital::filesGetSoundAddrData(int soundId) {
+	if (filesCheckRange(soundId))
+		return ihostGetSoundAddr(soundId);
 
-	debug(5, "IMuseDigiFilesHandler::getBufInfo(): ERROR: invalid buffer id");
 	return nullptr;
 }
 
-int IMuseDigiFilesHandler::openSound(int soundId) {
-	if (_engine->isEngineDisabled())
-		return 1;
+uint8 *IMuseDigital::filesFetchMap(int soundId) {
+	if (filesCheckRange(soundId))
+		return ihostGetMapAddr(soundId);
 
-	ImuseDigiSndMgr::SoundDesc *s = nullptr;
-	char fileName[60] = "";
-	getFilenameFromSoundId(soundId, fileName, sizeof(fileName));
-
-	int groupId = soundId == kTalkSoundID ? IMUSE_VOLGRP_VOICE : IMUSE_VOLGRP_MUSIC;
-	s = _sound->findSoundById(soundId);
-	if (!s)
-		s = _sound->openSound(soundId, fileName, IMUSE_BUNDLE, groupId, -1);
-	if (!s)
-		s = _sound->openSound(soundId, fileName, IMUSE_BUNDLE, groupId, 1);
-	if (!s)
-		s = _sound->openSound(soundId, fileName, IMUSE_BUNDLE, groupId, 2);
-	if (!s) {
-		debug(5, "IMuseDigiFilesHandler::openSound(): can't open sound %d (%s)", soundId, fileName);
-		return 1;
-	}
+	return nullptr;
+}
+
+int IMuseDigital::filesSeek(int soundId, int32 offset, int mode) {
+	if (filesCheckRange(soundId))
+		return ihostFseek(soundId, offset, mode);
 
 	return 0;
 }
 
-void IMuseDigiFilesHandler::closeSound(int soundId) {
-	if (_engine->isEngineDisabled())
-		return;
+int IMuseDigital::filesRead(int soundId, uint8 *buf, int32 size) {
+	if (filesCheckRange(soundId))
+		return ihostRead(soundId, buf, size);
+
+	return 0;
+}
+
+IMuseDigiSndBuffer *IMuseDigital::filesGetBufInfo(int bufId) {
+	if (bufId)
+		return ihostGetBufferInfo(bufId);
+
+	return nullptr;
+}
+
+int IMuseDigital::ihostLoadSound(const char *soundName, int requestedSoundId) {
+	return 0;
+}
 
-	_sound->scheduleSoundForDeallocation(soundId);
+int IMuseDigital::ihostUnloadSound(int soundId) {
+	return 0;
 }
 
-void IMuseDigiFilesHandler::closeAllSounds() {
-	ImuseDigiSndMgr::SoundDesc *s = _sound->getSounds();
-	for (int i = 0; i < MAX_IMUSE_SOUNDS; i++) {
-		if (s[i].inUse) {
-			closeSound(s[i].soundId);
+int IMuseDigital::ihostOpenSound(const char *filename, int requestedSoundId) {
+	Common::StackLock lock(*_mutex);
+	IMuseDigiResource *res;
+	int index;
+
+	if (requestedSoundId) {
+		index = requestedSoundId - 10000;
+		_openAudioFiles[index].resourcePtr = soundsOpenFile(filename);
+		Common::strlcpy(_openAudioFiles[index].soundName, filename, sizeof(_openAudioFiles[index].soundName));
+		_openAudioFiles[index].refCount = 1;
+		return requestedSoundId;
+	}
+
+	for (index = 1; index < DIMUSE_MAX_OPEN_FILES; index++) {
+		if (!_openAudioFiles[index].resourcePtr)
+			break;
+
+		if (_openAudioFiles[index].soundName[0] && !strcmp(_openAudioFiles[index].soundName, filename)) {
+			_openAudioFiles[index].refCount++;
+			return index + 10000;
 		}
 	}
 
-	_engine->flushTracks();
+	if (index >= DIMUSE_MAX_OPEN_FILES)
+		return 0;
+
+	res = soundsOpenFile(filename);
+	_openAudioFiles[index].resourcePtr = res;
+	if (res) {
+		Common::strlcpy(_openAudioFiles[index].soundName, filename, sizeof(_openAudioFiles[index].soundName));
+		_openAudioFiles[index].refCount = 1;
+		return index + 10000;
+	}
+
+	return 0;
 }
 
-void IMuseDigiFilesHandler::getFilenameFromSoundId(int soundId, char *fileName, size_t size) {
-	int i = 0;
+int IMuseDigital::ihostCloseSound(int soundId) {
+	Common::StackLock lock(*_mutex);
+	int index = soundId - 10000;
+
+	if (!_openAudioFiles[index].resourcePtr)
+		return 1;
 
-	if (soundId == kTalkSoundID) {
-		Common::strlcpy(fileName, _currentSpeechFilename, size);
-		return;
+	if (_openAudioFiles[index].refCount > 1) {
+		_openAudioFiles[index].refCount--;
+		return 0;
 	}
 
+	soundsCloseFile(_openAudioFiles[index].resourcePtr);
+	_openAudioFiles[index].resourcePtr = nullptr;
+	_openAudioFiles[index].soundName[0] = 0;
+	_openAudioFiles[index].refCount = 0;
+	return 0;
+}
+
+uint8 *IMuseDigital::ihostGetMapAddr(int soundId) {
 	// TODO
-	if (soundId < 2000) {
-		for (i = 0; i < ARRAYSIZE(_grimStateMusicTable); i++) {
-			if (_grimStateMusicTable[i].soundId == soundId) {
-				Common::strlcpy(fileName, _grimStateMusicTable[i].name, size);
-				Common::strlcat(fileName, ".IMC", size);
-				return;
-			}
-		}
-	} else {
-		for (i = 0; i < ARRAYSIZE(_grimSeqMusicTable); i++) {
-			if (_grimSeqMusicTable[i].soundId == soundId) {
-				Common::strlcpy(fileName, _grimSeqMusicTable[i].name, size);
-				Common::strlcat(fileName, ".IMC", size);
-				return;
-			}
+	return nullptr;
+}
+
+uint8 *IMuseDigital::ihostGetSoundAddr(int soundId) {
+	// TODO
+	return nullptr;
+}
+
+IMuseDigiSndBuffer *IMuseDigital::ihostGetBufferInfo(int bufId) {
+	return &_soundBuffers[bufId];
+}
+
+int IMuseDigital::ihostFseek(int soundId, int32 offset, int mode) {
+	Common::StackLock lock(*_mutex);
+
+	if (soundId >= 10000 && soundId < 10000 + DIMUSE_MAX_OPEN_FILES) {
+		IMuseDigiResource *res = _openAudioFiles[soundId - 10000].resourcePtr;
+		if (res) {
+			soundsFileSeek(res, offset, mode);
+			return soundsFileTell(res);
 		}
 	}
+
+	return 0;
+}
+
+int IMuseDigital::ihostRead(int soundId, uint8 *destBuf, int32 size) {
+	Common::StackLock lock(*_mutex);
+
+	IMuseDigiResource *res = _openAudioFiles[soundId - 10000].resourcePtr;
+	if (!res)
+		return 0;
+
+	// TODO
+	// Voice effects processing (hmiFX) for sound 10000
+
+	return copyDataFromResource(res, destBuf, size);
 }
 
-void IMuseDigiFilesHandler::allocSoundBuffer(int bufId, int32 size, int32 loadSize, int32 criticalSize) {
-	IMuseDigiSndBuffer *selectedSoundBuf;
+void IMuseDigital::soundsAllocateBuffer(int bufferId, int32 bufSize, int32 loadSize, int32 criticalSize) {
+	IMuseDigiSndBuffer *soundBuf = &_soundBuffers[bufferId];
 
-	selectedSoundBuf = &_soundBuffers[bufId];
-	selectedSoundBuf->buffer = (uint8 *)malloc(size);
-	selectedSoundBuf->bufSize = size;
-	selectedSoundBuf->loadSize = loadSize;
-	selectedSoundBuf->criticalSize = criticalSize;
+	soundBuf->buffer = (uint8 *)malloc(bufSize);
+	soundBuf->bufSize = bufSize;
+	soundBuf->loadSize = loadSize;
+	soundBuf->criticalSize = criticalSize;
 }
 
-void IMuseDigiFilesHandler::deallocSoundBuffer(int bufId) {
-	IMuseDigiSndBuffer *selectedSoundBuf;
+void IMuseDigital::soundsDeallocateBuffer(int bufferId) {
+	IMuseDigiSndBuffer *soundBuf = &_soundBuffers[bufferId];
 
-	selectedSoundBuf = &_soundBuffers[bufId];
-	free(selectedSoundBuf->buffer);
-	selectedSoundBuf->buffer = nullptr;
+	free(soundBuf->buffer);
+	soundBuf->buffer = nullptr;
 }
 
-void IMuseDigiFilesHandler::flushSounds() {
-	if (_engine->isEngineDisabled())
-		return;
+IMuseDigiResource *IMuseDigital::soundsOpenFile(const char *filename) {
+	Common::String lowerName(filename);
+	lowerName.toLowercase();
+
+	Common::SeekableReadStream *stream = g_resourceloader->openNewStreamFile(lowerName.c_str());
+	if (!stream)
+		return nullptr;
+
+	IMuseDigiResource *res = new IMuseDigiResource();
+	memset(res, 0, sizeof(IMuseDigiResource));
+	res->resId = stream;
+	res->curProcessedCompBlock = -1;
+	Common::strlcpy(res->filename, filename, sizeof(res->filename));
+
+	if (stream->readUint32BE() != MKTAG('M', 'C', 'M', 'P')) {
+		stream->seek(0, SEEK_SET);
+		res->hasMcmp = false;
+		res->resSize = stream->size();
+		return res;
+	}
+
+	res->hasMcmp = true;
+
+	int numCompBlocks = stream->readUint16BE();
+	res->compBlocksNum = numCompBlocks;
+
+	stream->seek(9 * numCompBlocks + 6, SEEK_SET);
+	int codecNamesSize = stream->readUint16BE();
+
+	uint8 *mcmpBlock = (uint8 *)malloc(9 * numCompBlocks);
+	res->mcmpBlockPtr = (uint8 *)malloc(codecNamesSize + 1);
+	res->compBlockPtr = new uint8 *[numCompBlocks + 1];
+	res->decompBlockSize = new int32[numCompBlocks + 1];
+	res->compBlockOffset = new int32[numCompBlocks + 1];
+	res->compBlockSize = new int32[numCompBlocks + 1];
+	res->vimaOffsets = new int32[numCompBlocks + 1];
+
+	stream->read(res->mcmpBlockPtr, codecNamesSize);
+	res->mcmpBlockPtr[codecNamesSize] = 0;
 
-	ImuseDigiSndMgr::SoundDesc *s = _sound->getSounds();
-	for (int i = 0; i < MAX_IMUSE_SOUNDS; i++) {
-		ImuseDigiSndMgr::SoundDesc *curSnd = &s[i];
-		if (curSnd && curSnd->inUse) {
-			if (curSnd->scheduledForDealloc)
-				if (!_engine->diMUSEGetParam(curSnd->soundId, DIMUSE_P_SND_TRACK_NUM) && !_engine->diMUSEGetParam(curSnd->soundId, DIMUSE_P_TRIGS_SNDS))
-					_sound->closeSound(curSnd);
+	stream->seek(6, SEEK_SET);
+	stream->read(mcmpBlock, 9 * numCompBlocks);
+
+	int32 cumulativeSize = 0;
+	int32 vimaOffset = 9 * numCompBlocks + codecNamesSize + 8;
+	uint8 *mcmpBlockPtr = mcmpBlock;
+
+	for (int i = 0; i < numCompBlocks; i++) {
+		uint8 *codecName = res->mcmpBlockPtr;
+		int codec = *mcmpBlockPtr;
+
+		for (int j = 0; j < codec; j++) {
+			if (*codecName++)
+				codecName += strlen((const char *)codecName) + 1;
 		}
+
+		res->compBlockPtr[i] = codecName;
+		res->decompBlockSize[i] = READ_BE_UINT32(mcmpBlockPtr + 1);
+		res->compBlockOffset[i] = cumulativeSize;
+		cumulativeSize += res->decompBlockSize[i];
+		res->compBlockSize[i] = READ_BE_UINT32(mcmpBlockPtr + 5);
+		res->vimaOffsets[i] = vimaOffset;
+		vimaOffset += res->compBlockSize[i];
+		mcmpBlockPtr += 9;
 	}
+
+	res->compBlockOffset[numCompBlocks] = cumulativeSize;
+	res->resSize = cumulativeSize;
+	res->vimaOffsets[numCompBlocks] = vimaOffset;
+
+	free(mcmpBlock);
+
+	res->curDecompBlockSize = 0;
+	res->decompDataBuffer = nullptr;
+	res->curProcessedCompBlock = -1;
+	return res;
 }
 
-int IMuseDigiFilesHandler::setCurrentSpeechFilename(const char *fileName) {
-	Common::strlcpy(_currentSpeechFilename, fileName, sizeof(_currentSpeechFilename));
-	if (openSound(kTalkSoundID))
-		return 1;
+void IMuseDigital::soundsCloseFile(IMuseDigiResource *res) {
+	if (res->hasMcmp) {
+		free(res->mcmpBlockPtr);
+		delete[] res->compBlockPtr;
+		delete[] res->decompBlockSize;
+		delete[] res->compBlockOffset;
+		delete[] res->compBlockSize;
+		delete[] res->vimaOffsets;
+		free(res->decompDataBuffer);
+	}
 
-	return 0;
+	delete res->resId;
+	delete res;
+}
+
+void IMuseDigital::soundsFileSeek(IMuseDigiResource *res, int32 offset, int mode) {
+	if (!res->hasMcmp) {
+		res->resId->seek(offset, mode);
+	} else if (mode == SEEK_SET) {
+		res->fileCurOffset = offset;
+	} else if (mode == SEEK_CUR) {
+		res->fileCurOffset += offset;
+	} else if (mode == SEEK_END) {
+		res->fileCurOffset = offset + res->resSize;
+	}
 }
 
-void IMuseDigiFilesHandler::closeSoundImmediatelyById(int soundId) {
-	if (_engine->isEngineDisabled())
-		return;
+int32 IMuseDigital::soundsFileTell(IMuseDigiResource *res) {
+	if (!res->hasMcmp)
+		return res->resId->pos();
+
+	return res->fileCurOffset;
+}
+
+int IMuseDigital::soundsGetCompBlockId(IMuseDigiResource *res, int32 offset) {
+	if ((uint32)offset < (uint32)res->resSize) {
+		for (int i = 0; i < res->compBlocksNum; i++) {
+			if ((uint32)offset >= (uint32)res->compBlockOffset[i] && (uint32)offset < (uint32)res->compBlockOffset[i + 1])
+				return i;
+		}
+	}
+
+	return -1;
+}
+
+int32 IMuseDigital::copyDataFromResource(IMuseDigiResource *res, uint8 *dest, int32 size) {
+	uint8 *cmpDataTmpBuf = nullptr;
+	uint32 curCompBlockSize = 0;
+	uint8 *curDest = dest;
+	int32 resSize, blockOffset, copySize;
+	int curBlockIndex, firstBlockIndex, lastBlockIndex, compBlocksMinus1;
+
+	if (!res->hasMcmp)
+		return res->resId->read(dest, size);
+
+	resSize = size;
+	curBlockIndex = soundsGetCompBlockId(res, res->fileCurOffset);
+	firstBlockIndex = curBlockIndex;
+	lastBlockIndex = soundsGetCompBlockId(res, size + res->fileCurOffset - 1);
+	compBlocksMinus1 = lastBlockIndex;
+
+	if (curBlockIndex < 0)
+		return 0;
+
+	if (lastBlockIndex < 0) {
+		compBlocksMinus1 = res->compBlocksNum - 1;
+		size = res->resSize - res->fileCurOffset;
+		resSize = size;
+		lastBlockIndex = compBlocksMinus1;
+	}
+
+	if (resSize) {
+		if (curBlockIndex <= lastBlockIndex) {
+			while (1) {
+				if (!res->decompDataBuffer || curBlockIndex != res->curProcessedCompBlock) {
+					uint32 compBlockSize = res->compBlockSize[curBlockIndex];
+					if (curCompBlockSize < compBlockSize) {
+						cmpDataTmpBuf = (uint8 *)realloc(cmpDataTmpBuf, compBlockSize + 2);
+						curCompBlockSize = compBlockSize;
+					}
+
+					res->resId->seek(res->vimaOffsets[curBlockIndex], SEEK_SET);
+					res->resId->read(cmpDataTmpBuf, compBlockSize);
+
+					// Two more zero bytes at the end of the input buffer
+					cmpDataTmpBuf[compBlockSize] = 0;
+					cmpDataTmpBuf[compBlockSize + 1] = 0;
+
+					int32 decompBlockSize = res->decompBlockSize[curBlockIndex];
+					if (res->curDecompBlockSize < decompBlockSize) {
+						res->decompDataBuffer = (uint8 *)realloc(res->decompDataBuffer, decompBlockSize);
+						res->curDecompBlockSize = decompBlockSize;
+					}
+
+					if (!memcmp(res->compBlockPtr[curBlockIndex], "VIMA", 4)) {
+						decompressVima(cmpDataTmpBuf, (int16 *)res->decompDataBuffer, decompBlockSize, _imuseDestTable, false);
+					} else {
+						copySize = compBlockSize;
+						if (decompBlockSize < copySize)
+							copySize = decompBlockSize;
+
+						memcpy(res->decompDataBuffer, cmpDataTmpBuf, copySize);
+					}
+
+					resSize = size;
+					lastBlockIndex = compBlocksMinus1;
+					res->curProcessedCompBlock = curBlockIndex;
+				}
+
+				if (firstBlockIndex == lastBlockIndex) {
+					copySize = resSize;
+					blockOffset = res->fileCurOffset - res->compBlockOffset[curBlockIndex];
+				} else if (curBlockIndex == firstBlockIndex) {
+					blockOffset = res->fileCurOffset - res->compBlockOffset[curBlockIndex];
+					copySize = res->decompBlockSize[curBlockIndex] - blockOffset;
+				} else {
+					blockOffset = 0;
+					if (curBlockIndex == lastBlockIndex)
+						copySize = res->fileCurOffset + resSize - res->compBlockOffset[curBlockIndex];
+					else
+						copySize = res->decompBlockSize[curBlockIndex];
+				}
+
+				memcpy(curDest, &res->decompDataBuffer[blockOffset], copySize);
+				curBlockIndex++;
+				resSize = size;
+				curDest += copySize;
+
+				if (curBlockIndex > compBlocksMinus1)
+					break;
+
+				lastBlockIndex = compBlocksMinus1;
+			}
+		}
+
+		free(cmpDataTmpBuf);
+		res->fileCurOffset += resSize;
+	}
 
-	_sound->closeSoundById(soundId);
+	return resSize;
 }
 
 } // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_files.h b/engines/grim/imuse/dimuse_files.h
index b6bbf73efcc..db7b572c748 100644
--- a/engines/grim/imuse/dimuse_files.h
+++ b/engines/grim/imuse/dimuse_files.h
@@ -22,44 +22,4 @@
 #ifndef GRIM_IMUSE_FILES_H
 #define GRIM_IMUSE_FILES_H
 
-#include "common/scummsys.h"
-#include "common/textconsole.h"
-#include "common/util.h"
-#include "engines/grim/imuse/dimuse_bndmgr.h"
-#include "engines/grim/imuse/dimuse_sndmgr.h"
-
-namespace Grim {
-
-class IMuseDigiFilesHandler {
-
-private:
-	IMuseDigital *_engine;
-	ImuseDigiSndMgr *_sound;
-	Common::Mutex _mutex;
-	IMuseDigiSndBuffer _soundBuffers[4];
-	char _currentSpeechFilename[60] = {};
-
-	void getFilenameFromSoundId(int soundId, char *fileName, size_t size);
-public:
-	IMuseDigiFilesHandler(IMuseDigital *engine);
-	~IMuseDigiFilesHandler();
-
-	uint8 *getSoundAddrData(int soundId);
-	int getSoundAddrDataSize(int soundId, bool hasStream);
-	int getNextSound(int soundId);
-	int seek(int soundId, int32 offset, int mode, int bufId);
-	int read(int soundId, uint8 *buf, int32 size, int bufId);
-	IMuseDigiSndBuffer *getBufInfo(int bufId);
-	int openSound(int soundId);
-	void closeSound(int soundId);
-	void closeAllSounds();
-	void allocSoundBuffer(int bufId, int32 size, int32 loadSize, int32 criticalSize);
-	void deallocSoundBuffer(int bufId);
-	void flushSounds();
-	int setCurrentSpeechFilename(const char *fileName);
-	void closeSoundImmediatelyById(int soundId);
-	void saveLoad(Common::Serializer &ser);
-};
-
-} // End of namespace Grim
 #endif
diff --git a/engines/grim/imuse/dimuse_scripts.cpp b/engines/grim/imuse/dimuse_scripts.cpp
index bc0b9e99842..da38ef11769 100644
--- a/engines/grim/imuse/dimuse_scripts.cpp
+++ b/engines/grim/imuse/dimuse_scripts.cpp
@@ -35,11 +35,11 @@ int IMuseDigital::scriptParse(int cmd, int a, int b) {
 				debug(5, "IMuseDigital::scriptParse(): script module already initialized");
 				return -1;
 			} else {
-				_scriptInitializedFlag = 1;
+				_scriptInitializedFlag = true;
 				return scriptInit();
 			}
 		case DIMUSE_C_SCRIPT_TERMINATE:
-			_scriptInitializedFlag = 0;
+			_scriptInitializedFlag = false;
 			return scriptTerminate();
 		case DIMUSE_C_SCRIPT_SAVE:
 		case DIMUSE_C_SCRIPT_RESTORE:
@@ -71,6 +71,8 @@ int IMuseDigital::scriptParse(int cmd, int a, int b) {
 }
 
 int IMuseDigital::scriptInit() {
+	diMUSEInitFilelist();
+
 	_curMusicState = 0;
 	_curMusicSeq = 0;
 	_nextSeqToPlay = 0;
@@ -109,7 +111,7 @@ void IMuseDigital::scriptRefresh() {
 			scriptSetSequence(0);
 	}
 
-	flushTracks();
+	diMUSEFlushSounds();
 }
 
 void IMuseDigital::scriptSetState(int stateId) {
@@ -219,19 +221,22 @@ int IMuseDigital::scriptSetAttribute(int attrIndex, int attrVal) {
 }
 
 void IMuseDigital::scriptSaveLoad(Common::Serializer &ser) {
-	if (ser.isLoading())
-		_filesHandler->closeAllSounds();
+	if (ser.isLoading()) {
+		diMUSEUnloadAll();
+		diMUSECloseAll();
+	}
 
 	ser.syncAsSint32LE(_curMusicState, VER(103));
 	ser.syncAsSint32LE(_curMusicSeq, VER(103));
 	ser.syncAsSint32LE(_nextSeqToPlay, VER(103));
 	ser.syncArray(_attributes, ARRAYSIZE(_attributes), Common::Serializer::Sint32LE, VER(103));
-	_filesHandler->saveLoad(ser);
+	diMUSESaveLoadFilelist(ser);
 }
 
 void IMuseDigital::scriptDeinit() {
 	diMUSEStopAllSounds();
-	_filesHandler->closeAllSounds();
+	diMUSEUnloadAll();
+	diMUSECloseAll();
 }
 
 int IMuseDigital::scriptTriggerCallback(char *marker) {
@@ -247,6 +252,7 @@ void IMuseDigital::scriptPlayMusic(const IMuseDigiStateTable *tableEntry, int cu
 	int hookId = 0;
 	int attribPos, oldSoundId, newSoundId, soundId;
 	int fadeTime, fadeDelay, fadeLength;
+	char fileName[64];
 
 	Common::StackLock lock(*_mutex);
 
@@ -311,11 +317,15 @@ void IMuseDigital::scriptPlayMusic(const IMuseDigiStateTable *tableEntry, int cu
 	case 11:
 	case 12:
 		// TODO
-		// newSoundId = diMUSEOpenSound(fileName, 0);
-		newSoundId = _filesHandler->openSound(tableEntry->soundId) ? 0 : tableEntry->soundId;
+		// The original remaps the name through a table which always appends ".IMC"
+		Common::strlcpy(fileName, tableEntry->name, sizeof(fileName));
+		Common::strlcat(fileName, ".IMC", sizeof(fileName));
+
+		debug(5, "IMuseDigital::scriptPlayMusic(): opening %s", fileName);
+		newSoundId = diMUSEOpenSound(fileName, 0);
 
 		if (!newSoundId) {
-			debug(5, "IMuseDigital::scriptPlayMusic(): unable to open sound %d", tableEntry->soundId);
+			debug(5, "IMuseDigital::scriptPlayMusic(): unable to open %s", fileName);
 			if (oldSoundId)
 				diMUSEFadeParam(oldSoundId, DIMUSE_P_VOLUME, 0, 60);
 			return;
@@ -391,7 +401,7 @@ void IMuseDigital::scriptPlayMusic(const IMuseDigiStateTable *tableEntry, int cu
 			diMUSEProcessStreams();
 		}
 
-		_filesHandler->closeSound(newSoundId);
+		diMUSECloseSound(newSoundId);
 		diMUSESetParam(newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
 		break;
 	case 5:
diff --git a/engines/grim/imuse/dimuse_streamer.cpp b/engines/grim/imuse/dimuse_streamer.cpp
index ea7f6963ca9..f56d7007738 100644
--- a/engines/grim/imuse/dimuse_streamer.cpp
+++ b/engines/grim/imuse/dimuse_streamer.cpp
@@ -32,7 +32,7 @@ int IMuseDigital::streamerInit() {
 }
 
 IMuseDigiStream *IMuseDigital::streamerAllocateSound(int soundId, int bufId, int32 maxRead) {
-	IMuseDigiSndBuffer *bufInfoPtr = _filesHandler->getBufInfo(bufId);
+	IMuseDigiSndBuffer *bufInfoPtr = filesGetBufInfo(bufId);
 	if (!bufInfoPtr) {
 		debug(5, "IMuseDigital::streamerAlloc(): ERROR: couldn't get buffer info");
 		return nullptr;
@@ -52,7 +52,7 @@ IMuseDigiStream *IMuseDigital::streamerAllocateSound(int soundId, int bufId, int
 
 	for (int l = 0; l < DIMUSE_MAX_STREAMS; l++) {
 		if (!_streams[l].soundId) {
-			_streams[l].endOffset = _filesHandler->seek(soundId, 0, SEEK_END, bufId);
+			_streams[l].endOffset = filesSeek(soundId, 0, SEEK_END);
 			_streams[l].curOffset = 0;
 			_streams[l].soundId = soundId;
 			_streams[l].bufId = bufId;
@@ -264,7 +264,7 @@ int IMuseDigital::streamerFeedStream(IMuseDigiStream *streamPtr, uint8 *srcBuf,
 
 int IMuseDigital::streamerFetchData(IMuseDigiStream *streamPtr) {
 	if (streamPtr->endOffset == 0) {
-		streamPtr->endOffset = _filesHandler->seek(streamPtr->soundId, 0, SEEK_END, streamPtr->bufId);
+		streamPtr->endOffset = filesSeek(streamPtr->soundId, 0, SEEK_END);
 	}
 
 	int32 size = streamPtr->readIndex - streamPtr->loadIndex;
@@ -296,7 +296,7 @@ int IMuseDigital::streamerFetchData(IMuseDigiStream *streamPtr) {
 				requestedAmount = loadSize;
 			}
 
-			if (_filesHandler->seek(streamPtr->soundId, streamPtr->curOffset, SEEK_SET, streamPtr->bufId) != streamPtr->curOffset) {
+			if (filesSeek(streamPtr->soundId, streamPtr->curOffset, SEEK_SET) != streamPtr->curOffset) {
 				debug(5, "IMuseDigital::streamerFetchData(): ERROR: invalid seek in streamer (%d), pausing stream...", streamPtr->curOffset);
 				streamPtr->paused = 1;
 				return 0;
@@ -305,7 +305,7 @@ int IMuseDigital::streamerFetchData(IMuseDigiStream *streamPtr) {
 			_streamerBailFlag = 0;
 
 			_mutex->lock();
-			actualAmount = _filesHandler->read(streamPtr->soundId, &streamPtr->buf[streamPtr->loadIndex], requestedAmount, streamPtr->bufId);
+			actualAmount = filesRead(streamPtr->soundId, &streamPtr->buf[streamPtr->loadIndex], requestedAmount);
 			_mutex->unlock();
 
 			if (_streamerBailFlag)
diff --git a/engines/grim/imuse/dimuse_tracks.cpp b/engines/grim/imuse/dimuse_tracks.cpp
index 44e859e601f..0dc2c1c2b54 100644
--- a/engines/grim/imuse/dimuse_tracks.cpp
+++ b/engines/grim/imuse/dimuse_tracks.cpp
@@ -303,8 +303,6 @@ int IMuseDigital::tracksStopAllSounds() {
 		tracksClear(curTrack);
 	}
 
-	_filesHandler->closeAllSounds();
-
 	return 0;
 }
 


Commit: 69f0cf60fb011a72aa2b379ea7f2a07d94c0452b
    https://github.com/scummvm/scummvm/commit/69f0cf60fb011a72aa2b379ea7f2a07d94c0452b
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Clean-up leftover files

Changed paths:
  R engines/grim/imuse/dimuse_bndmgr.cpp
  R engines/grim/imuse/dimuse_bndmgr.h
  R engines/grim/imuse/dimuse_files.h
  R engines/grim/imuse/dimuse_sndmgr.cpp
  R engines/grim/imuse/dimuse_sndmgr.h
  R engines/grim/imuse/dimuse_wave.cpp
    engines/grim/imuse/dimuse_engine.cpp
    engines/grim/imuse/dimuse_engine.h
    engines/grim/module.mk


diff --git a/engines/grim/imuse/dimuse_bndmgr.cpp b/engines/grim/imuse/dimuse_bndmgr.cpp
deleted file mode 100644
index a78965268ed..00000000000
--- a/engines/grim/imuse/dimuse_bndmgr.cpp
+++ /dev/null
@@ -1,413 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-
-#include "common/scummsys.h"
-#include "engines/grim/imuse/dimuse_bndmgr.h"
-#include "engines/grim/imuse/dimuse_codecs.h"
-
-namespace Grim {
-
-BundleDirCache::BundleDirCache() {
-	for (int fileId = 0; fileId < ARRAYSIZE(_bundleDirCache); fileId++) {
-		_bundleDirCache[fileId].bundleTable = nullptr;
-		_bundleDirCache[fileId].fileName[0] = 0;
-		_bundleDirCache[fileId].numFiles = 0;
-		_bundleDirCache[fileId].isCompressed = false;
-		_bundleDirCache[fileId].indexTable = nullptr;
-	}
-}
-
-BundleDirCache::~BundleDirCache() {
-	for (int fileId = 0; fileId < ARRAYSIZE(_bundleDirCache); fileId++) {
-		free(_bundleDirCache[fileId].bundleTable);
-		free(_bundleDirCache[fileId].indexTable);
-	}
-}
-
-BundleDirCache::AudioTable *BundleDirCache::getTable(int slot) {
-	return _bundleDirCache[slot].bundleTable;
-}
-
-int32 BundleDirCache::getNumFiles(int slot) {
-	return _bundleDirCache[slot].numFiles;
-}
-
-BundleDirCache::IndexNode *BundleDirCache::getIndexTable(int slot) {
-	return _bundleDirCache[slot].indexTable;
-}
-
-bool BundleDirCache::isSndDataExtComp(int slot) {
-	return _bundleDirCache[slot].isCompressed;
-}
-
-int BundleDirCache::matchFile(const char *filename) {
-	int32 tag, offset;
-	bool found = false;
-	int freeSlot = -1;
-	int fileId;
-
-	for (fileId = 0; fileId < ARRAYSIZE(_bundleDirCache); fileId++) {
-		if ((_bundleDirCache[fileId].bundleTable == nullptr) && (freeSlot == -1)) {
-			freeSlot = fileId;
-		}
-		if (scumm_stricmp(filename, _bundleDirCache[fileId].fileName) == 0) {
-			found = true;
-			break;
-		}
-	}
-
-	if (!found) {
-		Common::File file;
-
-		// TODO
-		// if (g_scumm->openFile(file, filename) == false) {
-		// 	error("BundleDirCache::matchFile() Can't open bundle file: %s", filename);
-		// 	return false;
-		// }
-
-		if (freeSlot == -1)
-			error("BundleDirCache::matchFileFile() Can't find free slot for file bundle dir cache");
-
-		tag = file.readUint32BE();
-		if (tag == MKTAG('L','B','2','3'))
-			_bundleDirCache[freeSlot].isCompressed = true;
-		offset = file.readUint32BE();
-
-		Common::strlcpy(_bundleDirCache[freeSlot].fileName, filename, sizeof(_bundleDirCache[freeSlot].fileName));
-		_bundleDirCache[freeSlot].numFiles = file.readUint32BE();
-		_bundleDirCache[freeSlot].bundleTable = (AudioTable *)malloc(_bundleDirCache[freeSlot].numFiles * sizeof(AudioTable));
-		assert(_bundleDirCache[freeSlot].bundleTable);
-
-		file.seek(offset, SEEK_SET);
-
-		_bundleDirCache[freeSlot].indexTable =
-				(IndexNode *)calloc(_bundleDirCache[freeSlot].numFiles, sizeof(IndexNode));
-		assert(_bundleDirCache[freeSlot].indexTable);
-
-		for (int32 i = 0; i < _bundleDirCache[freeSlot].numFiles; i++) {
-			char name[24], c;
-			int32 z = 0;
-			int32 z2;
-
-			if (tag == MKTAG('L','B','2','3')) {
-				file.read(_bundleDirCache[freeSlot].bundleTable[i].filename, 24);
-			} else {
-				for (z2 = 0; z2 < 8; z2++)
-					if ((c = file.readByte()) != 0)
-						name[z++] = c;
-				name[z++] = '.';
-				for (z2 = 0; z2 < 4; z2++)
-					if ((c = file.readByte()) != 0)
-						name[z++] = c;
-
-				name[z] = '\0';
-				Common::strlcpy(_bundleDirCache[freeSlot].bundleTable[i].filename, name, sizeof(_bundleDirCache[freeSlot].bundleTable[i].filename));
-			}
-			_bundleDirCache[freeSlot].bundleTable[i].offset = file.readUint32BE();
-			_bundleDirCache[freeSlot].bundleTable[i].size = file.readUint32BE();
-			Common::strlcpy(_bundleDirCache[freeSlot].indexTable[i].filename, _bundleDirCache[freeSlot].bundleTable[i].filename, sizeof(_bundleDirCache[freeSlot].indexTable[i].filename));
-			_bundleDirCache[freeSlot].indexTable[i].index = i;
-		}
-		qsort(_bundleDirCache[freeSlot].indexTable, _bundleDirCache[freeSlot].numFiles,
-				sizeof(IndexNode), (int (*)(const void *, const void *))scumm_stricmp);
-		return freeSlot;
-	} else {
-		return fileId;
-	}
-}
-
-BundleMgr::BundleMgr(BundleDirCache *cache) {
-	_cache = cache;
-	_bundleTable = nullptr;
-	_compTable = nullptr;
-	_numFiles = 0;
-	_numCompItems = 0;
-	_lastBlockDecompressedSize = 0;
-	_curSampleId = -1;
-	_fileBundleId = -1;
-	_file = new Common::File();
-	_compInputBuff = nullptr;
-}
-
-BundleMgr::~BundleMgr() {
-	close();
-	delete _file;
-}
-
-Common::SeekableReadStream *BundleMgr::getFile(const char *filename, int32 &offset, int32 &size) {
-	BundleDirCache::IndexNode target;
-	Common::strlcpy(target.filename, filename, sizeof(target.filename));
-	BundleDirCache::IndexNode *found = (BundleDirCache::IndexNode *)bsearch(&target, _indexTable, _numFiles,
-			sizeof(BundleDirCache::IndexNode), (int (*)(const void *, const void *))scumm_stricmp);
-	if (found) {
-		_file->seek(_bundleTable[found->index].offset, SEEK_SET);
-		offset = _bundleTable[found->index].offset;
-		size = _bundleTable[found->index].size;
-		return _file;
-	}
-
-	return nullptr;
-}
-
-bool BundleMgr::open(const char *filename, bool &isCompressed, bool errorFlag) {
-	if (_file->isOpen())
-		return true;
-
-	// TODO
-	// if (g_scumm->openFile(*_file, filename) == false) {
-	// 	if (errorFlag) {
-	// 		error("BundleMgr::open() Can't open bundle file: %s", filename);
-	// 	} else {
-	// 		warning("BundleMgr::open() Can't open bundle file: %s", filename);
-	// 	}
-	// 	return false;
-	// }
-
-	int slot = _cache->matchFile(filename);
-	assert(slot != -1);
-	isCompressed = _cache->isSndDataExtComp(slot);
-	_numFiles = _cache->getNumFiles(slot);
-	assert(_numFiles);
-	_bundleTable = _cache->getTable(slot);
-	_indexTable = _cache->getIndexTable(slot);
-	assert(_bundleTable);
-	_compTableLoaded = false;
-	_isUncompressed = false;
-	_outputSize = 0;
-	_lastBlockDecompressedSize = 0;
-	_curDecompressedFilePos = 0;
-	_lastBlock = -1;
-
-	return true;
-}
-
-void BundleMgr::close() {
-	if (_file->isOpen()) {
-		_file->close();
-		_bundleTable = nullptr;
-		_numFiles = 0;
-		_numCompItems = 0;
-		_lastBlockDecompressedSize = 0;
-		_curDecompressedFilePos = 0;
-		_compTableLoaded = false;
-		_isUncompressed = false;
-		_lastBlock = -1;
-		_outputSize = 0;
-		_curSampleId = -1;
-		free(_compTable);
-		_compTable = nullptr;
-		free(_compInputBuff);
-		_compInputBuff = nullptr;
-	}
-}
-
-bool BundleMgr::loadCompTable(int32 index) {
-	_file->seek(_bundleTable[index].offset, SEEK_SET);
-	uint32 tag = _file->readUint32BE();
-
-	if (tag == MKTAG('i','M','U','S')) {
-		_isUncompressed = true;
-		return true;
-	}
-
-	_numCompItems = _file->readUint32BE();
-	assert(_numCompItems > 0);
-	_file->seek(4, SEEK_CUR);
-	_lastBlockDecompressedSize = _file->readUint32BE();
-	if (tag != MKTAG('C','O','M','P')) {
-		debug("BundleMgr::loadCompTable() Compressed sound %d (%s:%d) invalid (%s)", index, _file->getName(), _bundleTable[index].offset, tag2str(tag));
-		return false;
-	}
-
-	_compTable = (CompTable *)malloc(sizeof(CompTable) * _numCompItems);
-	assert(_compTable);
-	int32 maxSize = 0;
-	for (int i = 0; i < _numCompItems; i++) {
-		_compTable[i].offset = _file->readUint32BE();
-		_compTable[i].size = _file->readUint32BE();
-		_compTable[i].codec = _file->readUint32BE();
-		_file->seek(4, SEEK_CUR);
-		if (_compTable[i].size > maxSize)
-			maxSize = _compTable[i].size;
-	}
-	// CMI hack: one more byte at the end of input buffer
-	_compInputBuff = (byte *)malloc(maxSize + 1);
-	assert(_compInputBuff);
-
-	return true;
-}
-
-int32 BundleMgr::seekFile(int32 offset, int mode) {
-	// We don't actually seek the file, but instead try to find that the specified offset exists
-	// within the decompressed blocks, and save that offset in _curDecompressedFilePos
-	int result = 0;
-	switch (mode) {
-	case SEEK_END:
-		if (_isUncompressed) {
-			result = offset + _bundleTable[_curSampleId].size;
-		} else {
-			result = offset + ((_numCompItems - 1) * DIMUSE_BUN_CHUNK_SIZE) + _lastBlockDecompressedSize;
-		}
-		_curDecompressedFilePos = result;
-		break;
-	case SEEK_SET:
-	default:
-		if (_isUncompressed) {
-			result = offset;
-			_curDecompressedFilePos = result;
-		} else {
-			int destBlock = offset / DIMUSE_BUN_CHUNK_SIZE + (offset % DIMUSE_BUN_CHUNK_SIZE != 0);
-			if (destBlock <= _numCompItems) {
-				result = offset;
-				_curDecompressedFilePos = result;
-			}
-		}
-		break;
-	}
-	return result;
-}
-
-int32 BundleMgr::readFile(const char *name, int32 size, byte **comp_final, bool header_outside) {
-	int32 final_size = 0;
-
-	if (!_file->isOpen()) {
-		error("BundleMgr::readFile() File is not open");
-		return 0;
-	}
-
-	// Find the sound in the bundle
-	BundleDirCache::IndexNode target;
-	strncpy(target.filename, name, sizeof(target.filename));
-	target.filename[sizeof(target.filename) - 1] = '\0';
-	BundleDirCache::IndexNode *found = (BundleDirCache::IndexNode *)bsearch(&target, _indexTable, _numFiles,
-		sizeof(BundleDirCache::IndexNode), (int(*)(const void *, const void *))scumm_stricmp);
-
-	if (found) {
-		int32 i, finalSize, outputSize;
-		int skip, firstBlock, lastBlock;
-		int headerSize = 0;
-
-		assert(0 <= found->index && found->index < _numFiles);
-
-		if (_file->isOpen() == false) {
-			error("BundleMgr::readFile() File is not open");
-			return 0;
-		}
-
-		if (_curSampleId == -1)
-			_curSampleId = found->index;
-
-		assert(_curSampleId == found->index);
-
-		if (!_compTableLoaded) {
-			_compTableLoaded = loadCompTable(found->index);
-			if (!_compTableLoaded)
-				return 0;
-		}
-
-		if (_isUncompressed) {
-			_file->seek(_bundleTable[found->index].offset + _curDecompressedFilePos + headerSize, SEEK_SET);
-			*comp_final = (byte *)malloc(size);
-			assert(*comp_final);
-			_file->read(*comp_final, size);
-			_curDecompressedFilePos += size;
-			return size;
-		}
-
-		firstBlock = (_curDecompressedFilePos + headerSize) / DIMUSE_BUN_CHUNK_SIZE;
-		lastBlock = (_curDecompressedFilePos + headerSize + size - 1) / DIMUSE_BUN_CHUNK_SIZE;
-
-		// Clip last_block by the total number of blocks (= "comp items")
-		if ((lastBlock >= _numCompItems) && (_numCompItems > 0))
-			lastBlock = _numCompItems - 1;
-
-		int32 blocksFinalSize = DIMUSE_BUN_CHUNK_SIZE * (1 + lastBlock - firstBlock);
-		*comp_final = (byte *)malloc(blocksFinalSize);
-		assert(*comp_final);
-		finalSize = 0;
-
-		skip = (_curDecompressedFilePos + headerSize) % DIMUSE_BUN_CHUNK_SIZE; // Excess length after the last block
-
-		for (i = firstBlock; i <= lastBlock; i++) {
-			if (_lastBlock != i) {
-				// CMI hack: one more zero byte at the end of input buffer
-				_compInputBuff[_compTable[i].size] = 0;
-				_file->seek(_bundleTable[found->index].offset + _compTable[i].offset, SEEK_SET);
-				_file->read(_compInputBuff, _compTable[i].size);
-				_outputSize = BundleCodecs::decompressCodec(_compTable[i].codec, _compInputBuff, _compOutputBuff, _compTable[i].size);
-
-				if (_outputSize > DIMUSE_BUN_CHUNK_SIZE) {
-					error("_outputSize: %d", _outputSize);
-				}
-				_lastBlock = i;
-			}
-
-			outputSize = _outputSize;
-
-			if (header_outside) {
-				outputSize -= skip;
-			} else {
-				if ((headerSize != 0) && (skip >= headerSize))
-					outputSize -= skip;
-			}
-
-			if ((outputSize + skip) > DIMUSE_BUN_CHUNK_SIZE) // workaround
-				outputSize -= (outputSize + skip) - DIMUSE_BUN_CHUNK_SIZE;
-
-			if (outputSize > size)
-				outputSize = size;
-
-			assert(finalSize + outputSize <= blocksFinalSize);
-
-			memcpy(*comp_final + finalSize, _compOutputBuff + skip, outputSize);
-			finalSize += outputSize;
-
-			size -= outputSize;
-			assert(size >= 0);
-			if (size == 0)
-				break;
-
-			skip = 0;
-		}
-		_curDecompressedFilePos += finalSize;
-
-		return finalSize;
-	}
-
-	debug(2, "BundleMgr::readFile() Failed finding sound %s", name);
-	return final_size;
-}
-
-bool BundleMgr::isExtCompBun() {
-	bool isExtComp = false;
-	bool isExtComp1 = false, isExtComp2 = false, isExtComp3 = false, isExtComp4 = false;
-	this->open("voxdisk1.bun", isExtComp1); this->close();
-	this->open("voxdisk2.bun", isExtComp2); this->close();
-	this->open("musdisk1.bun", isExtComp3); this->close();
-	this->open("musdisk2.bun", isExtComp4); this->close();
-
-	isExtComp = isExtComp1 | isExtComp2 | isExtComp3 | isExtComp4;
-
-	return isExtComp;
-}
-
-} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_bndmgr.h b/engines/grim/imuse/dimuse_bndmgr.h
deleted file mode 100644
index 5e73c3534d4..00000000000
--- a/engines/grim/imuse/dimuse_bndmgr.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#ifndef GRIM_IMUSE_BUNDLE_MGR_H
-#define GRIM_IMUSE_BUNDLE_MGR_H
-
-#include "common/scummsys.h"
-#include "common/debug.h"
-#include "common/file.h"
-#include "engines/grim/imuse/dimuse_defs.h"
-
-namespace Grim {
-
-class BundleDirCache {
-public:
-	struct AudioTable {
-		char filename[24];
-		int32 offset;
-		int32 size;
-	};
-
-	struct IndexNode {
-		char filename[24];
-		int32 index;
-	};
-
-private:
-
-	struct FileDirCache {
-		char fileName[20];
-		AudioTable *bundleTable;
-		int32 numFiles;
-		bool isCompressed;
-		IndexNode *indexTable;
-	} _bundleDirCache[4];
-
-public:
-	BundleDirCache();
-	~BundleDirCache();
-
-	int matchFile(const char *filename);
-	AudioTable *getTable(int slot);
-	IndexNode *getIndexTable(int slot);
-	int32 getNumFiles(int slot);
-	bool isSndDataExtComp(int slot);
-};
-
-class BundleMgr {
-
-private:
-	struct CompTable {
-		int32 offset;
-		int32 size;
-		int32 codec;
-	};
-
-	BundleDirCache *_cache;
-	BundleDirCache::AudioTable *_bundleTable;
-	BundleDirCache::IndexNode *_indexTable = nullptr;
-	CompTable *_compTable;
-
-	int _numFiles = 0;
-	int _numCompItems = 0;
-	int _lastBlockDecompressedSize = 0;
-	int _curSampleId = 0;
-	int _curDecompressedFilePos = 0;
-	Common::File *_file;
-	bool _compTableLoaded = 0;
-	bool _isUncompressed = 0;
-	int _fileBundleId = 0;
-	byte _compOutputBuff[0x2000] = {};
-	byte *_compInputBuff = nullptr;
-	int _outputSize = 0;
-	int _lastBlock = 0;
-	bool loadCompTable(int32 index);
-
-public:
-
-	BundleMgr(BundleDirCache *_cache);
-	~BundleMgr();
-
-	bool open(const char *filename, bool &isCompressed, bool errorFlag = false);
-	void close();
-	Common::SeekableReadStream *getFile(const char *filename, int32 &offset, int32 &size);
-	int32 seekFile(int32 offset, int size);
-	int32 readFile(const char *name, int32 size, byte **compFinal, bool headerOutside);
-	bool isExtCompBun();
-};
-
-} // End of namespace Grim
-
-#endif
diff --git a/engines/grim/imuse/dimuse_engine.cpp b/engines/grim/imuse/dimuse_engine.cpp
index e92e0c47c3a..da2db9be119 100644
--- a/engines/grim/imuse/dimuse_engine.cpp
+++ b/engines/grim/imuse/dimuse_engine.cpp
@@ -24,8 +24,6 @@
 
 #include "engines/grim/imuse/dimuse_engine.h"
 #include "engines/grim/imuse/dimuse_defs.h"
-#include "engines/grim/imuse/dimuse_bndmgr.h"
-#include "engines/grim/imuse/dimuse_sndmgr.h"
 #include "engines/grim/imuse/dimuse_tables.h"
 
 #include "engines/grim/movie/codecs/vima.h"
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/dimuse_engine.h
index cca2bcceea2..1b6f7503af5 100644
--- a/engines/grim/imuse/dimuse_engine.h
+++ b/engines/grim/imuse/dimuse_engine.h
@@ -33,10 +33,7 @@
 #include "engines/grim/imuse/dimuse_internalmixer.h"
 #include "engines/grim/imuse/dimuse_groups.h"
 #include "engines/grim/imuse/dimuse_fades.h"
-#include "engines/grim/imuse/dimuse_files.h"
 #include "engines/grim/imuse/dimuse_triggers.h"
-#include "engines/grim/imuse/dimuse_bndmgr.h"
-#include "engines/grim/imuse/dimuse_sndmgr.h"
 #include "engines/grim/imuse/dimuse_tables.h"
 
 #include "audio/mixer.h"
diff --git a/engines/grim/imuse/dimuse_files.h b/engines/grim/imuse/dimuse_files.h
deleted file mode 100644
index db7b572c748..00000000000
--- a/engines/grim/imuse/dimuse_files.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#ifndef GRIM_IMUSE_FILES_H
-#define GRIM_IMUSE_FILES_H
-
-#endif
diff --git a/engines/grim/imuse/dimuse_sndmgr.cpp b/engines/grim/imuse/dimuse_sndmgr.cpp
deleted file mode 100644
index 51384537813..00000000000
--- a/engines/grim/imuse/dimuse_sndmgr.cpp
+++ /dev/null
@@ -1,275 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-
-#include "common/scummsys.h"
-
-#include "audio/audiostream.h"
-#include "audio/decoders/flac.h"
-#include "audio/decoders/voc.h"
-#include "audio/decoders/vorbis.h"
-#include "audio/decoders/mp3.h"
-
-#include "engines/grim/imuse/dimuse_bndmgr.h"
-#include "engines/grim/imuse/dimuse_codecs.h"
-#include "engines/grim/imuse/dimuse_sndmgr.h"
-
-namespace Grim {
-
-ImuseDigiSndMgr::ImuseDigiSndMgr() {
-	for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
-		memset(&_sounds[l], 0, sizeof(SoundDesc));
-	}
-	_disk = 0;
-	_cacheBundleDir = new BundleDirCache();
-	assert(_cacheBundleDir);
-	BundleCodecs::initializeImcTables();
-}
-
-ImuseDigiSndMgr::~ImuseDigiSndMgr() {
-	for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
-		closeSound(&_sounds[l]);
-	}
-
-	delete _cacheBundleDir;
-	BundleCodecs::releaseImcTables();
-}
-
-ImuseDigiSndMgr::SoundDesc *ImuseDigiSndMgr::allocSlot() {
-	for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
-		if (!_sounds[l].inUse) {
-			_sounds[l].inUse = true;
-			_sounds[l].scheduledForDealloc = false;
-			return &_sounds[l];
-		}
-	}
-
-	return nullptr;
-}
-
-bool ImuseDigiSndMgr::openMusicBundle(SoundDesc *sound, int &disk) {
-	bool result = false;
-	bool compressed = false;
-
-	sound->bundle = new BundleMgr(_cacheBundleDir);
-	assert(sound->bundle);
-
-	char musicfile[20];
-	// TODO
-	// if (disk == -1)
-	// 	disk = _vm->VAR(_vm->VAR_CURRENTDISK);
-	Common::sprintf_s(musicfile, "musdisk%d.bun", disk);
-//	if (_disk != _vm->VAR(_vm->VAR_CURRENTDISK)) {
-//		_vm->_DiMUSE_v1->parseScriptCmds(0x1000, 0, 0, 0, 0, 0, 0, 0);
-//		_vm->_DiMUSE_v1->parseScriptCmds(0x2000, 0, 0, 0, 0, 0, 0, 0);
-//		_vm->_DiMUSE_v1->stopAllSounds();
-//		sound->bundle->closeFile();
-//	}
-
-	result = sound->bundle->open(musicfile, compressed);
-
-	// FIXME: Shouldn't we only set _disk if result == true?
-	// TODO
-	// _disk = (byte)_vm->VAR(_vm->VAR_CURRENTDISK);
-
-	// TODO
-	// _vm->VAR(_vm->VAR_MUSIC_BUNDLE_LOADED) = result ? 1 : 0;
-
-	return result;
-}
-
-bool ImuseDigiSndMgr::openVoiceBundle(SoundDesc *sound, int &disk) {
-	bool result = false;
-	bool compressed = false;
-
-	sound->bundle = new BundleMgr(_cacheBundleDir);
-	assert(sound->bundle);
-
-	char voxfile[20];
-	// TODO
-	// if (disk == -1)
-	// 	disk = _vm->VAR(_vm->VAR_CURRENTDISK);
-	Common::sprintf_s(voxfile, "voxdisk%d.bun", disk);
-//	if (_disk != _vm->VAR(_vm->VAR_CURRENTDISK)) {
-//		_vm->_DiMUSE_v1->parseScriptCmds(0x1000, 0, 0, 0, 0, 0, 0, 0);
-//		_vm->_DiMUSE_v1->parseScriptCmds(0x2000, 0, 0, 0, 0, 0, 0, 0);
-//		_vm->_DiMUSE_v1->stopAllSounds();
-//		sound->bundle->closeFile();
-//	}
-
-	result = sound->bundle->open(voxfile, compressed);
-
-	// FIXME: Shouldn't we only set _disk if result == true?
-	// TODO
-	// _disk = (byte)_vm->VAR(_vm->VAR_CURRENTDISK);
-
-	// TODO
-	// _vm->VAR(_vm->VAR_VOICE_BUNDLE_LOADED) = result ? 1 : 0;
-
-	return result;
-}
-
-ImuseDigiSndMgr::SoundDesc *ImuseDigiSndMgr::openSound(int32 soundId, const char *soundName, int soundType, int volGroupId, int disk) {
-	assert(soundId >= 0);
-	assert(soundType);
-
-	SoundDesc *sound = allocSlot();
-	if (!sound) {
-		error("ImuseDigiSndMgr::openSound() can't alloc free sound slot");
-	}
-
-	const bool header_outside = true;
-	bool result = false;
-	byte *ptr = nullptr;
-
-	switch (soundType) {
-	case IMUSE_RESOURCE:
-		assert(soundName[0] == 0);	// Paranoia check
-
-		// TODO
-		// _vm->_res->lock(rtSound, soundId);
-		// ptr = _vm->getResourceAddress(rtSound, soundId);
-		// if (ptr == nullptr) {
-		// 	closeSound(sound);
-		// 	return nullptr;
-		// }
-		// sound->resPtr = ptr;
-		// sound->resSize = _vm->getResourceSize(rtSound, soundId) - 8;
-		break;
-	case IMUSE_BUNDLE:
-		if (volGroupId == IMUSE_VOLGRP_VOICE)
-			result = openVoiceBundle(sound, disk);
-		else if (volGroupId == IMUSE_VOLGRP_MUSIC)
-			result = openMusicBundle(sound, disk);
-		else
-			error("ImuseDigiSndMgr::openSound() Don't know how load sound: %d", soundId);
-		if (!result) {
-			closeSound(sound);
-			return nullptr;
-		}
-
-		if (soundName[0] != 0) {
-			if (sound->bundle->readFile(soundName, 0x2000, &ptr, header_outside) == 0 || ptr == nullptr) {
-				closeSound(sound);
-				free(ptr);
-				return nullptr;
-			}
-		}
-
-		sound->resPtr = nullptr;
-		break;
-	default:
-		error("ImuseDigiSndMgr::openSound() Unknown soundType %d (trying to load sound %d)", soundType, soundId);
-	}
-
-	Common::strlcpy(sound->name, soundName, sizeof(sound->name));
-	sound->soundId = soundId;
-
-	if (soundType == IMUSE_BUNDLE) {
-		free(ptr);
-	}
-	return sound;
-}
-
-void ImuseDigiSndMgr::closeSound(SoundDesc *soundDesc) {
-	// Check if there's an actual sound to close...
-	if (!checkForProperHandle(soundDesc))
-		return;
-
-	if (soundDesc->resPtr) {
-		bool found = false;
-		for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
-			if ((_sounds[l].soundId == soundDesc->soundId) && (&_sounds[l] != soundDesc))
-				found = true;
-		}
-		// TODO
-		// if (!found)
-		// 	_vm->_res->unlock(rtSound, soundDesc->soundId);
-	}
-
-	delete soundDesc->bundle;
-
-	memset(soundDesc, 0, sizeof(SoundDesc));
-}
-
-ImuseDigiSndMgr::SoundDesc *ImuseDigiSndMgr::findSoundById(int soundId) {
-	SoundDesc *soundDesc = nullptr;
-	for (int i = 0; i < MAX_IMUSE_SOUNDS; i++) {
-		if (_sounds[i].soundId == soundId) {
-			soundDesc = &_sounds[i];
-			break;
-		}
-	}
-	return soundDesc;
-}
-
-ImuseDigiSndMgr::SoundDesc *ImuseDigiSndMgr::getSounds() {
-	return _sounds;
-}
-
-void ImuseDigiSndMgr::scheduleSoundForDeallocation(int soundId) {
-	SoundDesc *soundDesc = nullptr;
-	for (int i = 0; i < MAX_IMUSE_SOUNDS; i++) {
-		if (_sounds[i].soundId == soundId) {
-			soundDesc = &_sounds[i];
-		}
-	}
-
-	// Check if there's an actual sound to deallocate...
-	if (!checkForProperHandle(soundDesc))
-		return;
-
-	soundDesc->scheduledForDealloc = true;
-}
-
-void ImuseDigiSndMgr::closeSoundById(int soundId) {
-	SoundDesc *soundDesc = nullptr;
-	for (int i = 0; i < MAX_IMUSE_SOUNDS; i++) {
-		if (_sounds[i].soundId == soundId) {
-			soundDesc = &_sounds[i];
-		}
-	}
-
-	if (soundDesc) {
-		assert(checkForProperHandle(soundDesc));
-
-		// TODO
-		// if (soundDesc->resPtr) {
-		// 	_vm->_res->unlock(rtSound, soundDesc->soundId);
-		// }
-
-		delete soundDesc->bundle;
-
-		memset(soundDesc, 0, sizeof(SoundDesc));
-	}
-}
-
-bool ImuseDigiSndMgr::checkForProperHandle(SoundDesc *soundDesc) {
-	if (!soundDesc)
-		return false;
-	for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
-		if (soundDesc == &_sounds[l])
-			return true;
-	}
-	return false;
-}
-
-} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_sndmgr.h b/engines/grim/imuse/dimuse_sndmgr.h
deleted file mode 100644
index 72703118e81..00000000000
--- a/engines/grim/imuse/dimuse_sndmgr.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#ifndef GRIM_IMUSE_SNDMGR_H
-#define GRIM_IMUSE_SNDMGR_H
-
-
-#include "common/scummsys.h"
-
-namespace Audio {
-class SeekableAudioStream;
-}
-
-namespace Common {
-class SeekableReadStream;
-}
-
-namespace Grim {
-
-class BundleMgr;
-class BundleDirCache;
-
-class ImuseDigiSndMgr {
-public:
-
-#define MAX_IMUSE_SOUNDS 16
-
-#define IMUSE_RESOURCE 1
-#define IMUSE_BUNDLE 2
-
-#define IMUSE_VOLGRP_VOICE 1
-#define IMUSE_VOLGRP_SFX 2
-#define IMUSE_VOLGRP_MUSIC 3
-
-public:
-
-	struct SoundDesc {
-		bool inUse;
-		bool scheduledForDealloc;
-
-		byte *resPtr;
-		int resSize;
-		int resCurOffset;
-		char name[15];
-		int16 soundId;
-		BundleMgr *bundle;
-	};
-
-private:
-
-	SoundDesc _sounds[MAX_IMUSE_SOUNDS];
-	bool checkForProperHandle(SoundDesc *soundDesc);
-	SoundDesc *allocSlot();
-
-	byte _disk;
-	BundleDirCache *_cacheBundleDir;
-
-	bool openMusicBundle(SoundDesc *sound, int &disk);
-	bool openVoiceBundle(SoundDesc *sound, int &disk);
-
-public:
-
-	ImuseDigiSndMgr();
-	~ImuseDigiSndMgr();
-
-	SoundDesc *openSound(int32 soundId, const char *soundName, int soundType, int volGroupId, int disk);
-	void closeSound(SoundDesc *soundDesc);
-	void closeSoundById(int soundId);
-	SoundDesc *findSoundById(int soundId);
-	SoundDesc *getSounds();
-	void scheduleSoundForDeallocation(int soundId);
-
-};
-
-} // End of namespace Grim
-
-#endif
diff --git a/engines/grim/imuse/dimuse_wave.cpp b/engines/grim/imuse/dimuse_wave.cpp
deleted file mode 100644
index 9f5d17d4f33..00000000000
--- a/engines/grim/imuse/dimuse_wave.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#include "engines/grim/imuse/dimuse_engine.h"
-
-namespace Grim {
-
-} // End of namespace Grim
diff --git a/engines/grim/module.mk b/engines/grim/module.mk
index 97319cfe7fe..a7c1bc7ed3d 100644
--- a/engines/grim/module.mk
+++ b/engines/grim/module.mk
@@ -42,7 +42,6 @@ MODULE_OBJS := \
 	emi/lua_v2_actor.o \
 	emi/lua_v2_sound.o \
 	emi/emi_registry.o \
-	imuse/dimuse_bndmgr.o \
 	imuse/dimuse_cmds.o \
 	imuse/dimuse_codecs.o \
 	imuse/dimuse_dispatch.o \
@@ -52,13 +51,11 @@ MODULE_OBJS := \
 	imuse/dimuse_groups.o \
 	imuse/dimuse_internalmixer.o \
 	imuse/dimuse_scripts.o \
-	imuse/dimuse_sndmgr.o \
 	imuse/dimuse_streamer.o \
 	imuse/dimuse_tables.o \
 	imuse/dimuse_tracks.o \
 	imuse/dimuse_triggers.o \
 	imuse/dimuse_utils.o \
-	imuse/dimuse_wave.o \
 	imuse/dimuse_waveout.o \
 	imuse/imuse.o \
 	imuse/imuse_mcmp_mgr.o \


Commit: 7d556836b81204795acc26a4ff2141b152c482ad
    https://github.com/scummvm/scummvm/commit/7d556836b81204795acc26a4ff2141b152c482ad
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Port original SFX cache and external format detection

Changed paths:
    engines/grim/imuse/dimuse_defs.h
    engines/grim/imuse/dimuse_engine.cpp
    engines/grim/imuse/dimuse_engine.h
    engines/grim/imuse/dimuse_files.cpp


diff --git a/engines/grim/imuse/dimuse_defs.h b/engines/grim/imuse/dimuse_defs.h
index 6596a49bd24..ad7c05c6c8c 100644
--- a/engines/grim/imuse/dimuse_defs.h
+++ b/engines/grim/imuse/dimuse_defs.h
@@ -40,6 +40,7 @@ namespace Grim {
 #define DIMUSE_MAX_STREAMS     3
 #define DIMUSE_MAX_SOUND_LIST  10
 #define DIMUSE_MAX_OPEN_FILES  5
+#define DIMUSE_MAX_CACHED_SOUNDS 32
 
 #define DIMUSE_LARGE_FADES    1
 #define DIMUSE_SMALL_FADES    4
@@ -265,6 +266,18 @@ struct IMuseDigiResource {
 	char filename[80];
 };
 
+struct IMuseDigiCachedSound {
+	char soundFilename[32];
+	int luaSoundId;
+	uint32 tsOfAllocation;
+	uint8 *soundUncompData;
+	uint8 *soundAddrData;
+	uint8 *soundMap;
+	int uncompResourceSize;
+	int flag;
+	int priority;
+};
+
 struct IMuseDigiOpenAudioFile {
 	IMuseDigiResource *resourcePtr;
 	char soundName[32];
diff --git a/engines/grim/imuse/dimuse_engine.cpp b/engines/grim/imuse/dimuse_engine.cpp
index da2db9be119..cf2efab9313 100644
--- a/engines/grim/imuse/dimuse_engine.cpp
+++ b/engines/grim/imuse/dimuse_engine.cpp
@@ -86,6 +86,8 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 	_fadesHandler = new IMuseDigiFadesHandler(this, mutex);
 	_triggersHandler = new IMuseDigiTriggersHandler(this, mutex);
 
+	memset(_soundCache, 0, sizeof(_soundCache));
+	_currentSoundSlot = 0;
 	memset(_openAudioFiles, 0, sizeof(_openAudioFiles));
 	memset(_soundBuffers, 0, sizeof(_soundBuffers));
 	vimaInit(_imuseDestTable);
@@ -129,6 +131,7 @@ IMuseDigital::~IMuseDigital() {
 	diMUSETerminateScript();
 	diMUSETerminate();
 
+	cacheReset();
 	soundsDeallocateBuffer(DIMUSE_BUFFER_SPEECH);
 	soundsDeallocateBuffer(DIMUSE_BUFFER_MUSIC);
 
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/dimuse_engine.h
index 1b6f7503af5..01d7d773dab 100644
--- a/engines/grim/imuse/dimuse_engine.h
+++ b/engines/grim/imuse/dimuse_engine.h
@@ -252,6 +252,15 @@ private:
 	int ihostFseek(int soundId, int32 offset, int mode);
 	int ihostRead(int soundId, uint8 *destBuf, int32 size);
 
+	IMuseDigiCachedSound _soundCache[DIMUSE_MAX_CACHED_SOUNDS];
+	int _currentSoundSlot;
+
+	int cacheGetSoundId(const char *soundName);
+	int cachePurgeOldestStoppedSound();
+	void cacheReset();
+	uint8 *soundsGetExtFormatBuffer(uint8 *streamHeader, int *formatId, int *targetSampleRate, int *targetWordSize, int *targetNumChannels, int *swapEndianFlag, int *regionLength);
+	int createSoundHeader(uint8 *buffer, int mode, int sampleRate, int wordSize, int numChannels, int regionLength);
+
 	void soundsAllocateBuffer(int bufferId, int32 bufSize, int32 loadSize, int32 criticalSize);
 	void soundsDeallocateBuffer(int bufferId);
 	IMuseDigiResource *soundsOpenFile(const char *filename);
diff --git a/engines/grim/imuse/dimuse_files.cpp b/engines/grim/imuse/dimuse_files.cpp
index 008b0c7a34e..2c67309ae83 100644
--- a/engines/grim/imuse/dimuse_files.cpp
+++ b/engines/grim/imuse/dimuse_files.cpp
@@ -20,6 +20,7 @@
  */
 
 #include "common/stream.h"
+#include "common/system.h"
 
 #include "engines/grim/resource.h"
 #include "engines/grim/movie/codecs/vima.h"
@@ -380,7 +381,7 @@ int IMuseDigital::diMUSERemoveSoundFromList(IMuseDigiSoundList **listPtr, IMuseD
 }
 
 bool IMuseDigital::filesCheckRange(int soundId) {
-	return soundId && (uint32)soundId < 0xFFFFFFF0;
+	return soundId > 0;
 }
 
 uint8 *IMuseDigital::filesGetSoundAddrData(int soundId) {
@@ -483,13 +484,17 @@ int IMuseDigital::ihostCloseSound(int soundId) {
 }
 
 uint8 *IMuseDigital::ihostGetMapAddr(int soundId) {
-	// TODO
-	return nullptr;
+	if (soundId < 100 || soundId >= 100 + DIMUSE_MAX_CACHED_SOUNDS)
+		return nullptr;
+
+	return _soundCache[soundId - 100].soundMap;
 }
 
 uint8 *IMuseDigital::ihostGetSoundAddr(int soundId) {
-	// TODO
-	return nullptr;
+	if (soundId < 100 || soundId >= 100 + DIMUSE_MAX_CACHED_SOUNDS)
+		return nullptr;
+
+	return _soundCache[soundId - 100].soundAddrData;
 }
 
 IMuseDigiSndBuffer *IMuseDigital::ihostGetBufferInfo(int bufId) {
@@ -652,9 +657,9 @@ int32 IMuseDigital::soundsFileTell(IMuseDigiResource *res) {
 }
 
 int IMuseDigital::soundsGetCompBlockId(IMuseDigiResource *res, int32 offset) {
-	if ((uint32)offset < (uint32)res->resSize) {
+	if (offset >= 0 && offset < res->resSize) {
 		for (int i = 0; i < res->compBlocksNum; i++) {
-			if ((uint32)offset >= (uint32)res->compBlockOffset[i] && (uint32)offset < (uint32)res->compBlockOffset[i + 1])
+			if (offset >= res->compBlockOffset[i] && offset < res->compBlockOffset[i + 1])
 				return i;
 		}
 	}
@@ -759,4 +764,395 @@ int32 IMuseDigital::copyDataFromResource(IMuseDigiResource *res, uint8 *dest, in
 	return resSize;
 }
 
+int IMuseDigital::cacheGetSoundId(const char *soundName) {
+	uintptr soundKey = (uintptr)soundName;
+	IMuseDigiCachedSound *sound;
+	int slot, soundId, loadSlot = -1;
+	bool isLuaSoundId;
+	bool allocated = false;
+
+	if (!soundName)
+		return 0;
+
+	if (soundKey == 10000)
+		return 10000;
+
+	if (soundKey <= 1111)
+		return 0;
+
+	isLuaSoundId = soundKey < 1367;
+	if (soundKey > 1367) {
+		if (strlen(soundName) <= 4) {
+			soundId = atoi(soundName);
+			if (soundId == 10000)
+				return soundId;
+
+			if (soundId >= 1111 && soundId < 1367)
+				return 0;
+		}
+
+		isLuaSoundId = false;
+	}
+
+	sound = &_soundCache[DIMUSE_MAX_CACHED_SOUNDS - 1];
+	slot = DIMUSE_MAX_CACHED_SOUNDS - 1;
+
+	if (isLuaSoundId) {
+		while ((uintptr)sound->luaSoundId != soundKey) {
+			--sound;
+			if (!slot--)
+				return 0;
+		}
+
+		if (sound->soundUncompData)
+			return slot + 100;
+
+		loadSlot = slot;
+	} else {
+		while (scumm_stricmp(sound->soundFilename, soundName)) {
+			if (!sound->soundFilename[0])
+				loadSlot = slot;
+
+			--sound;
+			if (!slot--) {
+				// The sound is not in the cache: pick an empty slot or purge the oldest one
+				if (loadSlot < 0) {
+					loadSlot = cachePurgeOldestStoppedSound();
+					if (loadSlot < 0)
+						return 0;
+				}
+
+				sound = &_soundCache[loadSlot];
+				Common::strlcpy(sound->soundFilename, soundName, sizeof(sound->soundFilename));
+
+				int slotCounter = _currentSoundSlot;
+				bool collision;
+				do {
+					collision = false;
+					int candidateId = abs(slotCounter) % 256 + 1111;
+					for (int i = 0; i < DIMUSE_MAX_CACHED_SOUNDS; i++) {
+						if (_soundCache[i].soundFilename[0] && _soundCache[i].luaSoundId == candidateId) {
+							collision = true;
+							slotCounter++;
+							break;
+						}
+					}
+				} while (collision);
+
+				_currentSoundSlot = slotCounter;
+				sound->luaSoundId = abs(slotCounter) % 256 + 1111;
+				++_currentSoundSlot;
+
+				allocated = true;
+				break;
+			}
+		}
+
+		if (!allocated) {
+			if (sound->soundUncompData)
+				return slot + 100;
+
+			loadSlot = slot;
+		}
+	}
+
+	// Load the sound in the cache
+	sound->flag = 0;
+
+	IMuseDigiResource *res = soundsOpenFile(sound->soundFilename);
+	if (!res) {
+		memset(sound, 0, sizeof(IMuseDigiCachedSound));
+		return 0;
+	}
+
+	sound->tsOfAllocation = g_system->getMillis();
+
+	// TODO
+	// Lipsync registration for the ".lip" file with the same name
+
+	soundsFileSeek(res, 0, SEEK_END);
+	sound->uncompResourceSize = soundsFileTell(res);
+	soundsFileSeek(res, 0, SEEK_SET);
+
+	sound->soundUncompData = (uint8 *)malloc(sound->uncompResourceSize + 80);
+	if (sound->soundUncompData)
+		copyDataFromResource(res, sound->soundUncompData, sound->uncompResourceSize);
+
+	soundsCloseFile(res);
+
+	int formatId, sampleRate, wordSize, numChannels, swapEndianFlag, dataLength;
+	uint8 *extFormatBuffer = soundsGetExtFormatBuffer(sound->soundUncompData, &formatId, &sampleRate, &wordSize, &numChannels, &swapEndianFlag, &dataLength);
+
+	if (formatId == 3 || formatId == 5) {
+		if (wordSize == 8) {
+			// Convert the 8-bit samples to 16-bit
+			int headerSize = extFormatBuffer - sound->soundUncompData;
+			int dataSize = sound->uncompResourceSize - headerSize;
+			uint8 *convertedData = (uint8 *)malloc(2 * sound->uncompResourceSize + 80);
+
+			memcpy(convertedData, sound->soundUncompData, headerSize);
+
+			uint8 *dest = &convertedData[headerSize];
+			for (int i = 0; i < dataSize; i++) {
+				*dest++ = 0x80;
+				*dest++ = extFormatBuffer[i] ^ 0x80;
+			}
+
+			sound->uncompResourceSize = headerSize + 2 * dataSize;
+			free(sound->soundUncompData);
+			sound->soundUncompData = convertedData;
+			extFormatBuffer = &convertedData[headerSize];
+			dataLength *= 2;
+			swapEndianFlag = 1;
+			wordSize = 16;
+			formatId = 0;
+		}
+
+		if (formatId == 3) {
+			sound->soundMap = sound->soundUncompData;
+			sound->soundAddrData = sound->soundUncompData;
+		} else {
+			uint8 *newHeader = &sound->soundUncompData[sound->uncompResourceSize];
+			createSoundHeader(newHeader, 3, sampleRate, 16, numChannels, dataLength);
+			sound->soundMap = newHeader;
+			sound->soundAddrData = extFormatBuffer - 80;
+			newHeader[31] = swapEndianFlag;
+		}
+
+		return loadSlot + 100;
+	}
+
+	free(sound->soundUncompData);
+
+	// TODO
+	// Reset the lipsync state for this sound
+
+	memset(sound, 0, sizeof(IMuseDigiCachedSound));
+	return 0;
+}
+
+int IMuseDigital::cachePurgeOldestStoppedSound() {
+	int foundSlot = -1;
+	int emptySlot = -1;
+	uint32 oldestTimestamp = g_system->getMillis();
+
+	for (int slot = DIMUSE_MAX_CACHED_SOUNDS - 1; slot >= 0; slot--) {
+		IMuseDigiCachedSound *sound = &_soundCache[slot];
+
+		if (sound->soundFilename[0] && sound->soundUncompData) {
+			if (!diMUSEGetParam(slot + 100, DIMUSE_P_SND_TRACK_NUM) &&
+				!diMUSEGetParam(slot + 100, DIMUSE_P_TRIGS_SNDS) &&
+				(foundSlot < 0 || oldestTimestamp > sound->tsOfAllocation)) {
+				foundSlot = slot;
+				oldestTimestamp = sound->tsOfAllocation;
+			}
+		} else {
+			emptySlot = slot;
+		}
+	}
+
+	if (foundSlot >= 0) {
+		IMuseDigiCachedSound *sound = &_soundCache[foundSlot];
+		sound->soundFilename[0] = 0;
+
+		// TODO
+		// Reset the lipsync state for this sound
+
+		free(sound->soundUncompData);
+		memset(sound, 0, sizeof(IMuseDigiCachedSound));
+		return foundSlot;
+	}
+
+	return emptySlot;
+}
+
+void IMuseDigital::cacheReset() {
+	for (int slot = DIMUSE_MAX_CACHED_SOUNDS - 1; slot >= 0; slot--) {
+		if (_soundCache[slot].soundUncompData) {
+			// TODO
+			// Reset the lipsync state for this sound
+
+			free(_soundCache[slot].soundUncompData);
+		}
+	}
+
+	_currentSoundSlot = 0;
+	memset(_soundCache, 0, sizeof(_soundCache));
+}
+
+uint8 *IMuseDigital::soundsGetExtFormatBuffer(uint8 *streamHeader, int *formatId, int *targetSampleRate, int *targetWordSize, int *targetNumChannels, int *swapEndianFlag, int *regionLength) {
+	bool isMCMP = false;
+	uint8 *header = streamHeader;
+
+	if (formatId)
+		*formatId = 0;
+
+	if (!header)
+		return nullptr;
+
+	if (!memcmp(header, "MCMP", 4)) {
+		int numCompBlocks = READ_BE_UINT16(header + 4);
+		uint8 *codecNamesSize = header + 9 * numCompBlocks + 6;
+		isMCMP = true;
+		header = codecNamesSize + READ_BE_UINT16(codecNamesSize) + 2;
+	}
+
+	if (!memcmp(header, "RIFF", 4)) {
+		uint8 *endOfFile = header + READ_LE_UINT32(header + 4) + 8;
+
+		if (memcmp(header + 8, "WAVEfmt ", 8))
+			return nullptr;
+
+		if (READ_LE_UINT16(header + 20) != 1)
+			return nullptr;
+
+		if (formatId)
+			*formatId = (isMCMP ? 1 : 0) + 5;
+
+		uint8 *chunk = header + 16;
+		uint32 chunkSize = READ_LE_UINT32(chunk);
+
+		if (targetSampleRate)
+			*targetSampleRate = READ_LE_UINT32(chunk + 8);
+
+		if (targetWordSize)
+			*targetWordSize = (int16)READ_LE_UINT16(chunk + 18);
+
+		if (targetNumChannels)
+			*targetNumChannels = (int16)READ_LE_UINT16(chunk + 6);
+
+		if (swapEndianFlag)
+			*swapEndianFlag = 1;
+
+		while (1) {
+			chunk += chunkSize + 8;
+			chunkSize = READ_LE_UINT32(chunk);
+
+			if (chunk >= endOfFile)
+				break;
+
+			if (!memcmp(chunk - 4, "data", 4)) {
+				if (regionLength)
+					*regionLength = chunkSize;
+
+				return chunk + 4;
+			}
+		}
+
+		return nullptr;
+	}
+
+	if (!memcmp(header, "iMUS", 4)) {
+		uint32 mapSize = READ_BE_UINT32(header + 12);
+
+		if (memcmp(header + 16, "FRMT", 4))
+			return nullptr;
+
+		if (formatId)
+			*formatId = (isMCMP ? 1 : 0) + 3;
+
+		uint8 *frmtBlock = header + 32;
+
+		if (targetWordSize)
+			*targetWordSize = READ_BE_UINT32(frmtBlock);
+
+		if (targetSampleRate)
+			*targetSampleRate = READ_BE_UINT32(frmtBlock + 4);
+
+		if (targetNumChannels)
+			*targetNumChannels = READ_BE_UINT32(frmtBlock + 8);
+
+		if (swapEndianFlag)
+			*swapEndianFlag = 0;
+
+		if (regionLength)
+			*regionLength = READ_BE_UINT32(frmtBlock + mapSize - 12);
+
+		return frmtBlock + mapSize - 8;
+	}
+
+	if (isMCMP)
+		return nullptr;
+
+	if (!memcmp(header, "FORM", 4)) {
+		uint8 *endOfFile = header + READ_BE_UINT32(header + 4) + 8;
+
+		if (memcmp(header + 8, "AIFFCOMM", 8))
+			return nullptr;
+
+		if (formatId)
+			*formatId = 7;
+
+		uint8 *chunk = header + 16;
+		uint32 chunkSize = READ_BE_UINT32(chunk);
+
+		if (targetSampleRate) {
+			if (chunk[13] == 14)
+				*targetSampleRate = 44100;
+			else if (chunk[13] == 12)
+				*targetSampleRate = 11025;
+			else
+				*targetSampleRate = 22050;
+		}
+
+		if (targetWordSize)
+			*targetWordSize = chunk[11];
+
+		if (targetNumChannels)
+			*targetNumChannels = chunk[5];
+
+		if (swapEndianFlag)
+			*swapEndianFlag = 0;
+
+		while (1) {
+			chunk += chunkSize + 8;
+			chunkSize = READ_BE_UINT32(chunk);
+
+			if (chunk >= endOfFile)
+				break;
+
+			if (!memcmp(chunk - 4, "SSND", 4)) {
+				if (regionLength)
+					*regionLength = chunkSize - 8;
+
+				return chunk + 12;
+			}
+		}
+
+		return nullptr;
+	}
+
+	// TODO
+	// Headerless audio: CreateAudioChunk() guesses the format from the data
+	return nullptr;
+}
+
+int IMuseDigital::createSoundHeader(uint8 *buffer, int mode, int sampleRate, int wordSize, int numChannels, int regionLength) {
+	if (mode == 3) {
+		memcpy(buffer, "iMUS", 4);
+		WRITE_BE_UINT32(buffer + 4, regionLength + 80);
+		memcpy(buffer + 8, "MAP ", 4);
+		WRITE_BE_UINT32(buffer + 12, 56);
+		memcpy(buffer + 16, "FRMT", 4);
+		WRITE_BE_UINT32(buffer + 20, 20);
+		WRITE_BE_UINT32(buffer + 24, 80);
+		WRITE_BE_UINT32(buffer + 28, 0); // Endianness
+		WRITE_BE_UINT32(buffer + 32, wordSize);
+		WRITE_BE_UINT32(buffer + 36, sampleRate);
+		WRITE_BE_UINT32(buffer + 40, numChannels);
+		memcpy(buffer + 44, "REGN", 4);
+		WRITE_BE_UINT32(buffer + 48, 8);
+		WRITE_BE_UINT32(buffer + 52, 80);
+		WRITE_BE_UINT32(buffer + 56, regionLength);
+		memcpy(buffer + 60, "STOP", 4);
+		WRITE_BE_UINT32(buffer + 64, 4);
+		WRITE_BE_UINT32(buffer + 68, regionLength + 80);
+		memcpy(buffer + 72, "DATA", 4);
+		WRITE_BE_UINT32(buffer + 76, regionLength);
+		return 80;
+	}
+
+	return 0;
+}
+
 } // End of namespace Grim


Commit: 8555512555ee067f5894439ce1f2027fe983271c
    https://github.com/scummvm/scummvm/commit/8555512555ee067f5894439ce1f2027fe983271c
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Change some allocation sizes to match the original

Changed paths:
    engines/grim/imuse/dimuse_defs.h
    engines/grim/imuse/dimuse_engine.cpp


diff --git a/engines/grim/imuse/dimuse_defs.h b/engines/grim/imuse/dimuse_defs.h
index ad7c05c6c8c..084b79a538f 100644
--- a/engines/grim/imuse/dimuse_defs.h
+++ b/engines/grim/imuse/dimuse_defs.h
@@ -32,19 +32,20 @@ namespace Grim {
 #define DIMUSE_MAX_FADES       16
 #define DIMUSE_MAX_TRIGGERS    8
 #define DIMUSE_MAX_DEFERS      8
-#define DIMUSE_MAX_TRACKS      8
+#define DIMUSE_MAX_TRACKS      9
 #define DIMUSE_MAX_MAP_SIZE    512
-#define DIMUSE_MAX_DISPATCHES  8
+#define DIMUSE_MAX_DISPATCHES  9
 #define DIMUSE_MAX_STREAMZONES 50
 #define DIMUSE_MAX_FADE_VOLUME 8323072
 #define DIMUSE_MAX_STREAMS     3
 #define DIMUSE_MAX_SOUND_LIST  10
 #define DIMUSE_MAX_OPEN_FILES  5
 #define DIMUSE_MAX_CACHED_SOUNDS 32
+#define DIMUSE_SOUNDS_MEMORY_LIMIT 300000
 
 #define DIMUSE_LARGE_FADES    1
-#define DIMUSE_SMALL_FADES    4
-#define DIMUSE_LARGE_FADE_DIM 350000
+#define DIMUSE_SMALL_FADES    2
+#define DIMUSE_LARGE_FADE_DIM 100000
 #define DIMUSE_SMALL_FADE_DIM 44100
 
 #define DIMUSE_BASE_SAMPLERATE 22050
diff --git a/engines/grim/imuse/dimuse_engine.cpp b/engines/grim/imuse/dimuse_engine.cpp
index cf2efab9313..42bfc69b044 100644
--- a/engines/grim/imuse/dimuse_engine.cpp
+++ b/engines/grim/imuse/dimuse_engine.cpp
@@ -93,8 +93,8 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 	vimaInit(_imuseDestTable);
 
 	diMUSEInitialize();
-	soundsAllocateBuffer(DIMUSE_BUFFER_MUSIC, 528000, 44000, 352000);
-	soundsAllocateBuffer(DIMUSE_BUFFER_SPEECH, 176000, 44000, 88000);
+	soundsAllocateBuffer(DIMUSE_BUFFER_MUSIC, 440000, 44000, 352000);
+	soundsAllocateBuffer(DIMUSE_BUFFER_SPEECH, 88000, 44000, 88000);
 	diMUSEInitializeScript();
 
 	if (_mixer->getOutputBufSize() != 0) {


Commit: 918f8d4cabb9cc2141d96a2e648ac4554101b635
    https://github.com/scummvm/scummvm/commit/918f8d4cabb9cc2141d96a2e648ac4554101b635
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Port voice and lipsync routines

Changed paths:
    engines/grim/imuse/dimuse_defs.h
    engines/grim/imuse/dimuse_dispatch.cpp
    engines/grim/imuse/dimuse_engine.cpp
    engines/grim/imuse/dimuse_engine.h
    engines/grim/imuse/dimuse_files.cpp


diff --git a/engines/grim/imuse/dimuse_defs.h b/engines/grim/imuse/dimuse_defs.h
index 084b79a538f..58b1731ecfe 100644
--- a/engines/grim/imuse/dimuse_defs.h
+++ b/engines/grim/imuse/dimuse_defs.h
@@ -42,6 +42,9 @@ namespace Grim {
 #define DIMUSE_MAX_OPEN_FILES  5
 #define DIMUSE_MAX_CACHED_SOUNDS 32
 #define DIMUSE_SOUNDS_MEMORY_LIMIT 300000
+#define DIMUSE_MAX_LIPSYNCS    4
+#define DIMUSE_LIPSYNC_MAX_SIZE 2000
+#define DIMUSE_PHONEME_NONE    95
 
 #define DIMUSE_LARGE_FADES    1
 #define DIMUSE_SMALL_FADES    2
diff --git a/engines/grim/imuse/dimuse_dispatch.cpp b/engines/grim/imuse/dimuse_dispatch.cpp
index 7495cabc078..60cf929bdcd 100644
--- a/engines/grim/imuse/dimuse_dispatch.cpp
+++ b/engines/grim/imuse/dimuse_dispatch.cpp
@@ -754,8 +754,11 @@ int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
 
 int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
 	int32 *dstMap;
-	uint8 *rawMap, *copiedBuf, *soundAddrData;
+	uint8 *rawMap, *copiedBuf, *soundAddrData, *extFrmtBufPtr;
+	uint8 bufferHeader[80];
 	int32 size;
+	int32 curChunkPos = 0;
+	int targetSampleRate, targetNumChannels;
 
 	dstMap = dispatchPtr->map;
 
@@ -775,7 +778,23 @@ int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
 				return -3;
 			}
 
-			if (READ_BE_UINT32(copiedBuf) == MKTAG('i', 'M', 'U', 'S') && READ_BE_UINT32(copiedBuf + 8) == MKTAG('M', 'A', 'P', ' ')) {
+			if (!memcmp(copiedBuf, "RIFF", 4) && !memcmp(copiedBuf + 8, "WAVEfmt ", 8)) {
+				// A WAV file: build an iMUS map for it on the fly
+				extFrmtBufPtr = soundsGetExtFormatBuffer(copiedBuf, nullptr, &targetSampleRate, nullptr, &targetNumChannels, nullptr, &curChunkPos);
+				if (!extFrmtBufPtr) {
+					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: couldn't find the data chunk of the WAV file");
+					return -1;
+				}
+
+				dispatchPtr->currentOffset = extFrmtBufPtr - copiedBuf;
+				if (!streamerGetStreamBuffer(dispatchPtr->streamPtr, extFrmtBufPtr - copiedBuf)) {
+					return -1;
+				}
+
+				createSoundHeader(bufferHeader, 3, targetSampleRate, 16, targetNumChannels, curChunkPos);
+				bufferHeader[31] = 1;
+				rawMap = bufferHeader;
+			} else if (READ_BE_UINT32(copiedBuf) == MKTAG('i', 'M', 'U', 'S') && READ_BE_UINT32(copiedBuf + 8) == MKTAG('M', 'A', 'P', ' ')) {
 				size = READ_BE_UINT32(copiedBuf + 12) + 24;
 				if (!streamerGetStreamBufferAtOffset(dispatchPtr->streamPtr, 0, size)) {
 					return -3;
@@ -787,38 +806,45 @@ int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
 				}
 
 				dispatchPtr->currentOffset = size;
-				if (dispatchConvertMap(rawMap + 8, dstMap)) {
-					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: dispatchConvertMap() failed");
-					return -1;
-				}
+			} else {
+				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: unrecognized file format in stream buffer");
+				return -1;
+			}
 
-				if (dispatchPtr->map[2] != MKTAG('F', 'R', 'M', 'T')) {
-					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected 'FRMT' at start of map");
+			if (dispatchConvertMap(rawMap + 8, dstMap)) {
+				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: dispatchConvertMap() failed");
+				return -1;
+			}
+
+			if (curChunkPos) {
+				dispatchPtr->map[4] = dispatchPtr->currentOffset;
+				dispatchPtr->map[11] = dispatchPtr->currentOffset;
+				dispatchPtr->map[15] = dispatchPtr->currentOffset + curChunkPos;
+			}
+
+			if (dispatchPtr->map[2] != MKTAG('F', 'R', 'M', 'T')) {
+				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected 'FRMT' at start of map");
+				return -1;
+			}
+
+			if (dispatchPtr->map[4] != dispatchPtr->currentOffset) {
+				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected data to follow map");
+				return -1;
+			} else {
+				if (dispatchPtr->streamZoneList) {
+					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected NULL streamZoneList");
 					return -1;
 				}
 
-				if (dispatchPtr->map[4] != dispatchPtr->currentOffset) {
-					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected data to follow map");
+				dispatchPtr->streamZoneList = dispatchAllocateStreamZone();
+				if (!dispatchPtr->streamZoneList) {
+					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: couldn't allocate zone");
 					return -1;
-				} else {
-					if (dispatchPtr->streamZoneList) {
-						debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected NULL streamZoneList");
-						return -1;
-					}
-
-					dispatchPtr->streamZoneList = dispatchAllocateStreamZone();
-					if (!dispatchPtr->streamZoneList) {
-						debug(5, "IMuseDigital::dispatchGetMap(): ERROR: couldn't allocate zone");
-						return -1;
-					}
-
-					dispatchPtr->streamZoneList->offset = dispatchPtr->currentOffset;
-					dispatchPtr->streamZoneList->size = streamerGetFreeBufferAmount(dispatchPtr->streamPtr);
-					dispatchPtr->streamZoneList->fadeFlag = 0;
 				}
-			} else {
-				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: unrecognized file format in stream buffer");
-				return -1;
+
+				dispatchPtr->streamZoneList->offset = dispatchPtr->currentOffset;
+				dispatchPtr->streamZoneList->size = streamerGetFreeBufferAmount(dispatchPtr->streamPtr);
+				dispatchPtr->streamZoneList->fadeFlag = 0;
 			}
 
 		} else {
diff --git a/engines/grim/imuse/dimuse_engine.cpp b/engines/grim/imuse/dimuse_engine.cpp
index 42bfc69b044..e21e2ae568d 100644
--- a/engines/grim/imuse/dimuse_engine.cpp
+++ b/engines/grim/imuse/dimuse_engine.cpp
@@ -90,6 +90,11 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 	_currentSoundSlot = 0;
 	memset(_openAudioFiles, 0, sizeof(_openAudioFiles));
 	memset(_soundBuffers, 0, sizeof(_soundBuffers));
+	memset(_lipsyncSoundIds, 0, sizeof(_lipsyncSoundIds));
+	memset(_lipsyncBufs, 0, sizeof(_lipsyncBufs));
+	_curSpeechFile[0] = '\0';
+	_millisecsInCurSpeechFile = 0;
+	_globalVolume = 0;
 	vimaInit(_imuseDestTable);
 
 	diMUSEInitialize();
@@ -335,10 +340,10 @@ int32 IMuseDigital::getSoundElapsedTimeInMs(int soundId) {
 void IMuseDigital::pause(bool p) {
 	if (p) {
 		debug(5, "IMuseDigital::pause(): pausing...");
-		diMUSEPause();
+		soundsPause();
 	} else {
 		debug(5, "IMuseDigital::pause(): resuming...");
-		diMUSEResume();
+		soundsResume();
 	}
 }
 
@@ -543,10 +548,7 @@ int IMuseDigital::diMUSEDeferCommand(int count, int opcode, int c, int d, int e,
 }
 
 int IMuseDigital::diMUSEStartStream(int soundId, int priority, int bufferId) {
-	// TODO
-	// if (!filesCheckRange(soundId))
-	// 	return -1;
-	if (soundId == 0)
+	if (!filesCheckRange(soundId))
 		return -1;
 
 	Common::StackLock lock(*_mutex);
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/dimuse_engine.h
index 01d7d773dab..1d1c3a00259 100644
--- a/engines/grim/imuse/dimuse_engine.h
+++ b/engines/grim/imuse/dimuse_engine.h
@@ -270,6 +270,20 @@ private:
 	int soundsGetCompBlockId(IMuseDigiResource *res, int32 offset);
 	int32 copyDataFromResource(IMuseDigiResource *res, uint8 *dest, int32 size);
 
+	// Voice and lipsync
+	char _curSpeechFile[32];
+	int32 _millisecsInCurSpeechFile;
+	int _lipsyncSoundIds[DIMUSE_MAX_LIPSYNCS];
+	uint8 _lipsyncBufs[DIMUSE_MAX_LIPSYNCS][DIMUSE_LIPSYNC_MAX_SIZE + 48];
+	int _globalVolume;
+
+	int soundsRegisterVoice(const char *filename);
+	void soundsCloseVoiceFile();
+	void soundsReOpenVoiceFile();
+	int loadLip(const char *lipsyncFilename, int soundId);
+	void soundsResetLipsyncState(int soundId);
+	int soundsGetPhoneme(int soundId, int offset);
+
 	// Waveapi
 	waveOutParamsStruct waveOutSettings;
 
@@ -325,6 +339,25 @@ public:
 	int32 getCurMusicPosInMs();
 	int32 getSoundElapsedTimeInMs(int soundId);
 
+	// Sounds API
+	int soundsLoadStartSound(const char *soundName, int priority, int group);
+	int soundsLoadProcessStartSound(const char *soundName, int priority, int group);
+	void soundsStopSound(const char *soundName);
+	int soundsGetParam(const char *soundName, int paramId);
+	void soundsSetParam(const char *soundName, int paramId, int value);
+	int soundsFadeParam(const char *soundName, int paramId, int value, int length);
+	bool soundsIsSoundInUse(const char *soundName);
+	bool soundsIsSoundPlaying(const char *soundName);
+	int iMUSESetHook(const char *soundName, int hookId);
+	int iMUSEGetHook(const char *soundName);
+	void soundsPeriodic();
+	int soundsPause();
+	int soundsResume();
+	int soundStartVoiceStream(const char *filename, int volume, int pan);
+	int soundStopVoiceStream();
+	int soundGetVoiceTime();
+	int iMUSEGetPhoneme(int lipsyncId, int offset);
+
 	// Called by the Groups module
 	void tracksSetGroupVol();
 
@@ -353,7 +386,7 @@ public:
 	int diMUSEClearTrigger(int soundId, const char *marker, int opcode);
 	int diMUSEDeferCommand(int count, int opcode, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n);
 
-	int diMUSEStartStream(int soundId, int priority, int groupId);
+	int diMUSEStartStream(int soundId, int priority, int bufferId);
 	int diMUSESwitchStream(int oldSoundId, int newSoundId, int fadeDelay, int fadeSyncFlag2, int fadeSyncFlag1);
 	int diMUSEProcessStreams();
 	int diMUSEQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
diff --git a/engines/grim/imuse/dimuse_files.cpp b/engines/grim/imuse/dimuse_files.cpp
index 2c67309ae83..5507c8e29d0 100644
--- a/engines/grim/imuse/dimuse_files.cpp
+++ b/engines/grim/imuse/dimuse_files.cpp
@@ -867,8 +867,13 @@ int IMuseDigital::cacheGetSoundId(const char *soundName) {
 
 	sound->tsOfAllocation = g_system->getMillis();
 
-	// TODO
-	// Lipsync registration for the ".lip" file with the same name
+	char lipsyncFilename[32];
+	Common::strlcpy(lipsyncFilename, sound->soundFilename, sizeof(lipsyncFilename));
+	char *extension = strrchr(lipsyncFilename, '.');
+	if (extension) {
+		Common::strlcpy(extension, ".lip", lipsyncFilename + sizeof(lipsyncFilename) - extension);
+		loadLip(lipsyncFilename, sound->luaSoundId);
+	}
 
 	soundsFileSeek(res, 0, SEEK_END);
 	sound->uncompResourceSize = soundsFileTell(res);
@@ -923,10 +928,7 @@ int IMuseDigital::cacheGetSoundId(const char *soundName) {
 	}
 
 	free(sound->soundUncompData);
-
-	// TODO
-	// Reset the lipsync state for this sound
-
+	soundsResetLipsyncState(sound->luaSoundId);
 	memset(sound, 0, sizeof(IMuseDigiCachedSound));
 	return 0;
 }
@@ -954,9 +956,7 @@ int IMuseDigital::cachePurgeOldestStoppedSound() {
 	if (foundSlot >= 0) {
 		IMuseDigiCachedSound *sound = &_soundCache[foundSlot];
 		sound->soundFilename[0] = 0;
-
-		// TODO
-		// Reset the lipsync state for this sound
+		soundsResetLipsyncState(sound->luaSoundId);
 
 		free(sound->soundUncompData);
 		memset(sound, 0, sizeof(IMuseDigiCachedSound));
@@ -969,9 +969,7 @@ int IMuseDigital::cachePurgeOldestStoppedSound() {
 void IMuseDigital::cacheReset() {
 	for (int slot = DIMUSE_MAX_CACHED_SOUNDS - 1; slot >= 0; slot--) {
 		if (_soundCache[slot].soundUncompData) {
-			// TODO
-			// Reset the lipsync state for this sound
-
+			soundsResetLipsyncState(_soundCache[slot].luaSoundId);
 			free(_soundCache[slot].soundUncompData);
 		}
 	}
@@ -1155,4 +1153,300 @@ int IMuseDigital::createSoundHeader(uint8 *buffer, int mode, int sampleRate, int
 	return 0;
 }
 
+int IMuseDigital::soundsLoadStartSound(const char *soundName, int priority, int group) {
+	int soundId = cacheGetSoundId(soundName);
+	if (!soundId)
+		return 0;
+
+	if (priority > 124)
+		priority = 124;
+
+	diMUSEStartSound(soundId, priority);
+	diMUSESetParam(soundId, DIMUSE_P_GROUP, group);
+	_soundCache[soundId - 100].priority = priority;
+	return _soundCache[soundId - 100].luaSoundId;
+}
+
+int IMuseDigital::soundsLoadProcessStartSound(const char *soundName, int priority, int group) {
+	int soundId = cacheGetSoundId(soundName);
+	if (!soundId)
+		return 0;
+
+	if (priority > 124)
+		priority = 124;
+
+	// TODO
+	// If a voice effect is active (curEffectId), AllocateProcessedSound() the sound before starting it (hmiFX)
+
+	diMUSEStartSound(soundId, priority);
+	diMUSESetParam(soundId, DIMUSE_P_GROUP, group);
+	_soundCache[soundId - 100].priority = priority;
+	return _soundCache[soundId - 100].luaSoundId;
+}
+
+void IMuseDigital::soundsStopSound(const char *soundName) {
+	int soundId = cacheGetSoundId(soundName);
+	if (soundId)
+		diMUSEStopSound(soundId);
+}
+
+int IMuseDigital::soundsGetParam(const char *soundName, int paramId) {
+	int soundId = cacheGetSoundId(soundName);
+	if (soundId)
+		return diMUSEGetParam(soundId, paramId);
+
+	return 1;
+}
+
+void IMuseDigital::soundsSetParam(const char *soundName, int paramId, int value) {
+	int soundId = cacheGetSoundId(soundName);
+	if (soundId)
+		diMUSESetParam(soundId, paramId, value);
+}
+
+int IMuseDigital::soundsFadeParam(const char *soundName, int paramId, int value, int length) {
+	int soundId = cacheGetSoundId(soundName);
+	if (soundId)
+		return diMUSEFadeParam(soundId, paramId, value, 60 * length / 1000);
+
+	return 1;
+}
+
+bool IMuseDigital::soundsIsSoundInUse(const char *soundName) {
+	uint32 soundIndex = cacheGetSoundId(soundName) - 100;
+	if (soundIndex >= DIMUSE_MAX_CACHED_SOUNDS || !_soundCache[soundIndex].soundFilename[0] || !_soundCache[soundIndex].soundUncompData)
+		return false;
+
+	int soundId = soundIndex + 100;
+	return diMUSEGetParam(soundId, DIMUSE_P_SND_TRACK_NUM) > 0 || diMUSEGetParam(soundId, DIMUSE_P_TRIGS_SNDS) > 0;
+}
+
+bool IMuseDigital::soundsIsSoundPlaying(const char *soundName) {
+	int soundId = cacheGetSoundId(soundName);
+	return diMUSEGetParam(soundId, DIMUSE_P_SND_TRACK_NUM) > 0;
+}
+
+int IMuseDigital::iMUSESetHook(const char *soundName, int hookId) {
+	int soundId = cacheGetSoundId(soundName);
+	if (soundId)
+		return diMUSESetHook(soundId, hookId);
+
+	return -1;
+}
+
+int IMuseDigital::iMUSEGetHook(const char *soundName) {
+	int soundId = cacheGetSoundId(soundName);
+	if (soundId)
+		return diMUSEGetHook(soundId);
+
+	return -1;
+}
+
+void IMuseDigital::soundsPeriodic() {
+	int32 cachedSize = 0;
+
+	diMUSEProcessStreams();
+	diMUSERefreshScript();
+
+	for (int slot = DIMUSE_MAX_CACHED_SOUNDS - 1; slot >= 0; slot--) {
+		if (_soundCache[slot].soundFilename[0] && _soundCache[slot].soundUncompData)
+			cachedSize += _soundCache[slot].uncompResourceSize;
+	}
+
+	if (cachedSize > DIMUSE_SOUNDS_MEMORY_LIMIT)
+		cachePurgeOldestStoppedSound();
+}
+
+int IMuseDigital::soundsPause() {
+	diMUSEPause();
+	_globalVolume = diMUSESetGroupVol(0, -1);
+	diMUSESetGroupVol(0, 0);
+	diMUSESetAttribute(-1, 0);
+	return 0;
+}
+
+int IMuseDigital::soundsResume() {
+	diMUSESetGroupVol(0, _globalVolume);
+	diMUSEResume();
+	diMUSESetAttribute(-1, 1);
+	return 0;
+}
+
+int IMuseDigital::soundsRegisterVoice(const char *filename) {
+	char lipsyncFilename[32];
+
+	Common::strlcpy(_curSpeechFile, filename, sizeof(_curSpeechFile));
+	Common::strlcpy(lipsyncFilename, filename, sizeof(lipsyncFilename));
+
+	char *extension = strrchr(lipsyncFilename, '.');
+	if (extension) {
+		Common::strlcpy(extension, ".lip", lipsyncFilename + sizeof(lipsyncFilename) - extension);
+		loadLip(lipsyncFilename, kTalkSoundID);
+	}
+
+	IMuseDigiResource *res = soundsOpenFile(filename);
+	_openAudioFiles[0].resourcePtr = res;
+	if (!res) {
+		_millisecsInCurSpeechFile = 0;
+		return 0;
+	}
+
+	soundsFileSeek(res, 0, SEEK_END);
+	int dataSamplesInFile = soundsFileTell(res) - 44;
+	soundsFileSeek(res, 0, SEEK_SET);
+	_millisecsInCurSpeechFile = 10 * dataSamplesInFile / 441;
+	return 1;
+}
+
+void IMuseDigital::soundsCloseVoiceFile() {
+	if (_openAudioFiles[0].resourcePtr) {
+		soundsCloseFile(_openAudioFiles[0].resourcePtr);
+		soundsResetLipsyncState(kTalkSoundID);
+		_openAudioFiles[0].resourcePtr = nullptr;
+	}
+}
+
+void IMuseDigital::soundsReOpenVoiceFile() {
+	soundsCloseVoiceFile();
+	if (_curSpeechFile[0])
+		soundsRegisterVoice(_curSpeechFile);
+}
+
+int IMuseDigital::soundStartVoiceStream(const char *filename, int volume, int pan) {
+	diMUSEStopSound(kTalkSoundID);
+	soundsCloseVoiceFile();
+	if (!soundsRegisterVoice(filename))
+		return 1;
+
+	fillStreamsWhileMusicCritical(5);
+	diMUSEStartStream(kTalkSoundID, 127, DIMUSE_BUFFER_SPEECH);
+	diMUSESetParam(kTalkSoundID, DIMUSE_P_GROUP, DIMUSE_GROUP_SPEECH);
+	diMUSESetParam(kTalkSoundID, DIMUSE_P_VOLUME, volume);
+	diMUSESetParam(kTalkSoundID, DIMUSE_P_PAN, pan);
+	diMUSEProcessStreams();
+	diMUSEProcessStreams();
+	return 0;
+}
+
+int IMuseDigital::soundStopVoiceStream() {
+	diMUSEStopSound(kTalkSoundID);
+	return ihostCloseSound(kTalkSoundID);
+}
+
+int IMuseDigital::soundGetVoiceTime() {
+	return diMUSEGetParam(kTalkSoundID, DIMUSE_P_SND_POS_IN_MS);
+}
+
+int IMuseDigital::loadLip(const char *lipsyncFilename, int soundId) {
+	Common::String lowerName(lipsyncFilename);
+	lowerName.toLowercase();
+
+	Common::SeekableReadStream *lipsyncFile = g_resourceloader->openNewStreamFile(lowerName.c_str());
+	if (!lipsyncFile) {
+		soundsResetLipsyncState(soundId);
+		return 0;
+	}
+
+	if (!soundId) {
+		delete lipsyncFile;
+		return 0;
+	}
+
+	for (int i = 1; i < DIMUSE_MAX_LIPSYNCS; i++) {
+		if (soundId == _lipsyncSoundIds[i]) {
+			delete lipsyncFile;
+			return 1;
+		}
+	}
+
+	int slot = -1;
+	if (soundId == kTalkSoundID) {
+		slot = 0;
+	} else {
+		for (int i = 1; i < DIMUSE_MAX_LIPSYNCS; i++) {
+			if (!_lipsyncSoundIds[i]) {
+				slot = i;
+				break;
+			}
+		}
+	}
+
+	if (slot >= 0) {
+		_lipsyncSoundIds[slot] = soundId;
+
+		int fileSize = lipsyncFile->size();
+		if (fileSize <= DIMUSE_LIPSYNC_MAX_SIZE) {
+			lipsyncFile->read(_lipsyncBufs[slot], fileSize);
+
+			if (memcmp(_lipsyncBufs[slot], "LIP!", 4))
+				_lipsyncSoundIds[slot] = 0;
+		}
+	}
+
+	delete lipsyncFile;
+	return 0;
+}
+
+void IMuseDigital::soundsResetLipsyncState(int soundId) {
+	for (int i = 0; i < DIMUSE_MAX_LIPSYNCS; i++) {
+		if (soundId == _lipsyncSoundIds[i])
+			_lipsyncSoundIds[i] = 0;
+	}
+}
+
+int IMuseDigital::soundsGetPhoneme(int soundId, int offset) {
+	uint8 *lipsyncBuffer;
+
+	if (soundId == kTalkSoundID) {
+		if (!_lipsyncSoundIds[0])
+			return 0;
+
+		lipsyncBuffer = _lipsyncBufs[0];
+	} else if (soundId == _lipsyncSoundIds[1]) {
+		lipsyncBuffer = _lipsyncBufs[1];
+	} else if (soundId == _lipsyncSoundIds[2]) {
+		lipsyncBuffer = _lipsyncBufs[2];
+	} else if (soundId == _lipsyncSoundIds[3]) {
+		lipsyncBuffer = _lipsyncBufs[3];
+	} else {
+		return 0;
+	}
+
+	int numEntries = READ_LE_INT32(lipsyncBuffer + 4);
+	int offset16MsTicks = offset >> 4;
+	uint8 *entry = lipsyncBuffer + 8;
+
+	for (int i = 0; i < numEntries; i++) {
+		if (offset16MsTicks < READ_LE_INT16(entry))
+			break;
+
+		if (offset16MsTicks < READ_LE_INT16(entry + 4))
+			return READ_LE_INT16(entry + 2);
+
+		entry += 4;
+	}
+
+	return DIMUSE_PHONEME_NONE;
+}
+
+int IMuseDigital::iMUSEGetPhoneme(int lipsyncId, int offset) {
+	if (lipsyncId == _lipsyncSoundIds[0])
+		return soundsGetPhoneme(lipsyncId, offset + soundGetVoiceTime());
+
+	if (lipsyncId == _lipsyncSoundIds[1] || lipsyncId == _lipsyncSoundIds[2] || lipsyncId == _lipsyncSoundIds[3]) {
+		int soundId = 0;
+		for (int slot = 0; slot < DIMUSE_MAX_CACHED_SOUNDS && !soundId; slot++) {
+			if (_soundCache[slot].luaSoundId == lipsyncId)
+				soundId = slot + 100;
+		}
+
+		if (!soundId)
+			return 0;
+
+		return soundsGetPhoneme(lipsyncId, offset + diMUSEGetParam(soundId, DIMUSE_P_SND_POS_IN_MS));
+	}
+
+	return 0;
+}
+
 } // End of namespace Grim


Commit: 43f4d4527adc8ef5ec5b54e424f67bcb62881fbd
    https://github.com/scummvm/scummvm/commit/43f4d4527adc8ef5ec5b54e424f67bcb62881fbd
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Port HMIFX DSP effects usage

Changed paths:
  A engines/grim/imuse/dimuse_hmi.cpp
    engines/grim/imuse/dimuse_defs.h
    engines/grim/imuse/dimuse_engine.cpp
    engines/grim/imuse/dimuse_engine.h
    engines/grim/imuse/dimuse_files.cpp
    engines/grim/module.mk


diff --git a/engines/grim/imuse/dimuse_defs.h b/engines/grim/imuse/dimuse_defs.h
index 58b1731ecfe..f5b9988845b 100644
--- a/engines/grim/imuse/dimuse_defs.h
+++ b/engines/grim/imuse/dimuse_defs.h
@@ -45,6 +45,8 @@ namespace Grim {
 #define DIMUSE_MAX_LIPSYNCS    4
 #define DIMUSE_LIPSYNC_MAX_SIZE 2000
 #define DIMUSE_PHONEME_NONE    95
+#define DIMUSE_HMI_HEAP_SIZE   150000
+#define DIMUSE_HMI_TAIL_SIZE   18000
 
 #define DIMUSE_LARGE_FADES    1
 #define DIMUSE_SMALL_FADES    2
diff --git a/engines/grim/imuse/dimuse_engine.cpp b/engines/grim/imuse/dimuse_engine.cpp
index e21e2ae568d..bca814a4e2b 100644
--- a/engines/grim/imuse/dimuse_engine.cpp
+++ b/engines/grim/imuse/dimuse_engine.cpp
@@ -28,6 +28,8 @@
 
 #include "engines/grim/movie/codecs/vima.h"
 
+#include "audio/effects/hmi/hmifxlib.h"
+
 #include "audio/audiostream.h"
 #include "audio/mixer.h"
 
@@ -97,6 +99,25 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 	_globalVolume = 0;
 	vimaInit(_imuseDestTable);
 
+	_hmiFxLib = new Audio::HMIFxLib();
+	memset(&_hmiInitData, 0, sizeof(_hmiInitData));
+	memset(&_hmiRequest, 0, sizeof(_hmiRequest));
+	memset(&_hmiInputFmt, 0, sizeof(_hmiInputFmt));
+	memset(&_hmiOutputFmt, 0, sizeof(_hmiOutputFmt));
+	_presetCollection = nullptr;
+	_loadedPreset = nullptr;
+	_hmiFxInitialized = false;
+	_curHMIEffectIdInternal = 0;
+	_curEffectId = 0;
+	_curEffectName[0] = '\0';
+	_voiceSrcBuf = nullptr;
+	_maxChunkRequested = 0;
+	_voiceRemainderBuf = nullptr;
+	_voiceRemainderSize = 0;
+	_voiceRemainderCapacity = 0;
+	_voiceRemainderPos = 0;
+	setupHMI(DIMUSE_HMI_HEAP_SIZE);
+
 	diMUSEInitialize();
 	soundsAllocateBuffer(DIMUSE_BUFFER_MUSIC, 440000, 44000, 352000);
 	soundsAllocateBuffer(DIMUSE_BUFFER_SPEECH, 88000, 44000, 88000);
@@ -134,6 +155,15 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 IMuseDigital::~IMuseDigital() {
 	g_system->getTimerManager()->removeTimerProc(timer_handler);
 	diMUSETerminateScript();
+
+	soundsTerminateProcessing();
+	free(_voiceSrcBuf);
+	_voiceSrcBuf = nullptr;
+	_maxChunkRequested = 0;
+	free(_voiceRemainderBuf);
+	_voiceRemainderBuf = nullptr;
+	delete _hmiFxLib;
+
 	diMUSETerminate();
 
 	cacheReset();
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/dimuse_engine.h
index 1d1c3a00259..be071cab9a6 100644
--- a/engines/grim/imuse/dimuse_engine.h
+++ b/engines/grim/imuse/dimuse_engine.h
@@ -38,9 +38,11 @@
 
 #include "audio/mixer.h"
 #include "audio/decoders/raw.h"
+#include "audio/effects/hmi/hmi_types.h"
 
 namespace Audio {
 class AudioStream;
+class HMIFxLib;
 class Mixer;
 class QueuingAudioStream;
 }
@@ -284,6 +286,31 @@ private:
 	void soundsResetLipsyncState(int soundId);
 	int soundsGetPhoneme(int soundId, int offset);
 
+	// HMI voice effects
+	Audio::HMIFxLib *_hmiFxLib;
+	Audio::HMIInitData _hmiInitData;
+	Audio::HMILibrary *_presetCollection;
+	Audio::HMIProcessRequest _hmiRequest;
+	Audio::HMIPreset *_loadedPreset;
+	Audio::HMIFormat _hmiInputFmt;
+	Audio::HMIFormat _hmiOutputFmt;
+	bool _hmiFxInitialized;
+	int _curHMIEffectIdInternal;
+	int _curEffectId;
+	char _curEffectName[40];
+	uint8 *_voiceSrcBuf;
+	int32 _maxChunkRequested;
+	uint8 *_voiceRemainderBuf;
+	int32 _voiceRemainderSize;
+	int32 _voiceRemainderCapacity;
+	int32 _voiceRemainderPos;
+
+	int setupHMI(int heapSize);
+	int registerHMIEffect(const char *effectName);
+	int processSound(uint8 *srcBuf, uint32 soundLength, uint8 *destBuf, uint8 **outBuf, int32 *outLength, bool isLastChunk);
+	void soundsTerminateProcessing();
+	void allocateProcessedSound(int luaSoundId);
+
 	// Waveapi
 	waveOutParamsStruct waveOutSettings;
 
@@ -350,6 +377,7 @@ public:
 	bool soundsIsSoundPlaying(const char *soundName);
 	int iMUSESetHook(const char *soundName, int hookId);
 	int iMUSEGetHook(const char *soundName);
+	void iMUSESetVoiceEffect(const char *effectName);
 	void soundsPeriodic();
 	int soundsPause();
 	int soundsResume();
diff --git a/engines/grim/imuse/dimuse_files.cpp b/engines/grim/imuse/dimuse_files.cpp
index 5507c8e29d0..0aa0ebe2334 100644
--- a/engines/grim/imuse/dimuse_files.cpp
+++ b/engines/grim/imuse/dimuse_files.cpp
@@ -508,7 +508,19 @@ int IMuseDigital::ihostFseek(int soundId, int32 offset, int mode) {
 		IMuseDigiResource *res = _openAudioFiles[soundId - 10000].resourcePtr;
 		if (res) {
 			soundsFileSeek(res, offset, mode);
-			return soundsFileTell(res);
+
+			if (soundId == kTalkSoundID && _curEffectId && mode == SEEK_END)
+				return _curEffectId * (soundsFileTell(res) + DIMUSE_HMI_TAIL_SIZE - 44) + 44;
+
+			if (soundId != kTalkSoundID || !_curEffectId || mode != SEEK_SET)
+				return soundsFileTell(res);
+
+			int32 dryOffset = offset;
+			if (offset > 44)
+				dryOffset = (offset - 44) / _curEffectId + 44;
+
+			soundsFileSeek(res, dryOffset, SEEK_SET);
+			return offset;
 		}
 	}
 
@@ -522,10 +534,115 @@ int IMuseDigital::ihostRead(int soundId, uint8 *destBuf, int32 size) {
 	if (!res)
 		return 0;
 
-	// TODO
-	// Voice effects processing (hmiFX) for sound 10000
+	if (soundId != kTalkSoundID || !_curEffectId)
+		return copyDataFromResource(res, destBuf, size);
+
+	bool isLastChunk = false;
+	uint8 *effectBuf = nullptr;
+	int32 effectSize = 0;
+
+	int32 curPos = soundsFileTell(res);
+	soundsFileSeek(res, 0, SEEK_END);
+	int32 fileSize = soundsFileTell(res);
+	soundsFileSeek(res, curPos, SEEK_SET);
+
+	if (_maxChunkRequested < size) {
+		free(_voiceSrcBuf);
+		_voiceSrcBuf = (uint8 *)malloc(size);
+		_maxChunkRequested = size;
+	}
+
+	// Past the end of the original file we only serve the tail of the effect
+	if (curPos >= fileSize) {
+		if (!_voiceRemainderSize) {
+			memset(destBuf, 0, size);
+			return size;
+		}
+
+		int32 copySize = MIN(_voiceRemainderSize - _voiceRemainderPos, size);
+		memcpy(destBuf, _voiceRemainderBuf + _voiceRemainderPos, copySize);
+		_voiceRemainderPos += copySize;
+
+		if (copySize < size)
+			memset(destBuf + copySize, 0, size - copySize);
+
+		return size;
+	}
+
+	if (!curPos) {
+		// The first chunk starts with the WAV header, which gets adapted to the processed audio
+		int32 dataSize = size - 44;
+		int32 readSize = copyDataFromResource(res, _voiceSrcBuf, dataSize / _curEffectId + 44);
+		if (soundsFileTell(res) >= fileSize)
+			isLastChunk = true;
+
+		memcpy(destBuf, _voiceSrcBuf, 44);
+		WRITE_LE_UINT32(destBuf + 40, (DIMUSE_HMI_TAIL_SIZE + READ_LE_UINT32(destBuf + 40)) * _curEffectId);
+		WRITE_LE_UINT32(destBuf + 28, READ_LE_UINT32(destBuf + 28) * _curEffectId);
+
+		if (_curEffectId > 1) {
+			destBuf[32] *= 2;
+			destBuf[22] *= 2;
+		}
+
+		processSound(_voiceSrcBuf + 44, readSize - 44, destBuf + 44, &effectBuf, &effectSize, isLastChunk);
+		if (isLastChunk && effectBuf) {
+			memcpy(destBuf + 44, effectBuf, MIN(dataSize, effectSize));
+
+			if (dataSize > effectSize)
+				memset(destBuf + 44 + effectSize, 0, dataSize - effectSize);
+
+			if (dataSize < effectSize) {
+				_voiceRemainderSize = effectSize - dataSize;
+				_voiceRemainderPos = 0;
+
+				if (_voiceRemainderSize > _voiceRemainderCapacity) {
+					free(_voiceRemainderBuf);
+					_voiceRemainderBuf = (uint8 *)malloc(_voiceRemainderSize);
+					_voiceRemainderCapacity = _voiceRemainderSize;
+				}
+
+				memcpy(_voiceRemainderBuf, effectBuf + dataSize, _voiceRemainderSize);
+			} else {
+				_voiceRemainderSize = 0;
+			}
+
+			free(effectBuf);
+		}
+
+		return size;
+	}
 
-	return copyDataFromResource(res, destBuf, size);
+	int32 readSize = copyDataFromResource(res, _voiceSrcBuf, size / _curEffectId);
+	if (soundsFileTell(res) >= fileSize)
+		isLastChunk = true;
+
+	processSound(_voiceSrcBuf, readSize, destBuf, &effectBuf, &effectSize, isLastChunk);
+	if (!isLastChunk || !effectBuf)
+		return size;
+
+	memcpy(destBuf, effectBuf, MIN(size, effectSize));
+
+	if (size > effectSize)
+		memset(destBuf + effectSize, 0, size - effectSize);
+
+	if (size < effectSize) {
+		_voiceRemainderSize = effectSize - size;
+		_voiceRemainderPos = 0;
+
+		if (_voiceRemainderSize > _voiceRemainderCapacity) {
+			free(_voiceRemainderBuf);
+			_voiceRemainderBuf = (uint8 *)malloc(_voiceRemainderSize);
+			_voiceRemainderCapacity = _voiceRemainderSize;
+		}
+
+		memcpy(_voiceRemainderBuf, effectBuf + size, _voiceRemainderSize);
+	} else {
+		_voiceRemainderSize = 0;
+	}
+
+	free(effectBuf);
+	return size;
 }
 
 void IMuseDigital::soundsAllocateBuffer(int bufferId, int32 bufSize, int32 loadSize, int32 criticalSize) {
@@ -1175,8 +1292,11 @@ int IMuseDigital::soundsLoadProcessStartSound(const char *soundName, int priorit
 	if (priority > 124)
 		priority = 124;
 
-	// TODO
-	// If a voice effect is active (curEffectId), AllocateProcessedSound() the sound before starting it (hmiFX)
+	if (_curEffectId) {
+		IMuseDigiCachedSound *sound = &_soundCache[soundId - 100];
+		if (sound->luaSoundId && !sound->flag)
+			allocateProcessedSound(sound->luaSoundId);
+	}
 
 	diMUSEStartSound(soundId, priority);
 	diMUSESetParam(soundId, DIMUSE_P_GROUP, group);
@@ -1242,6 +1362,57 @@ int IMuseDigital::iMUSEGetHook(const char *soundName) {
 	return -1;
 }
 
+void IMuseDigital::iMUSESetVoiceEffect(const char *effectName) {
+	Common::strlcpy(_curEffectName, effectName, sizeof(_curEffectName));
+
+	if (!_hmiFxInitialized || !scumm_stricmp(effectName, "OFF"))
+		_curEffectId = 0;
+	else
+		_curEffectId = registerHMIEffect(effectName);
+}
+
+void IMuseDigital::allocateProcessedSound(int luaSoundId) {
+	if (luaSoundId < 1111 || luaSoundId >= 1367)
+		return;
+
+	int slot = DIMUSE_MAX_CACHED_SOUNDS - 1;
+	while (_soundCache[slot].luaSoundId != luaSoundId) {
+		if (!slot--)
+			return;
+	}
+
+	IMuseDigiCachedSound *sound = &_soundCache[slot];
+	if (!sound->soundUncompData || !sound->soundAddrData)
+		return;
+
+	int sampleRate = 0, wordSize = 0, numChannels = 0, dataLength = 0;
+	soundsGetExtFormatBuffer(sound->soundMap, nullptr, &sampleRate, &wordSize, &numChannels, nullptr, &dataLength);
+
+	if (sampleRate == 22050 && wordSize == 16 && numChannels == 1 && dataLength > 0) {
+		uint8 *processedBuf = (uint8 *)malloc(2 * dataLength + 80);
+		if (processedBuf) {
+			int effectChannels = processSound(sound->soundAddrData + 80, dataLength, processedBuf, nullptr, nullptr, false);
+
+			free(sound->soundUncompData);
+			sound->soundUncompData = processedBuf;
+
+			int regionLength = dataLength;
+			if (effectChannels == 2)
+				regionLength *= 2;
+
+			sound->uncompResourceSize = regionLength;
+			createSoundHeader(&processedBuf[regionLength], 3, 22050, 16, effectChannels, regionLength);
+
+			sound->soundMap = &processedBuf[regionLength];
+			sound->soundMap[31] = 1;
+			sound->soundAddrData = processedBuf - 80;
+			sound->flag = 1;
+		}
+
+		sound->tsOfAllocation = g_system->getMillis();
+	}
+}
+
 void IMuseDigital::soundsPeriodic() {
 	int32 cachedSize = 0;
 
diff --git a/engines/grim/imuse/dimuse_hmi.cpp b/engines/grim/imuse/dimuse_hmi.cpp
new file mode 100644
index 00000000000..9aac9c156bf
--- /dev/null
+++ b/engines/grim/imuse/dimuse_hmi.cpp
@@ -0,0 +1,166 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "common/stream.h"
+
+#include "audio/effects/hmi/hmifxlib.h"
+
+#include "engines/grim/resource.h"
+#include "engines/grim/imuse/dimuse_engine.h"
+
+namespace Grim {
+
+int IMuseDigital::setupHMI(int heapSize) {
+	if (_hmiFxInitialized)
+		return 1;
+
+	memset(&_hmiInitData, 0, sizeof(_hmiInitData));
+	_hmiInitData.heapSize = heapSize;
+	if (_hmiFxLib->hmiFXInitSystem(&_hmiInitData))
+		return 0;
+
+	Common::SeekableReadStream *presetFile = g_resourceloader->openNewStreamFile("imuse.psl");
+	int loadResult = presetFile ? _hmiFxLib->hmiFXPresetLoadLibrary(&_presetCollection, *presetFile) : 1;
+	delete presetFile;
+
+	if (loadResult) {
+		_hmiFxLib->hmiFXUnInitSystem(&_hmiInitData);
+		return 0;
+	}
+
+	_hmiInputFmt.fmtBeginSection = 1;
+	_hmiInputFmt.numChannels = 1;
+	_hmiInputFmt.sampleRate = 22050;
+	_hmiInputFmt.bitsPerSample = 16;
+	_hmiInputFmt.blockAlign = 2;
+	_hmiInputFmt.byteRate = 44100;
+	_hmiInputFmt.fmtEndSection = 0;
+
+	_hmiOutputFmt.fmtBeginSection = 1;
+	_hmiOutputFmt.numChannels = 1;
+	_hmiOutputFmt.sampleRate = 22050;
+	_hmiOutputFmt.bitsPerSample = 16;
+	_hmiOutputFmt.blockAlign = 2;
+	_hmiOutputFmt.byteRate = 44100;
+	_hmiOutputFmt.fmtEndSection = 0;
+
+	// The original never sets this flag, so it never releases the library
+	_hmiFxInitialized = true;
+	return 1;
+}
+
+int IMuseDigital::registerHMIEffect(const char *effectName) {
+	if (_loadedPreset)
+		_hmiFxLib->hmiFXPresetRelease(_loadedPreset);
+
+	_hmiRequest.flags = HMI_PROCESS_LOOKUP_ONLY;
+	_hmiRequest.effectName = (char *)effectName;
+	if (_hmiFxLib->hmiFXPresetProcess(_presetCollection, &_hmiRequest)) {
+		_loadedPreset = nullptr;
+		_curHMIEffectIdInternal = _hmiOutputFmt.numChannels;
+		return 0;
+	}
+
+	_loadedPreset = _hmiRequest.presetPtr;
+
+	// The original reads an uninitialized value if the preset has no effects
+	uint32 channels = 1;
+	_hmiFxLib->hmiFXPresetGetRouting(_loadedPreset, &channels);
+
+	_curHMIEffectIdInternal = channels;
+	_hmiOutputFmt.blockAlign = 2 * channels;
+	_hmiOutputFmt.numChannels = channels;
+	_hmiOutputFmt.byteRate = 44100 * channels;
+	_hmiFxLib->hmiFXPresetLock(_loadedPreset);
+	return _curHMIEffectIdInternal;
+}
+
+int IMuseDigital::processSound(uint8 *srcBuf, uint32 soundLength, uint8 *destBuf, uint8 **outBuf, int32 *outLength, bool isLastChunk) {
+	if (_loadedPreset) {
+		_hmiRequest.flags = HMI_PROCESS_USE_PRESET | HMI_PROCESS_OVERRIDE_INPUT_FORMAT | HMI_PROCESS_OVERRIDE_OUTPUT_FORMAT;
+		if (isLastChunk)
+			_hmiRequest.flags |= HMI_PROCESS_ALLOCATE_OUTPUT | HMI_PROCESS_INCLUDE_TAIL;
+
+		_hmiRequest.presetPtr = _loadedPreset;
+		_hmiRequest.inputFmt = &_hmiInputFmt;
+		_hmiRequest.outputFmt = &_hmiOutputFmt;
+		_hmiRequest.srcBuf = srcBuf;
+		_hmiRequest.srcLen = soundLength;
+		if (!isLastChunk)
+			_hmiRequest.dstBuf = destBuf;
+
+		int processResult = _hmiFxLib->hmiFXPresetProcess(_presetCollection, &_hmiRequest);
+		if (isLastChunk) {
+			// The original would hand back the stale buffer of the previous call on failure
+			*outBuf = processResult ? nullptr : _hmiRequest.dstBuf;
+			*outLength = processResult ? 0 : _hmiRequest.dstLen;
+		}
+
+		return _curHMIEffectIdInternal;
+	}
+
+	uint8 *dest;
+	if (isLastChunk) {
+		*outLength = _hmiOutputFmt.numChannels * soundLength;
+		*outBuf = (uint8 *)malloc(*outLength);
+		if (!*outBuf)
+			return _curHMIEffectIdInternal;
+
+		dest = *outBuf;
+	} else {
+		dest = destBuf;
+	}
+
+	if (!dest)
+		return _curHMIEffectIdInternal;
+
+	// Without a preset the samples are just copied, duplicated if the output is stereo
+	for (uint32 i = 0; i < soundLength >> 1; i++) {
+		memcpy(dest, srcBuf, 2);
+		dest += 2;
+
+		if (_hmiOutputFmt.numChannels == 2) {
+			memcpy(dest, srcBuf, 2);
+			dest += 2;
+		}
+
+		srcBuf += 2;
+	}
+
+	return _curHMIEffectIdInternal;
+}
+
+void IMuseDigital::soundsTerminateProcessing() {
+	if (!_hmiFxInitialized)
+		return;
+
+	_hmiFxInitialized = false;
+
+	if (_loadedPreset)
+		_hmiFxLib->hmiFXPresetRelease(_loadedPreset);
+
+	if (_presetCollection)
+		_hmiFxLib->hmiFXPresetFreeLibrary(_presetCollection);
+
+	_hmiFxLib->hmiFXUnInitSystem(&_hmiInitData);
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/module.mk b/engines/grim/module.mk
index a7c1bc7ed3d..fd9ed3d83d0 100644
--- a/engines/grim/module.mk
+++ b/engines/grim/module.mk
@@ -49,6 +49,7 @@ MODULE_OBJS := \
 	imuse/dimuse_fades.o \
 	imuse/dimuse_files.o \
 	imuse/dimuse_groups.o \
+	imuse/dimuse_hmi.o \
 	imuse/dimuse_internalmixer.o \
 	imuse/dimuse_scripts.o \
 	imuse/dimuse_streamer.o \


Commit: 5701e5cc735ba7de8525aa4b82ca10d370db6dd6
    https://github.com/scummvm/scummvm/commit/5701e5cc735ba7de8525aa4b82ca10d370db6dd6
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Hook up the new DiMUSE engine to the game

Changed paths:
    engines/grim/actor.cpp
    engines/grim/costume/sound_component.cpp
    engines/grim/grim.cpp
    engines/grim/grim.h
    engines/grim/imuse/dimuse_engine.cpp
    engines/grim/imuse/dimuse_engine.h
    engines/grim/lua_v1_sound.cpp
    engines/grim/module.mk
    engines/grim/sound.cpp
    engines/grim/sound.h


diff --git a/engines/grim/actor.cpp b/engines/grim/actor.cpp
index f179a72b6e3..21ecb1e0486 100644
--- a/engines/grim/actor.cpp
+++ b/engines/grim/actor.cpp
@@ -1191,7 +1191,7 @@ void Actor::sayLine(const char *msgId, bool background, float x, float y) {
 		if (g_grim->getGameType() == GType_GRIM && getCurrentCostume()) {
 			_talkDelay = 500;
 		}
-		g_sound->startVoice(_talkSoundName.c_str());
+		g_sound->startVoice(_talkSoundName.c_str(), 127, 64, background);
 	}
 
 	// If the actor is clearly not visible then don't try to play the lip sync
diff --git a/engines/grim/costume/sound_component.cpp b/engines/grim/costume/sound_component.cpp
index b0d684f5c2e..35bdf04f71c 100644
--- a/engines/grim/costume/sound_component.cpp
+++ b/engines/grim/costume/sound_component.cpp
@@ -24,7 +24,7 @@
 #include "engines/grim/debug.h"
 #include "engines/grim/costume.h"
 #include "engines/grim/costume/sound_component.h"
-#include "engines/grim/imuse/imuse.h"
+#include "engines/grim/imuse/dimuse_engine.h"
 
 namespace Grim {
 
@@ -44,19 +44,19 @@ SoundComponent::~SoundComponent() {
 void SoundComponent::setKey(int val) {
 	switch (val) {
 	case 0: // "Play"
-		// No longer a need to check the sound status, if it's already playing
-		// then it will just use the existing handle
-		g_imuse->startSfx(_name.c_str());
-		if (g_grim->getCurrSet()) {
-			Math::Vector3d pos = _cost->getMatrix().getPosition();
-			g_grim->getCurrSet()->setSoundPosition(_name.c_str(), pos);
+		if (!g_imuse->soundsIsSoundPlaying(_name.c_str())) {
+			g_imuse->soundsLoadStartSound(_name.c_str(), 127, DIMUSE_GROUP_SFX);
+			if (g_grim->getCurrSet()) {
+				Math::Vector3d pos = _cost->getMatrix().getPosition();
+				g_grim->getCurrSet()->setSoundPosition(_name.c_str(), pos);
+			}
 		}
 		break;
 	case 1: // "Stop"
-		g_imuse->stopSound(_name.c_str());
+		g_imuse->soundsStopSound(_name.c_str());
 		break;
 	case 2: // "Stop Looping"
-		g_imuse->setHookId(_name.c_str(), 0x80);
+		g_imuse->iMUSESetHook(_name.c_str(), 0x80);
 		break;
 	default:
 		Debug::warning(Debug::Costumes, "Unknown key %d for sound %s", val, _name.c_str());
@@ -65,8 +65,8 @@ void SoundComponent::setKey(int val) {
 
 void SoundComponent::reset() {
 	// A lot of the sound components this gets called against aren't actually running
-	if (g_imuse && g_imuse->getSoundStatus(_name.c_str()))
-		g_imuse->stopSound(_name.c_str());
+	if (g_imuse && !_name.empty())
+		g_imuse->soundsStopSound(_name.c_str());
 }
 
 } // end of namespace Grim
diff --git a/engines/grim/grim.cpp b/engines/grim/grim.cpp
index d006b196b9f..270869be54d 100644
--- a/engines/grim/grim.cpp
+++ b/engines/grim/grim.cpp
@@ -77,7 +77,7 @@
 #include "engines/grim/remastered/overlay.h"
 #include "engines/grim/remastered/lua_remastered.h"
 #include "engines/grim/remastered/commentary.h"
-#include "engines/grim/imuse/imuse.h"
+#include "engines/grim/imuse/dimuse_engine.h"
 #include "engines/grim/emi/sound/emisound.h"
 #include "engines/grim/lua/lua.h"
 
@@ -384,7 +384,24 @@ Common::Error GrimEngine::run() {
 			g_movie = CreateBinkPlayer(demo);
 	}
 	if (getGameType() == GType_GRIM) {
-		g_imuse = new Imuse(20, demo);
+		int sampleRate = DIMUSE_BASE_SAMPLERATE;
+		ConfMan.registerDefault("dimuse_sample_rate", DIMUSE_BASE_SAMPLERATE);
+		if (ConfMan.hasKey("dimuse_sample_rate", _targetName)) {
+			// Only accept sample rates which are a multiple or submultiple of 22050
+			int configSampleRate = ConfMan.getInt("dimuse_sample_rate");
+			if ((configSampleRate % (DIMUSE_BASE_SAMPLERATE / 2)) == 0 &&
+				configSampleRate >= DIMUSE_BASE_SAMPLERATE / 2 &&
+				configSampleRate <= DIMUSE_BASE_SAMPLERATE * 4) {
+				sampleRate = configSampleRate;
+			}
+		}
+
+		bool lowLatencyMode = false;
+		ConfMan.registerDefault("dimuse_low_latency_mode", false);
+		if (ConfMan.hasKey("dimuse_low_latency_mode", _targetName))
+			lowLatencyMode = ConfMan.getBool("dimuse_low_latency_mode");
+
+		g_imuse = new IMuseDigital(sampleRate, _mixer, &_imuseMutex, lowLatencyMode);
 		g_emiSound = nullptr;
 		if (g_grim->isRemastered()) {
 			// This must happen here, since we need the resource loader set up.
@@ -772,7 +789,7 @@ void GrimEngine::handleDebugLoadResource() {
 		resource = (void *)g_movie->play(buf, false, 0, 0);
 	else if (strstr(buf, ".wav") || strstr(buf, ".imu")) {
 		if (g_imuse)
-			g_imuse->startSfx(buf);
+			g_imuse->soundsLoadStartSound(buf, 127, DIMUSE_GROUP_SFX);
 		resource = (void *)1;
 	} else if (strstr(buf, ".mat")) {
 		CMap *cmap = g_resourceloader->loadColormap("item.cmp");
@@ -1053,9 +1070,6 @@ void GrimEngine::mainLoop() {
 		}
 
 		g_sound->flushTracks();
-		if (g_imuse) {
-			g_imuse->refreshScripts();
-		}
 
 		// Process events
 		Common::Event event;
@@ -1195,10 +1209,8 @@ void GrimEngine::savegameRestore() {
 	_savedState = SaveGame::openForLoading(filename);
 	if (!_savedState || !_savedState->isCompatible())
 		return;
-	if (g_imuse) {
-		g_imuse->stopAllSounds();
-		g_imuse->resetState();
-	}
+	if (g_imuse)
+		g_imuse->diMUSEStopAllSounds();
 	g_movie->stop();
 	if (g_imuse)
 		g_imuse->pause(true);
diff --git a/engines/grim/grim.h b/engines/grim/grim.h
index b6e9ed777b6..3bd29bd1803 100644
--- a/engines/grim/grim.h
+++ b/engines/grim/grim.h
@@ -28,6 +28,7 @@
 #include "common/str-array.h"
 #include "common/hashmap.h"
 #include "common/events.h"
+#include "common/mutex.h"
 
 #include "graphics/renderer.h"
 
@@ -233,6 +234,7 @@ protected:
 	bool _savegameSaveRequest = false;
 	Common::String _savegameFileName;
 	SaveGame *_savedState;
+	Common::Mutex _imuseMutex;
 	bool _justSaveLoaded;
 
 	Set *_currSet;
diff --git a/engines/grim/imuse/dimuse_engine.cpp b/engines/grim/imuse/dimuse_engine.cpp
index bca814a4e2b..e7c9707cd11 100644
--- a/engines/grim/imuse/dimuse_engine.cpp
+++ b/engines/grim/imuse/dimuse_engine.cpp
@@ -35,6 +35,8 @@
 
 namespace Grim {
 
+IMuseDigital *g_imuse = nullptr;
+
 void IMuseDigital::timer_handler(void *refCon) {
 	IMuseDigital *diMUSE = (IMuseDigital *)refCon;
 	diMUSE->diMUSEHeartbeat();
@@ -370,10 +372,10 @@ int32 IMuseDigital::getSoundElapsedTimeInMs(int soundId) {
 void IMuseDigital::pause(bool p) {
 	if (p) {
 		debug(5, "IMuseDigital::pause(): pausing...");
-		soundsPause();
+		diMUSEPause();
 	} else {
 		debug(5, "IMuseDigital::pause(): resuming...");
-		soundsResume();
+		diMUSEResume();
 	}
 }
 
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/dimuse_engine.h
index be071cab9a6..83b02458a8b 100644
--- a/engines/grim/imuse/dimuse_engine.h
+++ b/engines/grim/imuse/dimuse_engine.h
@@ -463,6 +463,8 @@ public:
 	void listGroups();
 };
 
+extern IMuseDigital *g_imuse;
+
 } // End of namespace Grim
 
 #endif
diff --git a/engines/grim/lua_v1_sound.cpp b/engines/grim/lua_v1_sound.cpp
index 72a7f4987e1..300c7ebdcb2 100644
--- a/engines/grim/lua_v1_sound.cpp
+++ b/engines/grim/lua_v1_sound.cpp
@@ -27,21 +27,18 @@
 #include "engines/grim/actor.h"
 #include "engines/grim/savegame.h"
 #include "engines/grim/set.h"
-#include "engines/grim/imuse/imuse.h"
+#include "engines/grim/imuse/dimuse_engine.h"
 #include "engines/grim/lua/lauxlib.h"
 
 namespace Grim {
 
-enum ImuseParam {
-	IM_SOUND_PLAY_COUNT = 0x100,
-	IM_SOUND_PEND_COUNT = 0x200,
-	IM_SOUND_GROUP = 0x400,
-	IM_SOUND_PRIORITY = 0x500,
-	IM_SOUND_VOL = 0x600,
-	IM_SOUND_PAN = 0x700
-};
+// Like the original, a sound is identified either by its name or by the number ImStartSound returned
+static const char *getSoundKey(lua_Object nameObj) {
+	if (lua_isnumber(nameObj))
+		return (const char *)(intptr)(int)lua_getnumber(nameObj);
 
-static float ImToMixer = 2.f;
+	return lua_getstring(nameObj);
+}
 
 void Lua_V1::ImStartSound() {
 	lua_Object nameObj = lua_getparam(1);
@@ -57,24 +54,16 @@ void Lua_V1::ImStartSound() {
 	int priority = (int)lua_getnumber(priorityObj);
 	int group = (int)lua_getnumber(groupObj);
 
-	// Start the sound with the appropriate settings
-	if (g_imuse->startSound(soundName, group, 0, 127, 64, priority, nullptr)) {
-		// FIXME actually it's pushnumber from result of startSound
-		lua_pushstring(soundName);
-	}
+	lua_pushnumber(g_imuse->soundsLoadStartSound(soundName, priority, group));
 }
 
 void Lua_V1::ImStopSound() {
 	lua_Object nameObj = lua_getparam(1);
-	if (lua_isnumber(nameObj))
-		error("ImStopsound: name from value not supported");
-
-	const char *soundName = lua_getstring(nameObj);
-	g_imuse->stopSound(soundName);
+	g_imuse->soundsStopSound(getSoundKey(nameObj));
 }
 
 void Lua_V1::ImStopAllSounds() {
-	g_imuse->stopAllSounds();
+	g_imuse->diMUSEStopAllSounds();
 }
 
 void Lua_V1::ImPause() {
@@ -89,40 +78,40 @@ void Lua_V1::ImSetVoiceEffect() {
 	const char *effectName;
 
 	effectName = luaL_check_string(1);
-	Debug::warning(Debug::Sound, "ImSetVoiceEffect(%s) Voice effects are not yet supported", effectName);
+	g_imuse->iMUSESetVoiceEffect(effectName);
 }
 
 void Lua_V1::ImSetMusicVol() {
 	lua_Object volObj = lua_getparam(1);
 	if (!lua_isnumber(volObj))
 		return;
-	g_system->getMixer()->setVolumeForSoundType(Audio::Mixer::kMusicSoundType, (int)(lua_getnumber(volObj) * ImToMixer));
+	g_imuse->diMUSESetMusicGroupVol((int)lua_getnumber(volObj));
 }
 
 void Lua_V1::ImGetMusicVol() {
-	lua_pushnumber(g_system->getMixer()->getVolumeForSoundType(Audio::Mixer::kMusicSoundType) / ImToMixer);
+	lua_pushnumber(g_imuse->diMUSEGetMusicGroupVol());
 }
 
 void Lua_V1::ImSetVoiceVol() {
 	lua_Object volObj = lua_getparam(1);
 	if (!lua_isnumber(volObj))
 		return;
-	g_system->getMixer()->setVolumeForSoundType(Audio::Mixer::kSpeechSoundType, (int)(lua_getnumber(volObj) * ImToMixer));
+	g_imuse->diMUSESetVoiceGroupVol((int)lua_getnumber(volObj));
 }
 
 void Lua_V1::ImGetVoiceVol() {
-	lua_pushnumber(g_system->getMixer()->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType) / ImToMixer);
+	lua_pushnumber(g_imuse->diMUSEGetVoiceGroupVol());
 }
 
 void Lua_V1::ImSetSfxVol() {
 	lua_Object volObj = lua_getparam(1);
 	if (!lua_isnumber(volObj))
 		return;
-	g_system->getMixer()->setVolumeForSoundType(Audio::Mixer::kSFXSoundType, (int)(lua_getnumber(volObj) * ImToMixer));
+	g_imuse->diMUSESetSFXGroupVol((int)lua_getnumber(volObj));
 }
 
 void Lua_V1::ImGetSfxVol() {
-	lua_pushnumber(g_system->getMixer()->getVolumeForSoundType(Audio::Mixer::kSFXSoundType) / ImToMixer);
+	lua_pushnumber(g_imuse->diMUSEGetSFXGroupVol());
 }
 
 void Lua_V1::ImSetParam() {
@@ -130,57 +119,30 @@ void Lua_V1::ImSetParam() {
 	lua_Object paramObj = lua_getparam(2);
 	lua_Object valueObj = lua_getparam(3);
 
-	if (lua_isnumber(nameObj)) {
-		warning("ImSetParam: getting name from number is not supported");
+	if (!lua_isnumber(nameObj) && !lua_isstring(nameObj))
 		return;
-	}
-	if (!lua_isstring(nameObj)) {
+	if (!lua_isnumber(paramObj) || !lua_isnumber(valueObj))
 		return;
-	}
 
-	const char *soundName = lua_getstring(nameObj);
 	int param = (int)lua_getnumber(paramObj);
 	int value = (int)lua_getnumber(valueObj);
 	if (value < 0)
 		value = 0;
-	switch (param) {
-	case IM_SOUND_VOL:
-		g_imuse->setVolume(soundName, value);
-		break;
-	case IM_SOUND_PAN:
-		g_imuse->setPan(soundName, value);
-		break;
-	default:
-		error("ImSetParam() Unimplemented %d", param);
-	}
+
+	g_imuse->soundsSetParam(getSoundKey(nameObj), param, value);
 }
 
 void Lua_V1::ImGetParam() {
 	lua_Object nameObj = lua_getparam(1);
 	lua_Object paramObj = lua_getparam(2);
 
-	if (lua_isnumber(nameObj)) {
-		warning("ImGetParam: getting name from number is not supported");
-		lua_pushnumber(-1.0);
-		return;
-	}
-	if (!lua_isstring(nameObj)) {
+	if (!lua_isnumber(nameObj) && !lua_isstring(nameObj)) {
 		lua_pushnumber(-1.0);
 		return;
 	}
 
-	const char *soundName = lua_getstring(nameObj);
 	int param = (int)lua_getnumber(paramObj);
-	switch (param) {
-	case IM_SOUND_PLAY_COUNT:
-		lua_pushnumber(g_imuse->getCountPlayedTracks(soundName));
-		break;
-	case IM_SOUND_VOL:
-		lua_pushnumber(g_imuse->getVolume(soundName));
-		break;
-	default:
-		error("ImGetParam() Unimplemented %d", param);
-	}
+	lua_pushnumber(g_imuse->soundsGetParam(getSoundKey(nameObj), param));
 }
 
 void Lua_V1::ImFadeParam() {
@@ -196,23 +158,13 @@ void Lua_V1::ImFadeParam() {
 	if (!lua_isnumber(opcodeObj) || !lua_isnumber(valueObj) || !lua_isnumber(durationObj))
 		return;
 
-	if (lua_isnumber(nameObj)) {
-		error("ImFadeParam: getting name from number is not supported");
-	}
-	const char *soundName = lua_getstring(nameObj);
 	int opcode = (int)lua_getnumber(opcodeObj);
 	int value = (int)lua_getnumber(valueObj);
 	if (value < 0)
 		value = 0;
 	int duration = (int)lua_getnumber(durationObj);
-	switch (opcode) {
-	case IM_SOUND_PAN:
-		g_imuse->setFadePan(soundName, value, duration);
-		break;
-	default:
-		error("ImFadeParam(%s, %x, %d, %d)", soundName, opcode, value, duration);
-		break;
-	}
+
+	g_imuse->soundsFadeParam(getSoundKey(nameObj), opcode, value, duration);
 }
 
 void Lua_V1::ImSetState() {
@@ -229,26 +181,17 @@ void Lua_V1::ImSetSequence() {
 		return;
 
 	int state = (int)lua_getnumber(stateObj);
-	lua_pushnumber(g_imuse->setMusicSequence(state));
+	lua_pushnumber(g_imuse->diMUSESetSequence(state));
 }
 
 void Lua_V1::SaveIMuse() {
-	SaveGame *savedIMuse = SaveGame::openForSaving("grim.tmp");
-	if (!savedIMuse)
-		return;
-	g_imuse->saveState(savedIMuse);
-	delete savedIMuse;
+	// TODO
+	// Save and restore of the iMUSE state
 }
 
 void Lua_V1::RestoreIMuse() {
-	SaveGame *savedIMuse = SaveGame::openForLoading("grim.tmp");
-	if (!savedIMuse)
-		return;
-	g_imuse->stopAllSounds();
-	g_imuse->resetState();
-	g_imuse->restoreState(savedIMuse);
-	delete savedIMuse;
-	g_system->getSavefileManager()->removeSavefile("grim.tmp");
+	// TODO
+	// Save and restore of the iMUSE state
 }
 
 void Lua_V1::SetSoundPosition() {
@@ -302,14 +245,8 @@ void Lua_V1::SetSoundPosition() {
 			someParam = 0.0;
 	}
 
-	if (g_grim->getCurrSet()) {
-		if (lua_isnumber(nameObj))
-			error("SetSoundPosition: number is not yet supported");
-		else {
-			const char *soundName = lua_getstring(nameObj);
-			g_grim->getCurrSet()->setSoundPosition(soundName, pos, minVolume, maxVolume);
-		}
-	}
+	if (g_grim->getCurrSet())
+		g_grim->getCurrSet()->setSoundPosition(getSoundKey(nameObj), pos, minVolume, maxVolume);
 }
 
 void Lua_V1::IsSoundPlaying() {
diff --git a/engines/grim/module.mk b/engines/grim/module.mk
index fd9ed3d83d0..83a8c9d1940 100644
--- a/engines/grim/module.mk
+++ b/engines/grim/module.mk
@@ -58,13 +58,7 @@ MODULE_OBJS := \
 	imuse/dimuse_triggers.o \
 	imuse/dimuse_utils.o \
 	imuse/dimuse_waveout.o \
-	imuse/imuse.o \
 	imuse/imuse_mcmp_mgr.o \
-	imuse/imuse_music.o \
-	imuse/imuse_script.o \
-	imuse/imuse_sndmgr.o \
-	imuse/imuse_tables.o \
-	imuse/imuse_track.o \
 	lua/lapi.o \
 	lua/lauxlib.o \
 	lua/lbuffer.o \
diff --git a/engines/grim/sound.cpp b/engines/grim/sound.cpp
index 91334089d77..8c99e06f0b0 100644
--- a/engines/grim/sound.cpp
+++ b/engines/grim/sound.cpp
@@ -20,7 +20,7 @@
  */
 
 #include "engines/grim/grim.h"
-#include "engines/grim/imuse/imuse.h"
+#include "engines/grim/imuse/dimuse_engine.h"
 #include "engines/grim/emi/sound/emisound.h"
 #include "engines/grim/sound.h"
 
@@ -28,39 +28,63 @@ namespace Grim {
 
 SoundPlayer *g_sound = nullptr;
 
-bool SoundPlayer::startVoice(const char *soundName, int volume, int pan) {
-	if (g_grim->getGameType() == GType_GRIM)
-		return g_imuse->startVoice(soundName, volume, pan);
-	else
+bool SoundPlayer::startVoice(const char *soundName, int volume, int pan, bool background) {
+	if (g_grim->getGameType() == GType_GRIM) {
+		if (background) {
+			if (!g_imuse->soundsLoadProcessStartSound(soundName, 127, DIMUSE_GROUP_SPEECH))
+				return false;
+
+			g_imuse->soundsSetParam(soundName, DIMUSE_P_VOLUME, volume);
+			return true;
+		}
+
+		bool started = !g_imuse->soundStartVoiceStream(soundName, volume, pan);
+		_streamedVoice = started ? soundName : "";
+		return started;
+	} else {
 		return g_emiSound->startVoice(soundName, volume, pan);
+	}
 }
 
 bool SoundPlayer::getSoundStatus(const char *soundName) {
-	if (g_grim->getGameType() == GType_GRIM)
-		return g_imuse->getSoundStatus(soundName);
-	else
+	if (g_grim->getGameType() == GType_GRIM) {
+		if (!*soundName)
+			return false;
+
+		if (_streamedVoice == soundName)
+			return g_imuse->diMUSEGetParam(kTalkSoundID, DIMUSE_P_SND_TRACK_NUM) > 0;
+
+		return g_imuse->soundsIsSoundPlaying(soundName);
+	} else {
 		return g_emiSound->getSoundStatus(soundName);
+	}
 }
 
 void SoundPlayer::stopSound(const char *soundName) {
 	if (g_grim->getGameType() == GType_GRIM) {
-		g_imuse->stopSound(soundName);
-		return;
+		if (_streamedVoice == soundName)
+			g_imuse->soundStopVoiceStream();
+		else
+			g_imuse->soundsStopSound(soundName);
 	} else {
 		g_emiSound->stopSound(soundName);
 	}
 }
 
 int32 SoundPlayer::getPosIn16msTicks(const char *soundName) {
-	if (g_grim->getGameType() == GType_GRIM)
-		return g_imuse->getPosIn16msTicks(soundName);
-	else
+	if (g_grim->getGameType() == GType_GRIM) {
+		if (_streamedVoice == soundName)
+			return g_imuse->soundGetVoiceTime() >> 4;
+
+		return g_imuse->soundsGetParam(soundName, DIMUSE_P_SND_POS_IN_MS) >> 4;
+	} else {
 		return g_emiSound->getPosIn16msTicks(soundName);
+	}
 }
 
 void SoundPlayer::setVolume(const char *soundName, int volume) {
 	if (g_grim->getGameType() == GType_GRIM) {
-		g_imuse->setVolume(soundName, volume);
+		g_imuse->soundsSetParam(soundName, DIMUSE_P_VOLUME, volume);
 	} else {
 		g_emiSound->setVolume(soundName, volume);
 	}
@@ -68,7 +92,7 @@ void SoundPlayer::setVolume(const char *soundName, int volume) {
 
 void SoundPlayer::setPan(const char *soundName, int pan) {
 	if (g_grim->getGameType() == GType_GRIM) {
-		g_imuse->setPan(soundName, pan);
+		g_imuse->soundsSetParam(soundName, DIMUSE_P_PAN, pan);
 	} else {
 		g_emiSound->setPan(soundName, pan);
 	}
@@ -76,7 +100,7 @@ void SoundPlayer::setPan(const char *soundName, int pan) {
 
 void SoundPlayer::setMusicState(int stateId) {
 	if (g_grim->getGameType() == GType_GRIM) {
-		g_imuse->setMusicState(stateId);
+		g_imuse->diMUSESetState(stateId);
 	} else {
 		g_emiSound->setMusicState(stateId);
 	}
@@ -84,7 +108,7 @@ void SoundPlayer::setMusicState(int stateId) {
 
 void SoundPlayer::flushTracks() {
 	if (g_grim->getGameType() == GType_GRIM) {
-		g_imuse->flushTracks();
+		g_imuse->soundsPeriodic();
 	} else {
 		g_emiSound->flushTracks();
 	}
@@ -92,7 +116,8 @@ void SoundPlayer::flushTracks() {
 
 void SoundPlayer::restoreState(SaveGame *savedState) {
 	if (g_grim->getGameType() == GType_GRIM) {
-		g_imuse->restoreState(savedState);
+		// TODO
+		// Save and restore of the iMUSE state
 	} else {
 		g_emiSound->restoreState(savedState);
 	}
@@ -100,7 +125,8 @@ void SoundPlayer::restoreState(SaveGame *savedState) {
 
 void SoundPlayer::saveState(SaveGame *savedState) {
 	if (g_grim->getGameType() == GType_GRIM) {
-		g_imuse->saveState(savedState);
+		// TODO
+		// Save and restore of the iMUSE state
 	} else {
 		g_emiSound->saveState(savedState);
 	}
diff --git a/engines/grim/sound.h b/engines/grim/sound.h
index cb9267615be..5b700c5e4cb 100644
--- a/engines/grim/sound.h
+++ b/engines/grim/sound.h
@@ -22,6 +22,8 @@
 #ifndef GRIM_SOUND_H
 #define GRIM_SOUND_H
 
+#include "common/str.h"
+
 #include "engines/grim/savegame.h"
 
 namespace Grim {
@@ -30,7 +32,7 @@ class EMISound;
 
 class SoundPlayer {
 public:
-	bool startVoice(const char *soundName, int volume = 127, int pan = 64);
+	bool startVoice(const char *soundName, int volume = 127, int pan = 64, bool background = false);
 	bool getSoundStatus(const char *soundName);
 	void stopSound(const char *soundName);
 	int32 getPosIn16msTicks(const char *soundName);
@@ -43,6 +45,10 @@ public:
 	// Save/Load:
 	void restoreState(SaveGame *savedState);
 	void saveState(SaveGame *savedState);
+
+private:
+	// Name of the voice currently in the streamed voice slot
+	Common::String _streamedVoice;
 };
 
 extern SoundPlayer *g_sound;


Commit: 7ce719034b215be3e61bd9fc29c49b15af4d26cd
    https://github.com/scummvm/scummvm/commit/7ce719034b215be3e61bd9fc29c49b15af4d26cd
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Implement saving and post-load fix for old savegames

Changed paths:
    engines/grim/imuse/dimuse_dispatch.cpp
    engines/grim/imuse/dimuse_engine.h
    engines/grim/imuse/dimuse_fades.cpp
    engines/grim/imuse/dimuse_files.cpp
    engines/grim/imuse/dimuse_scripts.cpp
    engines/grim/imuse/dimuse_tables.cpp
    engines/grim/imuse/dimuse_tables.h
    engines/grim/imuse/dimuse_tracks.cpp
    engines/grim/imuse/dimuse_triggers.cpp
    engines/grim/lua_v1_sound.cpp
    engines/grim/savegame.cpp
    engines/grim/sound.cpp


diff --git a/engines/grim/imuse/dimuse_dispatch.cpp b/engines/grim/imuse/dimuse_dispatch.cpp
index 60cf929bdcd..7e1c9eb02d3 100644
--- a/engines/grim/imuse/dimuse_dispatch.cpp
+++ b/engines/grim/imuse/dimuse_dispatch.cpp
@@ -94,36 +94,36 @@ IMuseDigiDispatch *IMuseDigital::dispatchGetDispatchByTrackId(int trackId) {
 void IMuseDigital::dispatchSaveLoad(Common::Serializer &ser) {
 
 	for (int l = 0; l < DIMUSE_MAX_DISPATCHES; l++) {
-		ser.syncAsSint32LE(_dispatches[l].wordSize, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].sampleRate, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].channelCount, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].swapEndiannessFlag, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].currentOffset, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].audioRemaining, VER(103));
-		ser.syncArray(_dispatches[l].map, DIMUSE_MAX_MAP_SIZE, Common::Serializer::Sint32LE, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].wordSize, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].sampleRate, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].channelCount, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].swapEndiannessFlag, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].currentOffset, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].audioRemaining, VER(30));
+		ser.syncArray(_dispatches[l].map, DIMUSE_MAX_MAP_SIZE, Common::Serializer::Sint32LE, VER(30));
 
 		// This is only needed to signal if the sound originally had a stream associated with it
 		int hasStream = 0;
 		if (ser.isSaving()) {
 			if (_dispatches[l].streamPtr)
 				hasStream = 1;
-			ser.syncAsSint32LE(hasStream, VER(103));
+			ser.syncAsSint32LE(hasStream, VER(30));
 		} else {
-			ser.syncAsSint32LE(hasStream, VER(103));
+			ser.syncAsSint32LE(hasStream, VER(30));
 			_dispatches[l].streamPtr = hasStream ? (IMuseDigiStream *)1 : nullptr;
 		}
 
-		ser.syncAsSint32LE(_dispatches[l].streamBufID, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].streamErrFlag, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].fadeOffset, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].fadeRemaining, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].fadeWordSize, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].fadeSampleRate, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].fadeChannelCount, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].fadeSyncFlag, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].fadeSyncDelta, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].fadeVol, VER(103));
-		ser.syncAsSint32LE(_dispatches[l].fadeSlope, VER(103));
+		ser.syncAsSint32LE(_dispatches[l].streamBufID, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].streamErrFlag, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].fadeOffset, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].fadeRemaining, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].fadeWordSize, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].fadeSampleRate, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].fadeChannelCount, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].fadeSyncFlag, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].fadeSyncDelta, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].fadeVol, VER(30));
+		ser.syncAsSint32LE(_dispatches[l].fadeSlope, VER(30));
 	}
 
 	if (ser.isLoading()) {
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/dimuse_engine.h
index 83b02458a8b..3a8048a4c0f 100644
--- a/engines/grim/imuse/dimuse_engine.h
+++ b/engines/grim/imuse/dimuse_engine.h
@@ -378,6 +378,8 @@ public:
 	int iMUSESetHook(const char *soundName, int hookId);
 	int iMUSEGetHook(const char *soundName);
 	void iMUSESetVoiceEffect(const char *effectName);
+	void soundsSaveLoad(Common::Serializer &ser);
+	void soundsRestoreLegacy(int32 stateIndex, int32 seqIndex);
 	void soundsPeriodic();
 	int soundsPause();
 	int soundsResume();
diff --git a/engines/grim/imuse/dimuse_fades.cpp b/engines/grim/imuse/dimuse_fades.cpp
index 9746af60820..c41b26a0477 100644
--- a/engines/grim/imuse/dimuse_fades.cpp
+++ b/engines/grim/imuse/dimuse_fades.cpp
@@ -138,16 +138,16 @@ void IMuseDigiFadesHandler::loop() {
 
 void IMuseDigiFadesHandler::saveLoad(Common::Serializer &ser) {
 	for (int l = 0; l < DIMUSE_MAX_FADES; l++) {
-		ser.syncAsSint32LE(_fades[l].status, VER(103));
-		ser.syncAsSint32LE(_fades[l].sound, VER(103));
-		ser.syncAsSint32LE(_fades[l].param, VER(103));
-		ser.syncAsSint32LE(_fades[l].currentVal, VER(103));
-		ser.syncAsSint32LE(_fades[l].counter, VER(103));
-		ser.syncAsSint32LE(_fades[l].length, VER(103));
-		ser.syncAsSint32LE(_fades[l].slope, VER(103));
-		ser.syncAsSint32LE(_fades[l].slopeMod, VER(103));
-		ser.syncAsSint32LE(_fades[l].modOvfloCounter, VER(103));
-		ser.syncAsSint32LE(_fades[l].nudge, VER(103));
+		ser.syncAsSint32LE(_fades[l].status, VER(30));
+		ser.syncAsSint32LE(_fades[l].sound, VER(30));
+		ser.syncAsSint32LE(_fades[l].param, VER(30));
+		ser.syncAsSint32LE(_fades[l].currentVal, VER(30));
+		ser.syncAsSint32LE(_fades[l].counter, VER(30));
+		ser.syncAsSint32LE(_fades[l].length, VER(30));
+		ser.syncAsSint32LE(_fades[l].slope, VER(30));
+		ser.syncAsSint32LE(_fades[l].slopeMod, VER(30));
+		ser.syncAsSint32LE(_fades[l].modOvfloCounter, VER(30));
+		ser.syncAsSint32LE(_fades[l].nudge, VER(30));
 	}
 
 	if (ser.isLoading())
diff --git a/engines/grim/imuse/dimuse_files.cpp b/engines/grim/imuse/dimuse_files.cpp
index 0aa0ebe2334..791d77aa35a 100644
--- a/engines/grim/imuse/dimuse_files.cpp
+++ b/engines/grim/imuse/dimuse_files.cpp
@@ -61,8 +61,8 @@ void IMuseDigital::diMUSESaveLoadFilelist(Common::Serializer &ser) {
 		}
 	}
 
-	ser.syncAsSint32LE(loadedCount, VER(103));
-	ser.syncAsSint32LE(openedCount, VER(103));
+	ser.syncAsSint32LE(loadedCount, VER(30));
+	ser.syncAsSint32LE(openedCount, VER(30));
 
 	sound = _loadedSoundList;
 	for (int i = 0; i < loadedCount; i++) {
@@ -73,9 +73,9 @@ void IMuseDigital::diMUSESaveLoadFilelist(Common::Serializer &ser) {
 			sound = sound->next;
 		}
 
-		ser.syncAsSint32LE(soundId, VER(103));
-		ser.syncArray(filename, sizeof(filename), Common::Serializer::SByte, VER(103));
-		ser.syncAsSint32LE(refCount, VER(103));
+		ser.syncAsSint32LE(soundId, VER(30));
+		ser.syncArray(filename, sizeof(filename), Common::Serializer::SByte, VER(30));
+		ser.syncAsSint32LE(refCount, VER(30));
 
 		if (ser.isLoading()) {
 			if (!diMUSELoadSound(filename, soundId)) {
@@ -101,9 +101,9 @@ void IMuseDigital::diMUSESaveLoadFilelist(Common::Serializer &ser) {
 			sound = sound->next;
 		}
 
-		ser.syncAsSint32LE(soundId, VER(103));
-		ser.syncArray(filename, sizeof(filename), Common::Serializer::SByte, VER(103));
-		ser.syncAsSint32LE(refCount, VER(103));
+		ser.syncAsSint32LE(soundId, VER(30));
+		ser.syncArray(filename, sizeof(filename), Common::Serializer::SByte, VER(30));
+		ser.syncAsSint32LE(refCount, VER(30));
 
 		if (ser.isLoading()) {
 			if (!diMUSEOpenSound(filename, soundId)) {
@@ -1600,6 +1600,137 @@ int IMuseDigital::soundsGetPhoneme(int soundId, int offset) {
 	return DIMUSE_PHONEME_NONE;
 }
 
+void IMuseDigital::soundsSaveLoad(Common::Serializer &ser) {
+	Common::StackLock lock(*_mutex);
+
+	char effectName[sizeof(_curEffectName)];
+
+	if (ser.isSaving()) {
+		Common::strlcpy(effectName, _curEffectId ? _curEffectName : "OFF", sizeof(effectName));
+		_curSpeechFile[0] = '\0';
+	}
+
+	ser.syncArray(effectName, sizeof(effectName), Common::Serializer::SByte, VER(30));
+
+	if (ser.isLoading()) {
+		diMUSEStopAllSounds();
+		diMUSEFlushSounds();
+		soundsCloseVoiceFile();
+		cacheReset();
+		iMUSESetVoiceEffect(effectName);
+		_curSpeechFile[0] = '\0';
+	}
+
+	diMUSESaveLoad(ser);
+	diMUSESaveLoadScript(ser);
+
+	if (ser.isLoading()) {
+		for (int soundId = diMUSEGetNextSound(0); soundId; soundId = diMUSEGetNextSound(soundId)) {
+			if (soundId <= kTalkSoundID)
+				diMUSEStopSound(soundId);
+		}
+
+		soundsCloseVoiceFile();
+	}
+
+	int32 numSounds = 0;
+	int savedSlots[DIMUSE_MAX_CACHED_SOUNDS];
+
+	if (ser.isSaving()) {
+		// Only active sounds with a native iMUS map are saved...
+		for (int slot = 0; slot < DIMUSE_MAX_CACHED_SOUNDS; slot++) {
+			IMuseDigiCachedSound *sound = &_soundCache[slot];
+
+			if (sound->soundFilename[0] && sound->soundUncompData &&
+				diMUSEGetParam(slot + 100, DIMUSE_P_SND_TRACK_NUM) > 0 &&
+				!memcmp(sound->soundMap, "iMUS", 4) && READ_BE_UINT16(sound->soundMap + 14) != 56)
+				savedSlots[numSounds++] = slot;
+		}
+	}
+
+	ser.syncAsSint32LE(numSounds, VER(30));
+	if (numSounds < 0 || numSounds > DIMUSE_MAX_CACHED_SOUNDS)
+		return;
+
+	// The cached sounds are restarted with the same ids, volume, pan and hook
+	for (int i = 0; i < numSounds; i++) {
+		char soundName[32] = {};
+		int32 luaSoundId = 0, priority = 0;
+
+		if (ser.isSaving()) {
+			Common::strlcpy(soundName, _soundCache[savedSlots[i]].soundFilename, sizeof(soundName));
+			luaSoundId = _soundCache[savedSlots[i]].luaSoundId;
+			priority = _soundCache[savedSlots[i]].priority;
+		}
+
+		ser.syncArray(soundName, sizeof(soundName), Common::Serializer::SByte, VER(30));
+		ser.syncAsSint32LE(luaSoundId, VER(30));
+		ser.syncAsSint32LE(priority, VER(30));
+
+		if (ser.isLoading()) {
+			_currentSoundSlot = luaSoundId - 1111;
+			soundsLoadStartSound(soundName, priority, DIMUSE_GROUP_SFX);
+		}
+	}
+
+	for (int i = 0; i < numSounds; i++) {
+		int32 luaSoundId = 0, volume = 0, pan = 0;
+
+		if (ser.isSaving()) {
+			luaSoundId = _soundCache[savedSlots[i]].luaSoundId;
+			volume = diMUSEGetParam(savedSlots[i] + 100, DIMUSE_P_VOLUME);
+			pan = diMUSEGetParam(savedSlots[i] + 100, DIMUSE_P_PAN);
+		}
+
+		ser.syncAsSint32LE(luaSoundId, VER(30));
+		ser.syncAsSint32LE(volume, VER(30));
+		ser.syncAsSint32LE(pan, VER(30));
+
+		if (ser.isLoading()) {
+			soundsSetParam((const char *)(intptr)luaSoundId, DIMUSE_P_VOLUME, volume);
+			soundsSetParam((const char *)(intptr)luaSoundId, DIMUSE_P_PAN, pan);
+		}
+	}
+
+	for (int i = 0; i < numSounds; i++) {
+		int32 luaSoundId = 0, hookId = 0;
+
+		if (ser.isSaving()) {
+			luaSoundId = _soundCache[savedSlots[i]].luaSoundId;
+			hookId = diMUSEGetHook(savedSlots[i] + 100);
+		}
+
+		ser.syncAsSint32LE(luaSoundId, VER(30));
+		ser.syncAsSint32LE(hookId, VER(30));
+
+		if (ser.isLoading())
+			iMUSESetHook((const char *)(intptr)luaSoundId, hookId);
+	}
+}
+
+void IMuseDigital::soundsRestoreLegacy(int32 stateIndex, int32 seqIndex) {
+	Common::StackLock lock(*_mutex);
+
+	// The savegames of the old iMUSE only stored the music state and sequence, so
+	// the rest is reset and the music is started again as it was
+	diMUSEStopAllSounds();
+	diMUSEFlushSounds();
+	soundsCloseVoiceFile();
+	cacheReset();
+	_curSpeechFile[0] = '\0';
+
+	int stateId = grimLegacyStateSoundId(stateIndex);
+	int seqId = (seqIndex >= 0 && seqIndex < ARRAYSIZE(_grimSeqMusicTable)) ? _grimSeqMusicTable[seqIndex].soundId : -1;
+
+	_curMusicState = 0;
+	_curMusicSeq = 0;
+	_nextSeqToPlay = 0;
+	memset(_attributes, 0, sizeof(_attributes));
+
+	scriptSetSequence(seqId);
+	scriptSetState(stateId);
+}
+
 int IMuseDigital::iMUSEGetPhoneme(int lipsyncId, int offset) {
 	if (lipsyncId == _lipsyncSoundIds[0])
 		return soundsGetPhoneme(lipsyncId, offset + soundGetVoiceTime());
diff --git a/engines/grim/imuse/dimuse_scripts.cpp b/engines/grim/imuse/dimuse_scripts.cpp
index da38ef11769..d14a7a61473 100644
--- a/engines/grim/imuse/dimuse_scripts.cpp
+++ b/engines/grim/imuse/dimuse_scripts.cpp
@@ -226,10 +226,10 @@ void IMuseDigital::scriptSaveLoad(Common::Serializer &ser) {
 		diMUSECloseAll();
 	}
 
-	ser.syncAsSint32LE(_curMusicState, VER(103));
-	ser.syncAsSint32LE(_curMusicSeq, VER(103));
-	ser.syncAsSint32LE(_nextSeqToPlay, VER(103));
-	ser.syncArray(_attributes, ARRAYSIZE(_attributes), Common::Serializer::Sint32LE, VER(103));
+	ser.syncAsSint32LE(_curMusicState, VER(30));
+	ser.syncAsSint32LE(_curMusicSeq, VER(30));
+	ser.syncAsSint32LE(_nextSeqToPlay, VER(30));
+	ser.syncArray(_attributes, ARRAYSIZE(_attributes), Common::Serializer::Sint32LE, VER(30));
 	diMUSESaveLoadFilelist(ser);
 }
 
diff --git a/engines/grim/imuse/dimuse_tables.cpp b/engines/grim/imuse/dimuse_tables.cpp
index 21be3913401..3b7bc0cd6dd 100644
--- a/engines/grim/imuse/dimuse_tables.cpp
+++ b/engines/grim/imuse/dimuse_tables.cpp
@@ -19,6 +19,8 @@
  *
  */
 
+#include "common/util.h"
+
 #include "engines/grim/imuse/dimuse_tables.h"
 
 namespace Grim {
@@ -251,4 +253,26 @@ const IMuseDigiStateTable _grimSeqMusicTable[41] = {
 	{"2399 - End Credits",      2, 2399, "seqEndCredits",        0,  0, 200, 127, 0}, /* 040 */
 };
 
+// The state table of the previous iMUSE implementation had some entries in a different order, so
+// we have to account for that when reloading older savegames...
+static const struct {
+	int tableIndex;
+	int soundId;
+} kLegacyMovedStates[] = {
+	{142, 1304}, {143, 1305}, {144, 1306}, {161, 1325}, {162, 1326}, {163, 1327}, {164, 1328},
+	{165, 1329}, {166, 1330}, {167, 1331}, {168, 1332}, {170, 1334}, {176, 1354}, {177, 1355}
+};
+
+int grimLegacyStateSoundId(int tableIndex) {
+	if (tableIndex < 0 || tableIndex >= ARRAYSIZE(_grimStateMusicTable))
+		return -1;
+
+	for (int i = 0; i < ARRAYSIZE(kLegacyMovedStates); i++) {
+		if (kLegacyMovedStates[i].tableIndex == tableIndex)
+			return kLegacyMovedStates[i].soundId;
+	}
+
+	return _grimStateMusicTable[tableIndex].soundId;
+}
+
 } // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_tables.h b/engines/grim/imuse/dimuse_tables.h
index 809565cbdc0..a18c0d7d3eb 100644
--- a/engines/grim/imuse/dimuse_tables.h
+++ b/engines/grim/imuse/dimuse_tables.h
@@ -41,6 +41,9 @@ struct IMuseDigiStateTable {
 extern const IMuseDigiStateTable _grimStateMusicTable[181];
 extern const IMuseDigiStateTable _grimSeqMusicTable[41];
 
+// Sound id of a state, given its position in the table of the old iMUSE
+int grimLegacyStateSoundId(int tableIndex);
+
 } // End of namespace Grim
 
 #endif
diff --git a/engines/grim/imuse/dimuse_tracks.cpp b/engines/grim/imuse/dimuse_tracks.cpp
index 0dc2c1c2b54..8c36f781c2d 100644
--- a/engines/grim/imuse/dimuse_tracks.cpp
+++ b/engines/grim/imuse/dimuse_tracks.cpp
@@ -75,18 +75,18 @@ void IMuseDigital::tracksSaveLoad(Common::Serializer &ser) {
 	dispatchSaveLoad(ser);
 
 	for (int l = 0; l < _trackCount; l++) {
-		ser.syncAsSint32LE(_tracks[l].soundId, VER(103));
-		ser.syncAsSint32LE(_tracks[l].marker, VER(103));
-		ser.syncAsSint32LE(_tracks[l].group, VER(103));
-		ser.syncAsSint32LE(_tracks[l].priority, VER(103));
-		ser.syncAsSint32LE(_tracks[l].vol, VER(103));
-		ser.syncAsSint32LE(_tracks[l].effVol, VER(103));
-		ser.syncAsSint32LE(_tracks[l].pan, VER(103));
-		ser.syncAsSint32LE(_tracks[l].detune, VER(103));
-		ser.syncAsSint32LE(_tracks[l].transpose, VER(103));
-		ser.syncAsSint32LE(_tracks[l].pitchShift, VER(103));
-		ser.syncAsSint32LE(_tracks[l].mailbox, VER(103));
-		ser.syncAsSint32LE(_tracks[l].jumpHook, VER(103));
+		ser.syncAsSint32LE(_tracks[l].soundId, VER(30));
+		ser.syncAsSint32LE(_tracks[l].marker, VER(30));
+		ser.syncAsSint32LE(_tracks[l].group, VER(30));
+		ser.syncAsSint32LE(_tracks[l].priority, VER(30));
+		ser.syncAsSint32LE(_tracks[l].vol, VER(30));
+		ser.syncAsSint32LE(_tracks[l].effVol, VER(30));
+		ser.syncAsSint32LE(_tracks[l].pan, VER(30));
+		ser.syncAsSint32LE(_tracks[l].detune, VER(30));
+		ser.syncAsSint32LE(_tracks[l].transpose, VER(30));
+		ser.syncAsSint32LE(_tracks[l].pitchShift, VER(30));
+		ser.syncAsSint32LE(_tracks[l].mailbox, VER(30));
+		ser.syncAsSint32LE(_tracks[l].jumpHook, VER(30));
 	}
 
 	if (ser.isLoading()) {
diff --git a/engines/grim/imuse/dimuse_triggers.cpp b/engines/grim/imuse/dimuse_triggers.cpp
index 8d9a4e9a259..b27f9c248f6 100644
--- a/engines/grim/imuse/dimuse_triggers.cpp
+++ b/engines/grim/imuse/dimuse_triggers.cpp
@@ -78,35 +78,35 @@ int IMuseDigiTriggersHandler::clearAllTriggers() {
 
 void IMuseDigiTriggersHandler::saveLoad(Common::Serializer &ser) {
 	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
-		ser.syncAsSint32LE(_trigs[l].sound, VER(103));
-		ser.syncArray(_trigs[l].text, 256, Common::Serializer::SByte, VER(103));
-		ser.syncAsSint32LE(_trigs[l].opcode, VER(103));
-		ser.syncAsSint32LE(_trigs[l].a, VER(103));
-		ser.syncAsSint32LE(_trigs[l].b, VER(103));
-		ser.syncAsSint32LE(_trigs[l].c, VER(103));
-		ser.syncAsSint32LE(_trigs[l].d, VER(103));
-		ser.syncAsSint32LE(_trigs[l].e, VER(103));
-		ser.syncAsSint32LE(_trigs[l].f, VER(103));
-		ser.syncAsSint32LE(_trigs[l].g, VER(103));
-		ser.syncAsSint32LE(_trigs[l].h, VER(103));
-		ser.syncAsSint32LE(_trigs[l].i, VER(103));
-		ser.syncAsSint32LE(_trigs[l].j, VER(103));
-		ser.syncAsSint32LE(_trigs[l].clearLater, VER(103));
+		ser.syncAsSint32LE(_trigs[l].sound, VER(30));
+		ser.syncArray(_trigs[l].text, 256, Common::Serializer::SByte, VER(30));
+		ser.syncAsSint32LE(_trigs[l].opcode, VER(30));
+		ser.syncAsSint32LE(_trigs[l].a, VER(30));
+		ser.syncAsSint32LE(_trigs[l].b, VER(30));
+		ser.syncAsSint32LE(_trigs[l].c, VER(30));
+		ser.syncAsSint32LE(_trigs[l].d, VER(30));
+		ser.syncAsSint32LE(_trigs[l].e, VER(30));
+		ser.syncAsSint32LE(_trigs[l].f, VER(30));
+		ser.syncAsSint32LE(_trigs[l].g, VER(30));
+		ser.syncAsSint32LE(_trigs[l].h, VER(30));
+		ser.syncAsSint32LE(_trigs[l].i, VER(30));
+		ser.syncAsSint32LE(_trigs[l].j, VER(30));
+		ser.syncAsSint32LE(_trigs[l].clearLater, VER(30));
 	}
 
 	for (int l = 0; l < DIMUSE_MAX_DEFERS; l++) {
-		ser.syncAsSint32LE(_defers[l].counter, VER(103));
-		ser.syncAsSint32LE(_defers[l].opcode, VER(103));
-		ser.syncAsSint32LE(_defers[l].a, VER(103));
-		ser.syncAsSint32LE(_defers[l].b, VER(103));
-		ser.syncAsSint32LE(_defers[l].c, VER(103));
-		ser.syncAsSint32LE(_defers[l].d, VER(103));
-		ser.syncAsSint32LE(_defers[l].e, VER(103));
-		ser.syncAsSint32LE(_defers[l].f, VER(103));
-		ser.syncAsSint32LE(_defers[l].g, VER(103));
-		ser.syncAsSint32LE(_defers[l].h, VER(103));
-		ser.syncAsSint32LE(_defers[l].i, VER(103));
-		ser.syncAsSint32LE(_defers[l].j, VER(103));
+		ser.syncAsSint32LE(_defers[l].counter, VER(30));
+		ser.syncAsSint32LE(_defers[l].opcode, VER(30));
+		ser.syncAsSint32LE(_defers[l].a, VER(30));
+		ser.syncAsSint32LE(_defers[l].b, VER(30));
+		ser.syncAsSint32LE(_defers[l].c, VER(30));
+		ser.syncAsSint32LE(_defers[l].d, VER(30));
+		ser.syncAsSint32LE(_defers[l].e, VER(30));
+		ser.syncAsSint32LE(_defers[l].f, VER(30));
+		ser.syncAsSint32LE(_defers[l].g, VER(30));
+		ser.syncAsSint32LE(_defers[l].h, VER(30));
+		ser.syncAsSint32LE(_defers[l].i, VER(30));
+		ser.syncAsSint32LE(_defers[l].j, VER(30));
 	}
 
 	if (ser.isLoading())
diff --git a/engines/grim/lua_v1_sound.cpp b/engines/grim/lua_v1_sound.cpp
index 300c7ebdcb2..a5dc6b30aab 100644
--- a/engines/grim/lua_v1_sound.cpp
+++ b/engines/grim/lua_v1_sound.cpp
@@ -27,6 +27,7 @@
 #include "engines/grim/actor.h"
 #include "engines/grim/savegame.h"
 #include "engines/grim/set.h"
+#include "engines/grim/sound.h"
 #include "engines/grim/imuse/dimuse_engine.h"
 #include "engines/grim/lua/lauxlib.h"
 
@@ -185,13 +186,20 @@ void Lua_V1::ImSetSequence() {
 }
 
 void Lua_V1::SaveIMuse() {
-	// TODO
-	// Save and restore of the iMUSE state
+	SaveGame *savedIMuse = SaveGame::openForSaving("grim.tmp");
+	if (!savedIMuse)
+		return;
+	g_sound->saveState(savedIMuse);
+	delete savedIMuse;
 }
 
 void Lua_V1::RestoreIMuse() {
-	// TODO
-	// Save and restore of the iMUSE state
+	SaveGame *savedIMuse = SaveGame::openForLoading("grim.tmp");
+	if (!savedIMuse)
+		return;
+	g_sound->restoreState(savedIMuse);
+	delete savedIMuse;
+	g_system->getSavefileManager()->removeSavefile("grim.tmp");
 }
 
 void Lua_V1::SetSoundPosition() {
diff --git a/engines/grim/savegame.cpp b/engines/grim/savegame.cpp
index ad60aa0b769..12fd899b0c4 100644
--- a/engines/grim/savegame.cpp
+++ b/engines/grim/savegame.cpp
@@ -34,7 +34,7 @@ namespace Grim {
 #define SAVEGAME_FOOTERTAG  'ESAV'
 
 uint SaveGame::SAVEGAME_MAJOR_VERSION = 22;
-uint SaveGame::SAVEGAME_MINOR_VERSION = 29;
+uint SaveGame::SAVEGAME_MINOR_VERSION = 30;
 
 SaveGame *SaveGame::openForLoading(const Common::String &filename) {
 	Common::InSaveFile *inSaveFile = g_system->getSavefileManager()->openForLoading(filename);
diff --git a/engines/grim/sound.cpp b/engines/grim/sound.cpp
index 8c99e06f0b0..40c9d6a4fe4 100644
--- a/engines/grim/sound.cpp
+++ b/engines/grim/sound.cpp
@@ -19,6 +19,9 @@
  *
  */
 
+#include "common/memstream.h"
+#include "common/serializer.h"
+
 #include "engines/grim/grim.h"
 #include "engines/grim/imuse/dimuse_engine.h"
 #include "engines/grim/emi/sound/emisound.h"
@@ -116,8 +119,26 @@ void SoundPlayer::flushTracks() {
 
 void SoundPlayer::restoreState(SaveGame *savedState) {
 	if (g_grim->getGameType() == GType_GRIM) {
-		// TODO
-		// Save and restore of the iMUSE state
+		uint32 sectionSize = savedState->beginSection('IMUS');
+
+		if (savedState->saveMinorVersion() < 30) {
+			// Post-load fix for older savegames using the previous iMUSE implementation...
+			int32 stateIndex = savedState->readLESint32();
+			int32 seqIndex = savedState->readLESint32();
+			savedState->endSection();
+
+			g_imuse->soundsRestoreLegacy(stateIndex, seqIndex);
+			return;
+		}
+
+		byte *sectionData = (byte *)malloc(sectionSize);
+		savedState->read(sectionData, sectionSize);
+		savedState->endSection();
+
+		Common::MemoryReadStream stream(sectionData, sectionSize, DisposeAfterUse::YES);
+		Common::Serializer ser(&stream, nullptr);
+		ser.setVersion(savedState->saveMinorVersion());
+		g_imuse->soundsSaveLoad(ser);
 	} else {
 		g_emiSound->restoreState(savedState);
 	}
@@ -125,8 +146,14 @@ void SoundPlayer::restoreState(SaveGame *savedState) {
 
 void SoundPlayer::saveState(SaveGame *savedState) {
 	if (g_grim->getGameType() == GType_GRIM) {
-		// TODO
-		// Save and restore of the iMUSE state
+		Common::MemoryWriteStreamDynamic stream(DisposeAfterUse::YES);
+		Common::Serializer ser(nullptr, &stream);
+		ser.setVersion(SaveGame::SAVEGAME_MINOR_VERSION);
+		g_imuse->soundsSaveLoad(ser);
+
+		savedState->beginSection('IMUS');
+		savedState->write(stream.getData(), stream.size());
+		savedState->endSection();
 	} else {
 		g_emiSound->saveState(savedState);
 	}


Commit: 4ae2ee9cf773c55f0c2ddbc21826a1cb202018b8
    https://github.com/scummvm/scummvm/commit/4ae2ee9cf773c55f0c2ddbc21826a1cb202018b8
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Port original sound positioning formulas

Changed paths:
    engines/grim/grim.cpp
    engines/grim/imuse/dimuse_dispatch.cpp
    engines/grim/lua_v1_sound.cpp
    engines/grim/set.cpp
    engines/grim/set.h


diff --git a/engines/grim/grim.cpp b/engines/grim/grim.cpp
index 270869be54d..07d36b05fb8 100644
--- a/engines/grim/grim.cpp
+++ b/engines/grim/grim.cpp
@@ -1576,7 +1576,9 @@ void GrimEngine::makeCurrentSetup(int num) {
 		getCurrSet()->setSetup(num);
 		getCurrSet()->setSoundParameters(20, 127);
 		cameraChangeHandle(prevSetup, num);
-		// here should be set sound position
+
+		if (getGameType() == GType_GRIM)
+			getCurrSet()->relocateSounds();
 
 		_setupChanged = true;
 	}
diff --git a/engines/grim/imuse/dimuse_dispatch.cpp b/engines/grim/imuse/dimuse_dispatch.cpp
index 7e1c9eb02d3..bf439fe69bf 100644
--- a/engines/grim/imuse/dimuse_dispatch.cpp
+++ b/engines/grim/imuse/dimuse_dispatch.cpp
@@ -744,6 +744,8 @@ int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
 				return 0;
 
 			continue;
+		case MKTAG('S', 'T', 'O', 'P'):
+			return -1;
 		default:
 			debug(5, "IMuseDigital::dispatchNavigateMap(): ERROR: Unrecognized map event at offset %dx", dispatchPtr->currentOffset);
 			return -1;
diff --git a/engines/grim/lua_v1_sound.cpp b/engines/grim/lua_v1_sound.cpp
index a5dc6b30aab..045434b9294 100644
--- a/engines/grim/lua_v1_sound.cpp
+++ b/engines/grim/lua_v1_sound.cpp
@@ -206,7 +206,7 @@ void Lua_V1::SetSoundPosition() {
 	Math::Vector3d pos;
 	int minVolume = 10;
 	int maxVolume = 127;
-	float someParam = 0;
+	float maxDist = 8.0f;
 	int argId = 1;
 	lua_Object paramObj;
 
@@ -248,13 +248,17 @@ void Lua_V1::SetSoundPosition() {
 
 	paramObj = lua_getparam(argId++);
 	if (lua_isnumber(paramObj)) {
-		someParam = (int)lua_getnumber(paramObj);
-		if (someParam < 0.0)
-			someParam = 0.0;
+		maxDist = lua_getnumber(paramObj);
+		if (maxDist < 0.0f)
+			maxDist = 0.0f;
 	}
 
-	if (g_grim->getCurrSet())
-		g_grim->getCurrSet()->setSoundPosition(getSoundKey(nameObj), pos, minVolume, maxVolume);
+	if (g_grim->getCurrSet()) {
+		if (lua_isnumber(nameObj))
+			g_grim->getCurrSet()->setSoundPosition((int)lua_getnumber(nameObj), pos, minVolume, maxVolume, maxDist);
+		else
+			g_grim->getCurrSet()->setSoundPosition(lua_getstring(nameObj), pos, minVolume, maxVolume, maxDist);
+	}
 }
 
 void Lua_V1::IsSoundPlaying() {
diff --git a/engines/grim/set.cpp b/engines/grim/set.cpp
index f474edb8364..8af92fb038a 100644
--- a/engines/grim/set.cpp
+++ b/engines/grim/set.cpp
@@ -30,11 +30,38 @@
 #include "engines/grim/gfx_base.h"
 #include "engines/grim/sound.h"
 #include "engines/grim/emi/sound/emisound.h"
+#include "engines/grim/imuse/dimuse_engine.h"
 
 #include "math/frustum.h"
 
 namespace Grim {
 
+// Default sound parameters of a room in the original
+static const float kSoundDefaultMaxDist = 8.0f;
+static const float kSoundPanFactor = 1.5f;
+static const float kSoundRadius = 0.8f;
+
+// The original normalizes the vector with an approximation of its length, which it returns too
+static float normalize3QuickAcc(Math::Vector3d &vector) {
+	float x = ABS(vector.x());
+	float y = ABS(vector.y());
+	float z = ABS(vector.z());
+
+	float maxValue = MAX(x, MAX(y, z));
+	float minValue = MIN(x, MIN(y, z));
+	float midValue = MAX(MIN(x, y), MIN(MAX(x, y), z));
+
+	float length = (minValue * 0.25f + midValue * 0.34375f) + maxValue;
+
+	// The original could divide by zero here, let's avoid that...
+	if (length > 0.0f) {
+		float scale = 1.0f / length;
+		vector.set(vector.x() * scale, vector.y() * scale, vector.z() * scale);
+	}
+
+	return length;
+}
+
 Set::Set(const Common::String &sceneName, Common::SeekableReadStream *data) :
 		_locked(false), _name(sceneName), _enableLights(false) {
 
@@ -1019,32 +1046,115 @@ void Set::setLightPosition(int light, const Math::Vector3d &pos) {
 }
 
 void Set::setSoundPosition(const char *soundName, const Math::Vector3d &pos) {
-	setSoundPosition(soundName, pos, _minVolume, _maxVolume);
+	setSoundPosition(soundName, pos, _minVolume, _maxVolume, kSoundDefaultMaxDist);
+}
+
+void Set::setSoundPosition(const char *soundName, const Math::Vector3d &pos, int minVol, int maxVol, float maxDist) {
+	SoundPosition sound;
+	sound.name = soundName;
+	sound.soundId = 0;
+	sound.pos = pos;
+	sound.minVol = minVol;
+	sound.maxVol = maxVol;
+	sound.maxDist = maxDist;
+	addSoundPosition(sound);
+}
+
+void Set::setSoundPosition(int soundId, const Math::Vector3d &pos, int minVol, int maxVol, float maxDist) {
+	SoundPosition sound;
+	sound.soundId = soundId;
+	sound.pos = pos;
+	sound.minVol = minVol;
+	sound.maxVol = maxVol;
+	sound.maxDist = maxDist;
+	addSoundPosition(sound);
+}
+
+const char *Set::getSoundKey(const SoundPosition &sound) const {
+	// Like in the original, a sound is identified either by its name or by its number
+	if (sound.name.empty())
+		return (const char *)(intptr)sound.soundId;
+
+	return sound.name.c_str();
+}
+
+bool Set::isSoundPlaying(const SoundPosition &sound) const {
+	return g_imuse->soundsIsSoundPlaying(getSoundKey(sound));
+}
+
+void Set::addSoundPosition(const SoundPosition &newSound) {
+	// Only the sounds which are currently playing can be positioned
+	if (!isSoundPlaying(newSound))
+		return;
+
+	removeStoppedSounds();
+
+	_soundPositions.push_front(newSound);
+	updateSoundPosition(newSound);
+}
+
+void Set::removeStoppedSounds() {
+	Common::List<SoundPosition>::iterator it = _soundPositions.begin();
+	while (it != _soundPositions.end()) {
+		if (isSoundPlaying(*it))
+			++it;
+		else
+			it = _soundPositions.erase(it);
+	}
 }
 
-void Set::setSoundPosition(const char *soundName, const Math::Vector3d &pos, int minVol, int maxVol) {
-	int newBalance, newVolume;
-	calculateSoundPosition(pos, minVol, maxVol, newVolume, newBalance);
-	g_sound->setVolume(soundName, newVolume);
-	g_sound->setPan(soundName, newBalance);
+void Set::relocateSounds() {
+	removeStoppedSounds();
+
+	for (Common::List<SoundPosition>::iterator it = _soundPositions.begin(); it != _soundPositions.end(); ++it)
+		updateSoundPosition(*it);
 }
 
-void Set::calculateSoundPosition(const Math::Vector3d &pos, int minVol, int maxVol, int &volume, int &balance) {
-	// TODO: The volume and pan needs to be updated when the setup changes.
+void Set::updateSoundPosition(const SoundPosition &sound) {
+	int newVolume, newBalance;
+	const char *soundKey = getSoundKey(sound);
+
+	if (calculateSoundPosition(sound.pos, sound.minVol, sound.maxVol, sound.maxDist, newVolume, newBalance))
+		g_sound->setVolume(soundKey, newVolume);
+
+	g_sound->setPan(soundKey, newBalance);
+}
+
+bool Set::calculateSoundPosition(const Math::Vector3d &pos, int minVol, int maxVol, float maxDist, int &volume, int &balance) {
 	// Note: This is only used in Grim. See SoundTrack::updatePosition for the corresponding implementation in EMI.
 
-	// distance calculation
-	Math::Vector3d cameraPos = _currSetup->_pos;
-	Math::Vector3d vector = pos - cameraPos;
-	float distance = vector.getMagnitude();
-	float diffVolume = maxVol - minVol;
-	// This 8.f is a guess, so it may need some adjusting
-	int newVolume = (int)(8.f * diffVolume / distance);
-	newVolume += minVol;
-	if (newVolume > _maxVolume)
-		newVolume = _maxVolume;
-	volume = newVolume;
-	float angle;
+	// The volume doesn't change if the sound is closer than the radius
+	Math::Vector3d vector = pos - _currSetup->_pos;
+	float distance = normalize3QuickAcc(vector);
+	bool hasVolume = false;
+
+	if (distance - kSoundRadius >= 0.0f) {
+		// These are unsigned like in the original, so a negative volume ends up as the maximum one
+		uint32 minVolume = minVol;
+		uint32 maxVolume = maxVol;
+		uint32 newVolume = minVolume;
+
+		// The original could divide by zero here, let's avoid that...
+		if (maxDist > 0.0f)
+			newVolume = (int)((maxDist - (distance - kSoundRadius)) * ((float)(maxVol - minVol) / maxDist) + minVol);
+
+		if (newVolume >= minVolume) {
+			if (newVolume > maxVolume)
+				newVolume = maxVolume;
+
+			volume = newVolume;
+		} else {
+			volume = minVolume;
+		}
+
+		hasVolume = true;
+	}
+
+	// In the original the division by zero gives a vector of NaNs, which ends up as the leftmost pan...
+	if (distance == 0.0f) {
+		balance = 0;
+		return hasVolume;
+	}
 
 	Math::Vector3d cameraVector = _currSetup->_interest - _currSetup->_pos;
 	Math::Vector3d up(0, 0, 1);
@@ -1057,10 +1167,11 @@ void Set::calculateSoundPosition(const Math::Vector3d &pos, int minVol, int maxV
 	     cameraVector * Math::Vector3d::dotProduct(cameraVector, up) * (1 - cosr);
 	right = Math::Vector3d::crossProduct(cameraVector, up);
 	right.normalize();
-	angle = atan2(Math::Vector3d::dotProduct(vector, right), Math::Vector3d::dotProduct(vector, cameraVector));
 
-	float pan = sin(angle);
-	balance = (int)((pan + 1.f) / 2.f * 127.f + 0.5f);
+	float pan = CLIP(Math::Vector3d::dotProduct(vector, right) * kSoundPanFactor, -1.f, 1.f);
+	balance = MIN((int)((pan + 1.f) * 64.f), 127);
+
+	return hasVolume;
 }
 
 Sector *Set::getSectorBase(int id) {
diff --git a/engines/grim/set.h b/engines/grim/set.h
index 140fb0cfd86..1e2179db422 100644
--- a/engines/grim/set.h
+++ b/engines/grim/set.h
@@ -69,8 +69,10 @@ public:
 	void setupLights(const Math::Vector3d &pos, bool inOverworld);
 
 	void setSoundPosition(const char *soundName, const Math::Vector3d &pos);
-	void setSoundPosition(const char *soundName, const Math::Vector3d &pos, int minVol, int maxVol);
-	void calculateSoundPosition(const Math::Vector3d &pos, int minVol, int maxVol, int &volume, int &balance);
+	void setSoundPosition(const char *soundName, const Math::Vector3d &pos, int minVol, int maxVol, float maxDist);
+	void setSoundPosition(int soundId, const Math::Vector3d &pos, int minVol, int maxVol, float maxDist);
+	void relocateSounds();
+	bool calculateSoundPosition(const Math::Vector3d &pos, int minVol, int maxVol, float maxDist, int &volume, int &balance);
 	void setSoundParameters(int minVolume, int maxVolume);
 	void getSoundParameters(int *minVolume, int *maxVolume);
 
@@ -172,6 +174,22 @@ private:
 	typedef Common::List<ObjectState::Ptr> StateList;
 	StateList _states;
 
+	// A sound with a position in the set, which has to be updated when the camera changes
+	struct SoundPosition {
+		Common::String name;	// Empty if the sound is identified by a number
+		int soundId;
+		Math::Vector3d pos;
+		int minVol, maxVol;
+		float maxDist;
+	};
+	Common::List<SoundPosition> _soundPositions;
+
+	const char *getSoundKey(const SoundPosition &sound) const;
+	bool isSoundPlaying(const SoundPosition &sound) const;
+	void addSoundPosition(const SoundPosition &newSound);
+	void updateSoundPosition(const SoundPosition &sound);
+	void removeStoppedSounds();
+
 	Math::Frustum _frustum;
 
 	friend class GrimEngine;


Commit: 75e5d511d7c4bcafb1b86966004188b2c1ffe224
    https://github.com/scummvm/scummvm/commit/75e5d511d7c4bcafb1b86966004188b2c1ffe224
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Implement 3D speech positioning

Changed paths:
    engines/grim/actor.cpp
    engines/grim/actor.h
    engines/grim/grim.cpp
    engines/grim/lua_v1.cpp
    engines/grim/lua_v1.h
    engines/grim/lua_v1_actor.cpp
    engines/grim/lua_v1_graphics.cpp
    engines/grim/lua_v1_sound.cpp
    engines/grim/set.cpp
    engines/grim/set.h


diff --git a/engines/grim/actor.cpp b/engines/grim/actor.cpp
index 21ecb1e0486..0f6979e508b 100644
--- a/engines/grim/actor.cpp
+++ b/engines/grim/actor.cpp
@@ -29,6 +29,7 @@
 #include "engines/grim/lipsync.h"
 #include "engines/grim/movie/movie.h"
 #include "engines/grim/sound.h"
+#include "engines/grim/imuse/dimuse_defs.h"
 #include "engines/grim/lua.h"
 #include "engines/grim/resource.h"
 #include "engines/grim/savegame.h"
@@ -92,7 +93,7 @@ Actor::Actor() :
 		_globalAlpha(1.f), _alphaMode(AlphaOff),
 		 _mustPlaceText(false),
 		_puckOrient(false), _talking(false),
-		_inOverworld(false), _drawnToClean(false), _backgroundTalk(false),
+		_inOverworld(false), _drawnToClean(false), _backgroundTalk(false), _voiceIs3D(false),
 		_sortOrder(0), _useParentSortOrder(false),
 		_sectorSortOrder(0), _hasSectorSortOrder(false), _fakeUnbound(false), _lightMode(LightFastDyn),
 		_hasFollowedBoxes(false), _lookAtActor(0) {
@@ -145,6 +146,7 @@ void Actor::saveState(SaveGame *savedState) const {
 	savedState->writeString(_talkSoundName);
 	savedState->writeBool(_talking);
 	savedState->writeBool(_backgroundTalk);
+	savedState->writeBool(_voiceIs3D);
 
 	savedState->writeLEUint32((uint32)_collisionMode);
 	savedState->writeFloat(_collisionScale);
@@ -303,6 +305,9 @@ bool Actor::restoreState(SaveGame *savedState) {
 	_talkSoundName      = savedState->readString();
 	_talking = savedState->readBool();
 	_backgroundTalk = savedState->readBool();
+	if (savedState->saveMinorVersion() >= 30)
+		_voiceIs3D = savedState->readBool();
+
 	if (isTalking()) {
 		g_grim->addTalkingActor(this);
 	}
@@ -1191,7 +1196,15 @@ void Actor::sayLine(const char *msgId, bool background, float x, float y) {
 		if (g_grim->getGameType() == GType_GRIM && getCurrentCostume()) {
 			_talkDelay = 500;
 		}
-		g_sound->startVoice(_talkSoundName.c_str(), 127, 64, background);
+		bool started = g_sound->startVoice(_talkSoundName.c_str(), 127, 64, background);
+
+		// The voice can be positioned in the set, like the original does
+		if (started && _voiceIs3D && currSet && g_grim->getGameType() == GType_GRIM) {
+			if (background)
+				currSet->setSoundPosition(_talkSoundName.c_str(), getPos(), 20, 127, kSoundDefaultMaxDist, kSoundDefaultRadius);
+			else
+				currSet->setSoundPosition(kTalkSoundID, getPos(), 20, 127, kSoundDefaultMaxDist, kSoundDefaultRadius);
+		}
 	}
 
 	// If the actor is clearly not visible then don't try to play the lip sync
diff --git a/engines/grim/actor.h b/engines/grim/actor.h
index 4994b937195..feed0db6136 100644
--- a/engines/grim/actor.h
+++ b/engines/grim/actor.h
@@ -134,6 +134,7 @@ public:
 	 * @see getTalkColor
 	 */
 	void setTalkColor(const Color &color) { _talkColor = color; }
+	void setVoiceIs3D(bool is3D) { _voiceIs3D = is3D; }
 	/**
 	 * Returns the color of the subtitles of the actor.
 	 *
@@ -614,6 +615,7 @@ private:
 	Common::String _talkSoundName;
 	bool _talking;
 	bool _backgroundTalk;
+	bool _voiceIs3D;
 	ObjectPtr<LipSync> _lipSync;
 	Common::List<Costume *> _costumeStack;
 
diff --git a/engines/grim/grim.cpp b/engines/grim/grim.cpp
index 07d36b05fb8..c0d128b63df 100644
--- a/engines/grim/grim.cpp
+++ b/engines/grim/grim.cpp
@@ -1237,6 +1237,9 @@ void GrimEngine::savegameRestore() {
 	Set::getPool().restoreObjects(_savedState);
 	Debug::debug(Debug::Engine, "Sets restored successfully.");
 
+	if (g_imuse)
+		g_imuse->floodMusicBuffer();
+
 	TextObject::getPool().restoreObjects(_savedState);
 	Debug::debug(Debug::Engine, "TextObjects restored successfully.");
 
@@ -1546,6 +1549,9 @@ void GrimEngine::setSet(Set *scene) {
 	if (scene == _currSet)
 		return;
 
+	if (g_imuse)
+		g_imuse->floodMusicBuffer();
+
 	if (getGameType() == GType_MONKEY4) {
 		for (PoolSound *s : PoolSound::getPool()) {
 			s->stop();
@@ -1560,7 +1566,7 @@ void GrimEngine::setSet(Set *scene) {
 
 	Set *lastSet = _currSet;
 	_currSet = scene;
-	_currSet->setSoundParameters(20, 127);
+	_currSet->setSoundParameters();
 	// should delete the old scene after setting the new one
 	if (lastSet && !lastSet->_locked) {
 		delete lastSet;
@@ -1574,7 +1580,7 @@ void GrimEngine::makeCurrentSetup(int num) {
 	int prevSetup = g_grim->getCurrSet()->getSetup();
 	if (prevSetup != num) {
 		getCurrSet()->setSetup(num);
-		getCurrSet()->setSoundParameters(20, 127);
+		getCurrSet()->setSoundParameters();
 		cameraChangeHandle(prevSetup, num);
 
 		if (getGameType() == GType_GRIM)
diff --git a/engines/grim/lua_v1.cpp b/engines/grim/lua_v1.cpp
index 8b80aa1f47e..24af3a32a01 100644
--- a/engines/grim/lua_v1.cpp
+++ b/engines/grim/lua_v1.cpp
@@ -896,6 +896,9 @@ struct luaL_reg grimMainOpcodes[] = {
 	{ "PlaySoundAt", LUA_OPCODE(Lua_V1, PlaySoundAt) },
 	{ "IsSoundPlaying", LUA_OPCODE(Lua_V1, IsSoundPlaying) },
 	{ "SetSoundPosition", LUA_OPCODE(Lua_V1, SetSoundPosition) },
+	{ "SetSoundParameters", LUA_OPCODE(Lua_V1, SetSoundParameters) },
+	{ "GetSoundParameters", LUA_OPCODE(Lua_V1, GetSoundParameters) },
+	{ "ActorVoiceIs3D", LUA_OPCODE(Lua_V1, ActorVoiceIs3D) },
 	{ "FileFindFirst", LUA_OPCODE(Lua_V1, FileFindFirst) },
 	{ "FileFindNext", LUA_OPCODE(Lua_V1, FileFindNext) },
 	{ "FileFindDispose", LUA_OPCODE(Lua_V1, FileFindDispose) },
diff --git a/engines/grim/lua_v1.h b/engines/grim/lua_v1.h
index 5524be0fc32..e4d89b88070 100644
--- a/engines/grim/lua_v1.h
+++ b/engines/grim/lua_v1.h
@@ -178,6 +178,9 @@ protected:
 	DECLARE_LUA_OPCODE(SaveIMuse);
 	DECLARE_LUA_OPCODE(RestoreIMuse);
 	DECLARE_LUA_OPCODE(SetSoundPosition);
+	DECLARE_LUA_OPCODE(SetSoundParameters);
+	DECLARE_LUA_OPCODE(GetSoundParameters);
+	DECLARE_LUA_OPCODE(ActorVoiceIs3D);
 	DECLARE_LUA_OPCODE(IsSoundPlaying);
 	DECLARE_LUA_OPCODE(PlaySoundAt);
 	DECLARE_LUA_OPCODE(FileFindDispose);
diff --git a/engines/grim/lua_v1_actor.cpp b/engines/grim/lua_v1_actor.cpp
index e7a045ab678..c20e4bb8856 100644
--- a/engines/grim/lua_v1_actor.cpp
+++ b/engines/grim/lua_v1_actor.cpp
@@ -82,6 +82,17 @@ void Lua_V1::SetActorTalkColor() {
 	actor->setTalkColor(getcolor(colorObj));
 }
 
+void Lua_V1::ActorVoiceIs3D() {
+	lua_Object actorObj = lua_getparam(1);
+	lua_Object is3DObj = lua_getparam(2);
+
+	if (!lua_isuserdata(actorObj) || lua_tag(actorObj) != MKTAG('A','C','T','R'))
+		return;
+
+	Actor *actor = getactor(actorObj);
+	actor->setVoiceIs3D(!lua_isnil(is3DObj));
+}
+
 void Lua_V1::GetActorTalkColor() {
 	lua_Object actorObj = lua_getparam(1);
 	if (!lua_isuserdata(actorObj) || lua_tag(actorObj) != MKTAG('A','C','T','R')) {
diff --git a/engines/grim/lua_v1_graphics.cpp b/engines/grim/lua_v1_graphics.cpp
index ca9946c1432..a7e9e2f7548 100644
--- a/engines/grim/lua_v1_graphics.cpp
+++ b/engines/grim/lua_v1_graphics.cpp
@@ -28,6 +28,7 @@
 #include "engines/grim/gfx_base.h"
 #include "engines/grim/set.h"
 #include "engines/grim/actor.h"
+#include "engines/grim/imuse/dimuse_engine.h"
 #include "engines/grim/movie/movie.h"
 #include "engines/grim/lua/lua.h"
 
@@ -96,6 +97,10 @@ void Lua_V1::StartMovie() {
 		lua_pushnil();
 		return;
 	}
+
+	if (g_imuse)
+		g_imuse->floodMusicBuffer();
+
 	int x = 0, y = 0;
 	if (!lua_isnil(lua_getparam(3)))
 		x = (int)lua_getnumber(lua_getparam(3));
diff --git a/engines/grim/lua_v1_sound.cpp b/engines/grim/lua_v1_sound.cpp
index 045434b9294..20be48004ef 100644
--- a/engines/grim/lua_v1_sound.cpp
+++ b/engines/grim/lua_v1_sound.cpp
@@ -206,13 +206,14 @@ void Lua_V1::SetSoundPosition() {
 	Math::Vector3d pos;
 	int minVolume = 10;
 	int maxVolume = 127;
-	float maxDist = 8.0f;
+	float maxDist = kSoundDefaultMaxDist;
+	float panFactor, maxRadius;
 	int argId = 1;
 	lua_Object paramObj;
 
-	if (g_grim->getCurrSet()) {
-		g_grim->getCurrSet()->getSoundParameters(&minVolume, &maxVolume);
-	}
+	// Use the room defaults if a room is currently set
+	if (g_grim->getCurrSet())
+		g_grim->getCurrSet()->getSoundParameters(&maxDist, &minVolume, &maxVolume, &panFactor, &maxRadius);
 
 	lua_Object nameObj = lua_getparam(argId++);
 	if (!lua_isnumber(nameObj) && !lua_isstring(nameObj))
@@ -255,10 +256,66 @@ void Lua_V1::SetSoundPosition() {
 
 	if (g_grim->getCurrSet()) {
 		if (lua_isnumber(nameObj))
-			g_grim->getCurrSet()->setSoundPosition((int)lua_getnumber(nameObj), pos, minVolume, maxVolume, maxDist);
+			g_grim->getCurrSet()->setSoundPosition((int)lua_getnumber(nameObj), pos, minVolume, maxVolume, maxDist, kSoundDefaultRadius);
 		else
-			g_grim->getCurrSet()->setSoundPosition(lua_getstring(nameObj), pos, minVolume, maxVolume, maxDist);
+			g_grim->getCurrSet()->setSoundPosition(lua_getstring(nameObj), pos, minVolume, maxVolume, maxDist, kSoundDefaultRadius);
+	}
+}
+
+void Lua_V1::SetSoundParameters() {
+	lua_Object maxDistObj = lua_getparam(1);
+	lua_Object minVolObj = lua_getparam(2);
+	lua_Object maxVolObj = lua_getparam(3);
+	lua_Object panFactorObj = lua_getparam(4);
+	lua_Object maxRadiusObj = lua_getparam(5);
+
+	Set *currSet = g_grim->getCurrSet();
+	if (!currSet) {
+		warning("SetSoundParameters: No current room!");
+		return;
+	}
+
+	if (lua_isnil(maxDistObj) && lua_isnil(minVolObj) && lua_isnil(maxVolObj) &&
+		lua_isnil(panFactorObj) && lua_isnil(maxRadiusObj)) {
+		// Reset all parameters
+		currSet->setSoundParameters();
+		return;
 	}
+
+	// The current values are kept for the parameters which aren't specified
+	float maxDist, panFactor, maxRadius;
+	int minVol, maxVol;
+	currSet->getSoundParameters(&maxDist, &minVol, &maxVol, &panFactor, &maxRadius);
+
+	if (!lua_isnil(maxDistObj))
+		maxDist = lua_getnumber(maxDistObj);
+	// The volumes are bytes in the original
+	if (!lua_isnil(minVolObj))
+		minVol = (uint8)(int)lua_getnumber(minVolObj);
+	if (!lua_isnil(maxVolObj))
+		maxVol = (uint8)(int)lua_getnumber(maxVolObj);
+	if (!lua_isnil(panFactorObj))
+		panFactor = lua_getnumber(panFactorObj);
+	if (!lua_isnil(maxRadiusObj))
+		maxRadius = lua_getnumber(maxRadiusObj);
+
+	currSet->setSoundParameters(maxDist, minVol, maxVol, panFactor, maxRadius);
+}
+
+void Lua_V1::GetSoundParameters() {
+	Set *currSet = g_grim->getCurrSet();
+	if (!currSet)
+		return;
+
+	float maxDist, panFactor, maxRadius;
+	int minVol, maxVol;
+	currSet->getSoundParameters(&maxDist, &minVol, &maxVol, &panFactor, &maxRadius);
+
+	lua_pushnumber(maxDist);
+	lua_pushnumber(minVol);
+	lua_pushnumber(maxVol);
+	lua_pushnumber(panFactor);
+	lua_pushnumber(maxRadius);
 }
 
 void Lua_V1::IsSoundPlaying() {
diff --git a/engines/grim/set.cpp b/engines/grim/set.cpp
index 8af92fb038a..aa214bcb2a6 100644
--- a/engines/grim/set.cpp
+++ b/engines/grim/set.cpp
@@ -36,11 +36,6 @@
 
 namespace Grim {
 
-// Default sound parameters of a room in the original
-static const float kSoundDefaultMaxDist = 8.0f;
-static const float kSoundPanFactor = 1.5f;
-static const float kSoundRadius = 0.8f;
-
 // The original normalizes the vector with an approximation of its length, which it returns too
 static float normalize3QuickAcc(Math::Vector3d &vector) {
 	float x = ABS(vector.x());
@@ -63,7 +58,8 @@ static float normalize3QuickAcc(Math::Vector3d &vector) {
 }
 
 Set::Set(const Common::String &sceneName, Common::SeekableReadStream *data) :
-		_locked(false), _name(sceneName), _enableLights(false) {
+		_locked(false), _name(sceneName), _enableLights(false), _soundMaxDist(kSoundDefaultMaxDist),
+		_soundPanFactor(kSoundDefaultPanFactor), _soundMaxRadius(kSoundDefaultRadius) {
 
 	char header[7];
 	data->read(header, 7);
@@ -81,7 +77,9 @@ Set::Set() :
 		_cmaps(nullptr), _locked(false), _enableLights(false), _numSetups(0),
 		_numLights(0), _numSectors(0), _numObjectStates(0), _minVolume(0),
 		_maxVolume(0), _numCmaps(0), _numShadows(0), _currSetup(nullptr),
-		_setups(nullptr), _lights(nullptr), _sectors(nullptr), _shadows(nullptr) {
+		_setups(nullptr), _lights(nullptr), _sectors(nullptr), _shadows(nullptr),
+		_soundMaxDist(kSoundDefaultMaxDist), _soundPanFactor(kSoundDefaultPanFactor),
+		_soundMaxRadius(kSoundDefaultRadius) {
 	setupOverworldLights();
 }
 
@@ -280,6 +278,9 @@ void Set::saveState(SaveGame *savedState) const {
 	savedState->writeBool(_enableLights);
 	savedState->writeLESint32(_minVolume);
 	savedState->writeLESint32(_maxVolume);
+	savedState->writeFloat(_soundMaxDist);
+	savedState->writeFloat(_soundPanFactor);
+	savedState->writeFloat(_soundMaxRadius);
 
 	savedState->writeLEUint32(_states.size());
 	for (StateList::const_iterator i = _states.begin(); i != _states.end(); ++i) {
@@ -328,6 +329,12 @@ bool Set::restoreState(SaveGame *savedState) {
 	_minVolume        = savedState->readLESint32();
 	_maxVolume        = savedState->readLESint32();
 
+	if (savedState->saveMinorVersion() >= 30) {
+		_soundMaxDist = savedState->readFloat();
+		_soundPanFactor = savedState->readFloat();
+		_soundMaxRadius = savedState->readFloat();
+	}
+
 	_numObjectStates = savedState->readLESint32();
 	_states.clear();
 	for (int i = 0; i < _numObjectStates; ++i) {
@@ -1046,10 +1053,10 @@ void Set::setLightPosition(int light, const Math::Vector3d &pos) {
 }
 
 void Set::setSoundPosition(const char *soundName, const Math::Vector3d &pos) {
-	setSoundPosition(soundName, pos, _minVolume, _maxVolume, kSoundDefaultMaxDist);
+	setSoundPosition(soundName, pos, _minVolume, _maxVolume, _soundMaxDist, _soundMaxRadius);
 }
 
-void Set::setSoundPosition(const char *soundName, const Math::Vector3d &pos, int minVol, int maxVol, float maxDist) {
+void Set::setSoundPosition(const char *soundName, const Math::Vector3d &pos, int minVol, int maxVol, float maxDist, float radius) {
 	SoundPosition sound;
 	sound.name = soundName;
 	sound.soundId = 0;
@@ -1057,16 +1064,18 @@ void Set::setSoundPosition(const char *soundName, const Math::Vector3d &pos, int
 	sound.minVol = minVol;
 	sound.maxVol = maxVol;
 	sound.maxDist = maxDist;
+	sound.radius = radius;
 	addSoundPosition(sound);
 }
 
-void Set::setSoundPosition(int soundId, const Math::Vector3d &pos, int minVol, int maxVol, float maxDist) {
+void Set::setSoundPosition(int soundId, const Math::Vector3d &pos, int minVol, int maxVol, float maxDist, float radius) {
 	SoundPosition sound;
 	sound.soundId = soundId;
 	sound.pos = pos;
 	sound.minVol = minVol;
 	sound.maxVol = maxVol;
 	sound.maxDist = maxDist;
+	sound.radius = radius;
 	addSoundPosition(sound);
 }
 
@@ -1114,13 +1123,13 @@ void Set::updateSoundPosition(const SoundPosition &sound) {
 	int newVolume, newBalance;
 	const char *soundKey = getSoundKey(sound);
 
-	if (calculateSoundPosition(sound.pos, sound.minVol, sound.maxVol, sound.maxDist, newVolume, newBalance))
+	if (calculateSoundPosition(sound.pos, sound.minVol, sound.maxVol, sound.maxDist, sound.radius, newVolume, newBalance))
 		g_sound->setVolume(soundKey, newVolume);
 
 	g_sound->setPan(soundKey, newBalance);
 }
 
-bool Set::calculateSoundPosition(const Math::Vector3d &pos, int minVol, int maxVol, float maxDist, int &volume, int &balance) {
+bool Set::calculateSoundPosition(const Math::Vector3d &pos, int minVol, int maxVol, float maxDist, float radius, int &volume, int &balance) {
 	// Note: This is only used in Grim. See SoundTrack::updatePosition for the corresponding implementation in EMI.
 
 	// The volume doesn't change if the sound is closer than the radius
@@ -1128,7 +1137,7 @@ bool Set::calculateSoundPosition(const Math::Vector3d &pos, int minVol, int maxV
 	float distance = normalize3QuickAcc(vector);
 	bool hasVolume = false;
 
-	if (distance - kSoundRadius >= 0.0f) {
+	if (distance - radius >= 0.0f) {
 		// These are unsigned like in the original, so a negative volume ends up as the maximum one
 		uint32 minVolume = minVol;
 		uint32 maxVolume = maxVol;
@@ -1136,7 +1145,7 @@ bool Set::calculateSoundPosition(const Math::Vector3d &pos, int minVol, int maxV
 
 		// The original could divide by zero here, let's avoid that...
 		if (maxDist > 0.0f)
-			newVolume = (int)((maxDist - (distance - kSoundRadius)) * ((float)(maxVol - minVol) / maxDist) + minVol);
+			newVolume = (int)((maxDist - (distance - radius)) * ((float)(maxVol - minVol) / maxDist) + minVol);
 
 		if (newVolume >= minVolume) {
 			if (newVolume > maxVolume)
@@ -1168,7 +1177,7 @@ bool Set::calculateSoundPosition(const Math::Vector3d &pos, int minVol, int maxV
 	right = Math::Vector3d::crossProduct(cameraVector, up);
 	right.normalize();
 
-	float pan = CLIP(Math::Vector3d::dotProduct(vector, right) * kSoundPanFactor, -1.f, 1.f);
+	float pan = CLIP(Math::Vector3d::dotProduct(vector, right) * _soundPanFactor, -1.f, 1.f);
 	balance = MIN((int)((pan + 1.f) * 64.f), 127);
 
 	return hasVolume;
@@ -1211,14 +1220,20 @@ Sector *Set::getSectorBySubstring(const Common::String &str, const Math::Vector3
 	return nullptr;
 }
 
-void Set::setSoundParameters(int minVolume, int maxVolume) {
+void Set::setSoundParameters(float maxDist, int minVolume, int maxVolume, float panFactor, float maxRadius) {
+	_soundMaxDist = maxDist;
 	_minVolume = minVolume;
 	_maxVolume = maxVolume;
+	_soundPanFactor = panFactor;
+	_soundMaxRadius = maxRadius;
 }
 
-void Set::getSoundParameters(int *minVolume, int *maxVolume) {
+void Set::getSoundParameters(float *maxDist, int *minVolume, int *maxVolume, float *panFactor, float *maxRadius) {
+	*maxDist = _soundMaxDist;
 	*minVolume = _minVolume;
 	*maxVolume = _maxVolume;
+	*panFactor = _soundPanFactor;
+	*maxRadius = _soundMaxRadius;
 }
 
 void Set::addObjectState(const ObjectState::Ptr &s) {
diff --git a/engines/grim/set.h b/engines/grim/set.h
index 1e2179db422..cc127fb2655 100644
--- a/engines/grim/set.h
+++ b/engines/grim/set.h
@@ -41,6 +41,11 @@ class CMap;
 struct Light;
 struct SetShadow;
 
+// Default sound parameters of a room in the original
+static const float kSoundDefaultMaxDist = 8.0f;
+static const float kSoundDefaultPanFactor = 1.5f;
+static const float kSoundDefaultRadius = 0.8f;
+
 class Set : public PoolObject<Set> {
 public:
 	Set(const Common::String &name, Common::SeekableReadStream *data);
@@ -69,12 +74,15 @@ public:
 	void setupLights(const Math::Vector3d &pos, bool inOverworld);
 
 	void setSoundPosition(const char *soundName, const Math::Vector3d &pos);
-	void setSoundPosition(const char *soundName, const Math::Vector3d &pos, int minVol, int maxVol, float maxDist);
-	void setSoundPosition(int soundId, const Math::Vector3d &pos, int minVol, int maxVol, float maxDist);
+	void setSoundPosition(const char *soundName, const Math::Vector3d &pos, int minVol, int maxVol, float maxDist, float radius);
+	void setSoundPosition(int soundId, const Math::Vector3d &pos, int minVol, int maxVol, float maxDist, float radius);
 	void relocateSounds();
-	bool calculateSoundPosition(const Math::Vector3d &pos, int minVol, int maxVol, float maxDist, int &volume, int &balance);
-	void setSoundParameters(int minVolume, int maxVolume);
-	void getSoundParameters(int *minVolume, int *maxVolume);
+	bool calculateSoundPosition(const Math::Vector3d &pos, int minVol, int maxVol, float maxDist, float radius, int &volume, int &balance);
+
+	// Without arguments the sound parameters go back to the defaults of a room
+	void setSoundParameters(float maxDist = kSoundDefaultMaxDist, int minVolume = 20, int maxVolume = 127,
+							float panFactor = kSoundDefaultPanFactor, float maxRadius = kSoundDefaultRadius);
+	void getSoundParameters(float *maxDist, int *minVolume, int *maxVolume, float *panFactor, float *maxRadius);
 
 	const Common::String &getName() const { return _name; }
 
@@ -181,8 +189,12 @@ private:
 		Math::Vector3d pos;
 		int minVol, maxVol;
 		float maxDist;
+		float radius;
 	};
 	Common::List<SoundPosition> _soundPositions;
+	float _soundMaxDist;
+	float _soundPanFactor;
+	float _soundMaxRadius;
 
 	const char *getSoundKey(const SoundPosition &sound) const;
 	bool isSoundPlaying(const SoundPosition &sound) const;


Commit: 4fa87fe0d452db0997d127f6ea61a8db5636d3b3
    https://github.com/scummvm/scummvm/commit/4fa87fe0d452db0997d127f6ea61a8db5636d3b3
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Port original costume sound components

Costume sounds now use the priority and volumes of their
component and the room sound parameters for their position

Changed paths:
    engines/grim/costume.cpp
    engines/grim/costume/sound_component.cpp
    engines/grim/costume/sound_component.h


diff --git a/engines/grim/costume.cpp b/engines/grim/costume.cpp
index 2660f4b49f0..3c5d762fbb6 100644
--- a/engines/grim/costume.cpp
+++ b/engines/grim/costume.cpp
@@ -220,7 +220,7 @@ Component *Costume::loadComponent (tag32 tag, Component *parent, int parentID, c
 		return new MeshComponent(parent, parentID, name, tag);
 	else if (tag == MKTAG('L','U','A','V'))
 		return new LuaVarComponent(parent, parentID, name, tag);
-	else if (tag == MKTAG('I','M','L','S'))
+	else if (tag == MKTAG('I','M','L','S') || tag == MKTAG('I','M','S','S'))
 		return new SoundComponent(parent, parentID, name, tag);
 	else if (tag == MKTAG('B','K','N','D'))
 		return new BitmapComponent(parent, parentID, name, tag);
diff --git a/engines/grim/costume/sound_component.cpp b/engines/grim/costume/sound_component.cpp
index 35bdf04f71c..fc171a3175d 100644
--- a/engines/grim/costume/sound_component.cpp
+++ b/engines/grim/costume/sound_component.cpp
@@ -29,10 +29,14 @@
 namespace Grim {
 
 SoundComponent::SoundComponent(Component *p, int parentID, const char *filename, tag32 t) :
-		Component(p, parentID, filename, t) {
+		Component(p, parentID, filename, t), _maxVolume(127), _pan(64), _priority(100), _minVolume(1) {
+	// The name can be followed by the maximum volume, the pan, the priority and the minimum volume
 	const char *comma = strchr(filename, ',');
 	if (comma) {
 		_name = Common::String(filename, comma);
+		sscanf(comma + 1, "%d,%d,%d,%d", &_maxVolume, &_pan, &_priority, &_minVolume);
+	} else {
+		_name = filename;
 	}
 }
 
@@ -45,15 +49,30 @@ void SoundComponent::setKey(int val) {
 	switch (val) {
 	case 0: // "Play"
 		if (!g_imuse->soundsIsSoundPlaying(_name.c_str())) {
-			g_imuse->soundsLoadStartSound(_name.c_str(), 127, DIMUSE_GROUP_SFX);
-			if (g_grim->getCurrSet()) {
-				Math::Vector3d pos = _cost->getMatrix().getPosition();
-				g_grim->getCurrSet()->setSoundPosition(_name.c_str(), pos);
+			if (isComponentType('I','M','S','S')) {
+				g_imuse->soundStartVoiceStream(_name.c_str(), _maxVolume, _pan);
+				g_imuse->soundsSetParam(_name.c_str(), DIMUSE_P_GROUP, DIMUSE_GROUP_SFX);
+				g_imuse->soundsSetParam(_name.c_str(), DIMUSE_P_PRIORITY, _priority);
+			} else {
+				g_imuse->soundsLoadStartSound(_name.c_str(), _priority, DIMUSE_GROUP_SFX);
+
+				Set *currSet = g_grim->getCurrSet();
+				if (currSet) {
+					float maxDist, panFactor, maxRadius;
+					int roomMinVolume, roomMaxVolume;
+					currSet->getSoundParameters(&maxDist, &roomMinVolume, &roomMaxVolume, &panFactor, &maxRadius);
+
+					Math::Vector3d pos = _cost->getMatrix().getPosition();
+					currSet->setSoundPosition(_name.c_str(), pos, MAX(roomMinVolume, _minVolume), MIN(roomMaxVolume, _maxVolume), maxDist, maxRadius);
+				}
 			}
 		}
 		break;
 	case 1: // "Stop"
-		g_imuse->soundsStopSound(_name.c_str());
+		if (isComponentType('I','M','S','S'))
+			g_imuse->soundStopVoiceStream();
+		else
+			g_imuse->soundsStopSound(_name.c_str());
 		break;
 	case 2: // "Stop Looping"
 		g_imuse->iMUSESetHook(_name.c_str(), 0x80);
diff --git a/engines/grim/costume/sound_component.h b/engines/grim/costume/sound_component.h
index 41cf1f6069c..cce1b207a7e 100644
--- a/engines/grim/costume/sound_component.h
+++ b/engines/grim/costume/sound_component.h
@@ -33,6 +33,12 @@ public:
 
 	void setKey(int val) override;
 	void reset() override;
+
+private:
+	int _maxVolume;
+	int _pan;
+	int _priority;
+	int _minVolume;
 };
 
 } // end of namespace Grim


Commit: 4aa1d3c5990e1d8a02d434f0cc305c104bc2ca61
    https://github.com/scummvm/scummvm/commit/4aa1d3c5990e1d8a02d434f0cc305c104bc2ca61
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Remove old iMUSE implementation files

Changed paths:
  R engines/grim/imuse/dimuse_codecs.cpp
  R engines/grim/imuse/dimuse_codecs.h
  R engines/grim/imuse/imuse.cpp
  R engines/grim/imuse/imuse.h
  R engines/grim/imuse/imuse_music.cpp
  R engines/grim/imuse/imuse_script.cpp
  R engines/grim/imuse/imuse_sndmgr.cpp
  R engines/grim/imuse/imuse_sndmgr.h
  R engines/grim/imuse/imuse_tables.cpp
  R engines/grim/imuse/imuse_tables.h
  R engines/grim/imuse/imuse_track.cpp
  R engines/grim/imuse/imuse_track.h
    engines/grim/module.mk


diff --git a/engines/grim/imuse/dimuse_codecs.cpp b/engines/grim/imuse/dimuse_codecs.cpp
deleted file mode 100644
index 2121e9e5cfa..00000000000
--- a/engines/grim/imuse/dimuse_codecs.cpp
+++ /dev/null
@@ -1,643 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#include "common/scummsys.h"
-#include "common/endian.h"
-#include "common/util.h"
-#include "engines/grim/imuse/dimuse_codecs.h"
-
-#include "audio/decoders/adpcm_intern.h"
-
-namespace Grim {
-
-namespace BundleCodecs {
-
-/*
- * The "IMC" codec below (see cases 13 & 15 in decompressCodec) is actually a
- * variant of the IMA codec, see also
- *   <https://multimedia.cx/simpleaudio.html>
- *
- * It is somewhat different, though: the standard ADPCM codecs use a fixed
- * size for their data packets (4 bits), while the codec implemented here
- * varies the size of each "packet" between 2 and 7 bits.
- */
-
-static byte *_destImcTable = nullptr;
-static uint32 *_destImcTable2 = nullptr;
-
-// This table is the "big brother" of Audio::ADPCMStream::_stepAdjustTable.
-static const byte imxOtherTable[6][64] = {
-	{
-		0xFF,
-		4
-	},
-
-	{
-		0xFF, 0xFF,
-		   2,    8
-	},
-
-	{
-		0xFF, 0xFF, 0xFF, 0xFF,
-		   1,    2,    4,    6
-	},
-
-	{
-		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
-		   1,    2,    4,    6,    8,   12,   16,   32
-	},
-
-	{
-		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
-		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
-		   1,    2,    4,    6,    8,   10,   12,   14,
-		  16,   18,   20,   22,   24,   26,   28,   32
-	},
-
-	{
-		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
-		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
-		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
-		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
-		   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
-	}
-};
-
-void releaseImcTables() {
-	free(_destImcTable);
-	_destImcTable = nullptr;
-	free(_destImcTable2);
-	_destImcTable2 = nullptr;
-}
-
-void initializeImcTables() {
-	int pos;
-
-	if (!_destImcTable) _destImcTable = (byte *)calloc(89, sizeof(byte));
-	if (!_destImcTable2) _destImcTable2 = (uint32 *)calloc(89 * 64, sizeof(uint32));
-
-	for (pos = 0; pos <= 88; ++pos) {
-		byte put = 1;
-		int32 tableValue = ((Audio::Ima_ADPCMStream::_imaTable[pos] * 4) / 7) / 2;
-		while (tableValue != 0) {
-			tableValue /= 2;
-			put++;
-		}
-		if (put < 3) {
-			put = 3;
-		}
-		if (put > 8) {
-			put = 8;
-		}
-		_destImcTable[pos] = put - 1;
-	}
-
-	for (int n = 0; n < 64; n++) {
-		for (pos = 0; pos <= 88; ++pos) {
-			int32 count = 32;
-			int32 put = 0;
-			int32 tableValue = Audio::Ima_ADPCMStream::_imaTable[pos];
-			do {
-				if ((count & n) != 0) {
-					put += tableValue;
-				}
-				count /= 2;
-				tableValue /= 2;
-			} while (count != 0);
-			_destImcTable2[n + pos * 64] = put;
-		}
-	}
-}
-
-#define NextBit                            \
-	do {                                   \
-		bit = mask & 1;                    \
-		mask >>= 1;                        \
-		if (!--bitsleft) {                 \
-			mask = READ_LE_UINT16(srcptr); \
-			srcptr += 2;                   \
-			bitsleft = 16;                 \
-		}                                  \
-	} while (0)
-
-static int32 compDecode(byte *src, byte *dst) {
-	byte *result, *srcptr = src, *dstptr = dst;
-	int data, size, bit, bitsleft = 16, mask = READ_LE_UINT16(srcptr);
-	srcptr += 2;
-
-	for (;;) {
-		NextBit;
-		if (bit) {
-			*dstptr++ = *srcptr++;
-		} else {
-			NextBit;
-			if (!bit) {
-				NextBit;
-				size = bit << 1;
-				NextBit;
-				size = (size | bit) + 3;
-				data = *srcptr++ | 0xffffff00;
-			} else {
-				data = *srcptr++;
-				size = *srcptr++;
-
-				data |= 0xfffff000 + ((size & 0xf0) << 4);
-				size = (size & 0x0f) + 3;
-
-				if (size == 3)
-					if (((*srcptr++) + 1) == 1)
-						return dstptr - dst;
-			}
-			result = dstptr + data;
-			while (size--)
-				*dstptr++ = *result++;
-		}
-	}
-}
-#undef NextBit
-
-int32 decompressADPCM(byte *compInput, byte *compOutput, int channels) {
-	byte *src;
-
-	// Decoder for the IMA ADPCM variants used in COMI.
-	// Contrary to regular IMA ADPCM, this codec uses a variable
-	// bitsize for the encoded data.
-
-	const int MAX_CHANNELS = 2;
-	int32 outputSamplesLeft;
-	int32 destPos;
-	int16 firstWord;
-	byte initialTablePos[MAX_CHANNELS] = {0, 0};
-	//int32 initialimcTableEntry[MAX_CHANNELS] = {7, 7};
-	int32 initialOutputWord[MAX_CHANNELS] = {0, 0};
-	int32 totalBitOffset, curTablePos, outputWord;
-	byte *dst;
-	int i;
-
-	// We only support mono and stereo
-	assert(channels == 1 || channels == 2);
-
-	src = compInput;
-	dst = compOutput;
-	outputSamplesLeft = 0x1000;
-
-	// Every data packet contains 0x2000 bytes of audio data
-	// when extracted. In order to encode bigger data sets,
-	// one has to split the data into multiple blocks.
-	//
-	// Every block starts with a 2 byte word. If that word is
-	// non-zero, it indicates the size of a block of raw audio
-	// data (not encoded) following it. That data we simply copy
-	// to the output buffer and then proceed by decoding the
-	// remaining data.
-	//
-	// If on the other hand the word is zero, then what follows
-	// are 7*channels bytes containing seed data for the decoder.
-	firstWord = READ_BE_UINT16(src);
-	src += 2;
-	if (firstWord != 0) {
-		// Copy raw data
-		memcpy(dst, src, firstWord);
-		dst += firstWord;
-		src += firstWord;
-		assert((firstWord & 1) == 0);
-		outputSamplesLeft -= firstWord / 2;
-	} else {
-		// Read the seed values for the decoder.
-		for (i = 0; i < channels; i++) {
-			initialTablePos[i] = *src;
-			src += 1;
-			//initialimcTableEntry[i] = READ_BE_UINT32(src);
-			src += 4;
-			initialOutputWord[i] = READ_BE_UINT32(src);
-			src += 4;
-		}
-	}
-
-	totalBitOffset = 0;
-	// The channels are encoded separately.
-	for (int chan = 0; chan < channels; chan++) {
-		// Read initial state (this makes it possible for the data stream
-		// to be split & spread across multiple data chunks.
-		curTablePos = initialTablePos[chan];
-		//imcTableEntry = initialimcTableEntry[chan];
-		outputWord = initialOutputWord[chan];
-
-		// We need to interleave the channels in the output; we achieve
-		// that by using a variables dest offset:
-		destPos = chan * 2;
-
-		const int bound = (channels == 1)
-							? outputSamplesLeft
-							: ((chan == 0)
-								? (outputSamplesLeft+1) / 2
-								: outputSamplesLeft / 2);
-		for (i = 0; i < bound; ++i) {
-			// Determine the size (in bits) of the next data packet
-			const int32 curTableEntryBitCount = _destImcTable[curTablePos];
-			assert(2 <= curTableEntryBitCount && curTableEntryBitCount <= 7);
-
-			// Read the next data packet
-			const byte *readPos = src + (totalBitOffset >> 3);
-			const uint16 readWord = (uint16)(READ_BE_UINT16(readPos) << (totalBitOffset & 7));
-			const byte packet = (byte)(readWord >> (16 - curTableEntryBitCount));
-
-			// Advance read position to the next data packet
-			totalBitOffset += curTableEntryBitCount;
-
-			// Decode the data packet into a delta value for the output signal.
-			const byte signBitMask = (1 << (curTableEntryBitCount - 1));
-			const byte dataBitMask = (signBitMask - 1);
-			const byte data = (packet & dataBitMask);
-
-			const int32 tmpA = (data << (7 - curTableEntryBitCount));
-			const int32 imcTableEntry = Audio::Ima_ADPCMStream::_imaTable[curTablePos] >> (curTableEntryBitCount - 1);
-			int32 delta = imcTableEntry + _destImcTable2[tmpA + (curTablePos * 64)];
-
-			// The topmost bit in the data packet tells is a sign bit
-			if ((packet & signBitMask) != 0) {
-				delta = -delta;
-			}
-
-			// Accumulate the delta onto the output data
-			outputWord += delta;
-
-			// Clip outputWord to 16 bit signed, and write it into the destination stream
-			outputWord = CLIP<int32>(outputWord, -0x8000, 0x7fff);
-
-			// This is being written as-is (LE), without concerns regarding endianness:
-			// this is because the internal DiMUSE mixer handles the data in LE format,
-			// and we'll convert data to the appropriate format using the QueuingAudioStream flags
-			// when flushing the final audio data to the output stream (see IMuseDigital::waveOutWrite())
-			WRITE_UINT16(dst + destPos, outputWord);
-
-			destPos += channels << 1;
-
-			// Adjust the curTablePos
-			curTablePos += (int8)imxOtherTable[curTableEntryBitCount - 2][data];
-			curTablePos = CLIP<int32>(curTablePos, 0, ARRAYSIZE(Audio::Ima_ADPCMStream::_imaTable) - 1);
-		}
-	}
-
-	return 0x2000;
-}
-
-int32 decompressCodec(int32 codec, byte *compInput, byte *compOutput, int32 inputSize) {
-	int32 outputSize;
-	int32 offset1, offset2, offset3, length, k, c, s, j, r, t, z;
-	byte *src, *t_table, *p, *ptr;
-	byte t_tmp1, t_tmp2;
-
-	switch (codec) {
-	case 0:
-		memcpy(compOutput, compInput, inputSize);
-		outputSize = inputSize;
-		break;
-
-	case 1:
-		outputSize = compDecode(compInput, compOutput);
-		break;
-
-	case 2:
-		outputSize = compDecode(compInput, compOutput);
-		p = compOutput;
-		for (z = 1; z < outputSize; z++)
-			p[z] += p[z - 1];
-		break;
-
-	case 3:
-		outputSize = compDecode(compInput, compOutput);
-		p = compOutput;
-		for (z = 2; z < outputSize; z++)
-			p[z] += p[z - 1];
-		for (z = 1; z < outputSize; z++)
-			p[z] += p[z - 1];
-		break;
-
-	case 4:
-		outputSize = compDecode(compInput, compOutput);
-		p = compOutput;
-		for (z = 2; z < outputSize; z++)
-			p[z] += p[z - 1];
-		for (z = 1; z < outputSize; z++)
-			p[z] += p[z - 1];
-
-		t_table = (byte *)calloc(outputSize, 1);
-		assert(t_table);
-
-		src = compOutput;
-		length = (outputSize << 3) / 12;
-		k = 0;
-		if (length > 0) {
-			c = -12;
-			s = 0;
-			j = 0;
-			do {
-				ptr = src + length + (k >> 1);
-				t_tmp2 = src[j];
-				if (k & 1) {
-					r = c >> 3;
-					t_table[r + 2] = ((t_tmp2 & 0x0f) << 4) | (ptr[1] >> 4);
-					t_table[r + 1] = (t_tmp2 & 0xf0) | (t_table[r + 1]);
-				} else {
-					r = s >> 3;
-					t_table[r + 0] = ((t_tmp2 & 0x0f) << 4) | (ptr[0] & 0x0f);
-					t_table[r + 1] = t_tmp2 >> 4;
-				}
-				s += 12;
-				c += 12;
-				k++;
-				j++;
-			} while (k < length);
-		}
-		offset1 = ((length - 1) * 3) >> 1;
-		t_table[offset1 + 1] = (t_table[offset1 + 1]) | (src[length - 1] & 0xf0);
-		memcpy(src, t_table, outputSize);
-		free(t_table);
-		break;
-
-	case 5:
-		outputSize = compDecode(compInput, compOutput);
-		p = compOutput;
-		for (z = 2; z < outputSize; z++)
-			p[z] += p[z - 1];
-		for (z = 1; z < outputSize; z++)
-			p[z] += p[z - 1];
-
-		t_table = (byte *)malloc(outputSize);
-		assert(t_table);
-
-		src = compOutput;
-		length = (outputSize << 3) / 12;
-		k = 1;
-		c = 0;
-		s = 12;
-		t_table[0] = src[length] >> 4;
-		t = length + k;
-		j = 1;
-		if (t > k) {
-			do {
-				t_tmp1 = *(src + length + (k >> 1));
-				t_tmp2 = src[j - 1];
-				if (k & 1) {
-					r = c >> 3;
-					t_table[r + 0] = (t_tmp2 & 0xf0) | t_table[r];
-					t_table[r + 1] = ((t_tmp2 & 0x0f) << 4) | (t_tmp1 & 0x0f);
-				} else {
-					r = s >> 3;
-					t_table[r + 0] = t_tmp2 >> 4;
-					t_table[r - 1] = ((t_tmp2 & 0x0f) << 4) | (t_tmp1 >> 4);
-				}
-				s += 12;
-				c += 12;
-				k++;
-				j++;
-			} while (k < t);
-		}
-		memcpy(src, t_table, outputSize);
-		free(t_table);
-		break;
-
-	case 6:
-		outputSize = compDecode(compInput, compOutput);
-		p = compOutput;
-		for (z = 2; z < outputSize; z++)
-			p[z] += p[z - 1];
-		for (z = 1; z < outputSize; z++)
-			p[z] += p[z - 1];
-
-		t_table = (byte *)malloc(outputSize);
-		assert(t_table);
-
-		src = compOutput;
-		length = (outputSize << 3) / 12;
-		k = 0;
-		c = 0;
-		j = 0;
-		s = -12;
-		t_table[0] = src[outputSize - 1];
-		t_table[outputSize - 1] = src[length - 1];
-		t = length - 1;
-		if (t > 0) {
-			do {
-				t_tmp1 = *(src + length + (k >> 1));
-				t_tmp2 = src[j];
-				if (k & 1) {
-					r = s >> 3;
-					t_table[r + 2] = (t_tmp2 & 0xf0) | t_table[r + 2];
-					t_table[r + 3] = ((t_tmp2 & 0x0f) << 4) | (t_tmp1 >> 4);
-				} else {
-					r = c >> 3;
-					t_table[r + 2] = t_tmp2 >> 4;
-					t_table[r + 1] = ((t_tmp2 & 0x0f) << 4) | (t_tmp1 & 0x0f);
-				}
-				s += 12;
-				c += 12;
-				k++;
-				j++;
-			} while (k < t);
-		}
-		memcpy(src, t_table, outputSize);
-		free(t_table);
-		break;
-
-	case 10:
-		outputSize = compDecode(compInput, compOutput);
-		p = compOutput;
-		for (z = 2; z < outputSize; z++)
-			p[z] += p[z - 1];
-		for (z = 1; z < outputSize; z++)
-			p[z] += p[z - 1];
-
-		t_table = (byte *)malloc(outputSize);
-		assert(t_table);
-		memcpy(t_table, p, outputSize);
-
-		offset1 = outputSize / 3;
-		offset2 = offset1 << 1;
-		offset3 = offset2;
-		src = compOutput;
-
-		while (offset1--) {
-			offset2 -= 2;
-			offset3--;
-			t_table[offset2 + 0] = src[offset1];
-			t_table[offset2 + 1] = src[offset3];
-		}
-
-		src = compOutput;
-		length = (outputSize << 3) / 12;
-		k = 0;
-		if (length > 0) {
-			c = -12;
-			s = 0;
-			do {
-				j = length + (k >> 1);
-				t_tmp1 = t_table[k];
-				if (k & 1) {
-					r = c >> 3;
-					t_tmp2 = t_table[j + 1];
-					src[r + 2] = ((t_tmp1 & 0x0f) << 4) | (t_tmp2 >> 4);
-					src[r + 1] = (src[r + 1]) | (t_tmp1 & 0xf0);
-				} else {
-					r = s >> 3;
-					t_tmp2 = t_table[j];
-					src[r + 0] = ((t_tmp1 & 0x0f) << 4) | (t_tmp2 & 0x0f);
-					src[r + 1] = t_tmp1 >> 4;
-				}
-				s += 12;
-				c += 12;
-				k++;
-			} while (k < length);
-		}
-		offset1 = ((length - 1) * 3) >> 1;
-		src[offset1 + 1] = (t_table[length] & 0xf0) | src[offset1 + 1];
-		free(t_table);
-		break;
-
-	case 11:
-		outputSize = compDecode(compInput, compOutput);
-		p = compOutput;
-		for (z = 2; z < outputSize; z++)
-			p[z] += p[z - 1];
-		for (z = 1; z < outputSize; z++)
-			p[z] += p[z - 1];
-
-		t_table = (byte *)malloc(outputSize);
-		assert(t_table);
-		memcpy(t_table, p, outputSize);
-
-		offset1 = outputSize / 3;
-		offset2 = offset1 << 1;
-		offset3 = offset2;
-		src = compOutput;
-
-		while (offset1--) {
-			offset2 -= 2;
-			offset3--;
-			t_table[offset2 + 0] = src[offset1];
-			t_table[offset2 + 1] = src[offset3];
-		}
-
-		src = compOutput;
-		length = (outputSize << 3) / 12;
-		k = 1;
-		c = 0;
-		s = 12;
-		t_tmp1 = t_table[length] >> 4;
-		src[0] = t_tmp1;
-		t = length + k;
-		if (t > k) {
-			do {
-				j = length + (k >> 1);
-				t_tmp1 = t_table[k - 1];
-				t_tmp2 = t_table[j];
-				if (k & 1) {
-					r = c >> 3;
-					src[r + 0] = (src[r]) | (t_tmp1 & 0xf0);
-					src[r + 1] = ((t_tmp1 & 0x0f) << 4) | (t_tmp2 & 0x0f);
-				} else {
-					r = s >> 3;
-					src[r + 0] = t_tmp1 >> 4;
-					src[r - 1] = ((t_tmp1 & 0x0f) << 4) | (t_tmp2 >> 4);
-				}
-				s += 12;
-				c += 12;
-				k++;
-			} while (k < t);
-		}
-		free(t_table);
-		break;
-
-	case 12:
-		outputSize = compDecode(compInput, compOutput);
-		p = compOutput;
-		for (z = 2; z < outputSize; z++)
-			p[z] += p[z - 1];
-		for (z = 1; z < outputSize; z++)
-			p[z] += p[z - 1];
-
-		t_table = (byte *)malloc(outputSize);
-		assert(t_table);
-		memcpy(t_table, p, outputSize);
-
-		offset1 = outputSize / 3;
-		offset2 = offset1 << 1;
-		offset3 = offset2;
-		src = compOutput;
-
-		while (offset1--) {
-			offset2 -= 2;
-			offset3--;
-			t_table[offset2 + 0] = src[offset1];
-			t_table[offset2 + 1] = src[offset3];
-		}
-
-		src = compOutput;
-		length = (outputSize << 3) / 12;
-		k = 0;
-		c = 0;
-		s = -12;
-		src[0] = t_table[outputSize - 1];
-		src[outputSize - 1] = t_table[length - 1];
-		t = length - 1;
-		if (t > 0) {
-			do {
-				j = length + (k >> 1);
-				t_tmp1 = t_table[k];
-				t_tmp2 = t_table[j];
-				if (k & 1) {
-					r = s >> 3;
-					src[r + 2] = (src[r + 2]) | (t_tmp1 & 0xf0);
-					src[r + 3] = ((t_tmp1 & 0x0f) << 4) | (t_tmp2 >> 4);
-				} else {
-					r = c >> 3;
-					src[r + 2] = t_tmp1 >> 4;
-					src[r + 1] = ((t_tmp1 & 0x0f) << 4) | (t_tmp2 & 0x0f);
-				}
-				s += 12;
-				c += 12;
-				k++;
-			} while (k < t);
-		}
-		free(t_table);
-		break;
-
-	case 13:
-	case 15:
-		outputSize = decompressADPCM(compInput, compOutput, (codec == 13) ? 1 : 2);
-		break;
-
-	default:
-		error("BundleCodecs::decompressCodec() Unknown codec %d", (int)codec);
-		outputSize = 0;
-		break;
-	}
-
-	return outputSize;
-}
-
-} // End of namespace BundleCodecs
-
-} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_codecs.h b/engines/grim/imuse/dimuse_codecs.h
deleted file mode 100644
index b53167b89db..00000000000
--- a/engines/grim/imuse/dimuse_codecs.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#ifndef GRIM_IMUSE_CODECS_H
-#define GRIM_IMUSE_CODECS_H
-
-#include "common/scummsys.h"
-
-namespace Grim {
-
-namespace BundleCodecs {
-
-int32 decompressCodec(int32 codec, byte *compInput, byte *compOutput, int32 inputSize);
-
-void initializeImcTables();
-void releaseImcTables();
-
-} // End of namespace BundleCodecs
-
-} // End of namespace Grim
-
-#endif
diff --git a/engines/grim/imuse/imuse.cpp b/engines/grim/imuse/imuse.cpp
deleted file mode 100644
index b79444dca67..00000000000
--- a/engines/grim/imuse/imuse.cpp
+++ /dev/null
@@ -1,375 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#include "common/textconsole.h"
-#include "common/timer.h"
-
-#include "engines/grim/savegame.h"
-#include "engines/grim/debug.h"
-
-#include "engines/grim/imuse/imuse.h"
-#include "engines/grim/movie/codecs/vima.h"
-
-#include "audio/audiostream.h"
-#include "audio/mixer.h"
-#include "audio/decoders/raw.h"
-
-namespace Grim {
-
-Imuse *g_imuse = nullptr;
-
-extern uint16 imuseDestTable[];
-extern ImuseTable grimStateMusicTable[];
-extern ImuseTable grimSeqMusicTable[];
-extern ImuseTable grimDemoStateMusicTable[];
-extern ImuseTable grimDemoSeqMusicTable[];
-
-void Imuse::timerHandler(void *refCon) {
-	Imuse *imuse = (Imuse *)refCon;
-	imuse->callback();
-}
-
-Imuse::Imuse(int fps, bool demo) {
-	_demo = demo;
-	_pause = false;
-	_sound = new ImuseSndMgr(_demo);
-	assert(_sound);
-	_callbackFps = fps;
-	resetState();
-	for (int l = 0; l < MAX_IMUSE_TRACKS + MAX_IMUSE_FADETRACKS; l++) {
-		_track[l] = new Track;
-		assert(_track[l]);
-		_track[l]->clear();
-		_track[l]->trackId = l;
-	}
-	vimaInit(imuseDestTable);
-	if (_demo) {
-		_stateMusicTable = grimDemoStateMusicTable;
-		_seqMusicTable = grimDemoSeqMusicTable;
-	} else {
-		_stateMusicTable = grimStateMusicTable;
-		_seqMusicTable = grimSeqMusicTable;
-	}
-	g_system->getTimerManager()->installTimerProc(timerHandler, 1000000 / _callbackFps, this, "imuseCallback");
-}
-
-Imuse::~Imuse() {
-	g_system->getTimerManager()->removeTimerProc(timerHandler);
-	stopAllSounds();
-	for (int l = 0; l < MAX_IMUSE_TRACKS + MAX_IMUSE_FADETRACKS; l++) {
-		delete _track[l];
-	}
-	delete _sound;
-}
-
-void Imuse::resetState() {
-	_curMusicState = 0;
-	_curMusicSeq = 0;
-	memset(_attributes, 0, sizeof(_attributes));
-}
-
-void Imuse::restoreState(SaveGame *savedState) {
-	Common::StackLock lock(_mutex);
-
-	savedState->beginSection('IMUS');
-	_curMusicState = savedState->readLESint32();
-	_curMusicSeq = savedState->readLESint32();
-	for (int r = 0; r < 185; r++) {
-		_attributes[r] = savedState->readLESint32();
-	}
-
-	for (int l = 0; l < MAX_IMUSE_TRACKS + MAX_IMUSE_FADETRACKS; l++) {
-		Track *track = _track[l];
-		track->clear();
-		track->trackId = l;
-		track->pan = savedState->readLESint32();
-		track->panFadeDest = savedState->readLESint32();
-		track->panFadeDelay = savedState->readLESint32();
-		track->panFadeUsed = savedState->readBool();
-		track->vol = savedState->readLESint32();
-		track->volFadeDest = savedState->readLESint32();
-		track->volFadeDelay = savedState->readLESint32();
-		track->volFadeUsed = savedState->readBool();
-		savedState->read(track->soundName, 32);
-		track->used = savedState->readBool();
-		track->toBeRemoved = savedState->readBool();
-		track->priority = savedState->readLESint32();
-		track->regionOffset = savedState->readLESint32();
-		track->dataOffset = savedState->readLESint32();
-		track->curRegion = savedState->readLESint32();
-		track->curHookId = savedState->readLESint32();
-		track->volGroupId = savedState->readLESint32();
-		track->feedSize = savedState->readLESint32();
-		track->mixerFlags = savedState->readLESint32();
-
-		if (!track->used)
-			continue;
-
-		if (track->toBeRemoved || track->curRegion == -1) {
-			track->used = false;
-			continue;
-		}
-
-		track->soundDesc = _sound->openSound(track->soundName, track->volGroupId);
-		if (!track->soundDesc) {
-			warning("Imuse::restoreState: Can't open sound so will not be resumed");
-			track->used = false;
-			continue;
-		}
-
-		int channels = _sound->getChannels(track->soundDesc);
-		int freq = _sound->getFreq(track->soundDesc);
-		track->mixerFlags = kFlag16Bits;
-		if (channels == 2)
-			track->mixerFlags |= kFlagStereo | kFlagReverseStereo;
-
-		track->stream = Audio::makeQueuingAudioStream(freq, (track->mixerFlags & kFlagStereo) != 0);
-		g_system->getMixer()->playStream(track->getType(), &track->handle, track->stream, -1, track->getVol(),
-											track->getPan(), DisposeAfterUse::YES, false,
-											(track->mixerFlags & kFlagReverseStereo) != 0);
-		g_system->getMixer()->pauseHandle(track->handle, true);
-	}
-	savedState->endSection();
-	g_system->getMixer()->pauseAll(false);
-}
-
-void Imuse::saveState(SaveGame *savedState) {
-	Common::StackLock lock(_mutex);
-
-	savedState->beginSection('IMUS');
-	savedState->writeLESint32(_curMusicState);
-	savedState->writeLESint32(_curMusicSeq);
-	for (int r = 0; r < 185; r++) {
-		savedState->writeLESint32(_attributes[r]);
-	}
-
-	for (int l = 0; l < MAX_IMUSE_TRACKS + MAX_IMUSE_FADETRACKS; l++) {
-		Track *track = _track[l];
-		savedState->writeLESint32(track->pan);
-		savedState->writeLESint32(track->panFadeDest);
-		savedState->writeLESint32(track->panFadeDelay);
-		savedState->writeBool(track->panFadeUsed);
-		savedState->writeLESint32(track->vol);
-		savedState->writeLESint32(track->volFadeDest);
-		savedState->writeLESint32(track->volFadeDelay);
-		savedState->writeBool(track->volFadeUsed);
-		savedState->write(track->soundName, 32);
-		savedState->writeBool(track->used);
-		savedState->writeBool(track->toBeRemoved);
-		savedState->writeLESint32(track->priority);
-		savedState->writeLESint32(track->regionOffset);
-		savedState->writeLESint32(track->dataOffset);
-		savedState->writeLESint32(track->curRegion);
-		savedState->writeLESint32(track->curHookId);
-		savedState->writeLESint32(track->volGroupId);
-		savedState->writeLESint32(track->feedSize);
-		savedState->writeLESint32(track->mixerFlags);
-	}
-	savedState->endSection();
-}
-
-int32 Imuse::makeMixerFlags(int32 flags) {
-	int32 mixerFlags = 0;
-	if (flags & kFlagUnsigned)
-		mixerFlags |= Audio::FLAG_UNSIGNED;
-	if (flags & kFlag16Bits)
-		mixerFlags |= Audio::FLAG_16BITS;
-	if (flags & kFlagLittleEndian)
-		mixerFlags |= Audio::FLAG_LITTLE_ENDIAN;
-	if (flags & kFlagStereo)
-		mixerFlags |= Audio::FLAG_STEREO;
-	return mixerFlags;
-}
-
-void Imuse::callback() {
-	Common::StackLock lock(_mutex);
-
-	for (int l = 0; l < MAX_IMUSE_TRACKS + MAX_IMUSE_FADETRACKS; l++) {
-		Track *track = _track[l];
-		if (track->used) {
-			// Ignore tracks which are about to finish. Also, if it did finish in the meantime,
-			// mark it as unused.
-			if (!track->stream) {
-				if (!track->soundDesc || !g_system->getMixer()->isSoundHandleActive(track->handle))
-					track->clear();
-				continue;
-			}
-
-			if (_pause)
-				return;
-
-			if (track->volFadeUsed) {
-				if (track->volFadeStep < 0) {
-					if (track->vol > track->volFadeDest) {
-						track->vol += track->volFadeStep;
-						if (track->vol < track->volFadeDest) {
-							track->vol = track->volFadeDest;
-							track->volFadeUsed = false;
-						}
-						if (track->vol == 0) {
-							// Fade out complete -> remove this track
-							flushTrack(track);
-							continue;
-						}
-					}
-				} else if (track->volFadeStep > 0) {
-					if (track->vol < track->volFadeDest) {
-						track->vol += track->volFadeStep;
-						if (track->vol > track->volFadeDest) {
-							track->vol = track->volFadeDest;
-							track->volFadeUsed = false;
-						}
-					}
-				}
-			}
-
-			if (track->panFadeUsed) {
-				if (track->panFadeStep < 0) {
-					if (track->pan > track->panFadeDest) {
-						track->pan += track->panFadeStep;
-						if (track->pan < track->panFadeDest) {
-							track->pan = track->panFadeDest;
-							track->panFadeUsed = false;
-						}
-					}
-				} else if (track->panFadeStep > 0) {
-					if (track->pan < track->panFadeDest) {
-						track->pan += track->panFadeStep;
-						if (track->pan > track->panFadeDest) {
-							track->pan = track->panFadeDest;
-							track->panFadeUsed = false;
-						}
-					}
-				}
-			}
-
-			assert(track->stream);
-			byte *data = nullptr;
-			int32 result = 0;
-
-			if (track->curRegion == -1) {
-				switchToNextRegion(track);
-				if (!track->stream) // Seems we reached the end of the stream
-					continue;
-			}
-
-			int channels = _sound->getChannels(track->soundDesc);
-			int32 mixer_size = track->feedSize / _callbackFps;
-
-			if (track->stream->endOfData()) {
-				mixer_size *= 2;
-			}
-
-			if (channels == 1)
-				mixer_size &= ~1;
-			if (channels == 2)
-				mixer_size &= ~3;
-
-			if (mixer_size == 0)
-				continue;
-
-			do {
-				int32 mixerFlags = makeMixerFlags(track->mixerFlags);
-				result = _sound->getDataFromRegion(track->soundDesc, track->curRegion, &data, track->regionOffset, mixer_size, &mixerFlags);
-				if (channels == 1) {
-					result &= ~1;
-				}
-				if (channels == 2) {
-					result &= ~3;
-				}
-
-				if (result > mixer_size)
-					result = mixer_size;
-
-				if (g_system->getMixer()->isReady()) {
-					track->stream->queueBuffer(data, result, DisposeAfterUse::YES, mixerFlags);
-					track->regionOffset += result;
-				} else
-					free(data);
-
-				if (_sound->isEndOfRegion(track->soundDesc, track->curRegion)) {
-					switchToNextRegion(track);
-					if (!track->stream)
-						break;
-				}
-				mixer_size -= result;
-				assert(mixer_size >= 0);
-			} while (mixer_size);
-			if (g_system->getMixer()->isReady()) {
-				g_system->getMixer()->setChannelVolume(track->handle, track->getVol());
-				g_system->getMixer()->setChannelBalance(track->handle, track->getPan());
-			}
-		}
-	}
-}
-
-void Imuse::switchToNextRegion(Track *track) {
-	assert(track);
-
-	if (track->trackId >= MAX_IMUSE_TRACKS) {
-		Debug::debug(Debug::Sound, "Imuse::switchToNextRegion(): fadeTrack end: soundName:%s", track->soundName);
-		flushTrack(track);
-		return;
-	}
-
-	int numRegions = _sound->getNumRegions(track->soundDesc);
-
-	if (++track->curRegion == numRegions) {
-		Debug::debug(Debug::Sound, "Imuse::switchToNextRegion(): end of tracks: soundName:%s", track->soundName);
-		flushTrack(track);
-		return;
-	}
-
-	ImuseSndMgr::SoundDesc *soundDesc = track->soundDesc;
-	int jumpId = _sound->getJumpIdByRegionAndHookId(soundDesc, track->curRegion, track->curHookId);
-	// It seems 128 is a special value meaning it should not force the 0 hookId,
-	// otherwise the sound hkwine.imu when glottis drinks the wine in the barrel
-	// in hk won't stop.
-	if (jumpId == -1 && track->curHookId != 128)
-		jumpId = _sound->getJumpIdByRegionAndHookId(soundDesc, track->curRegion, 0);
-	if (jumpId != -1) {
-		Debug::debug(Debug::Sound, "Imuse::switchToNextRegion(): JUMP: soundName:%s", track->soundName);
-		int region = _sound->getRegionIdByJumpId(soundDesc, jumpId);
-		assert(region != -1);
-		int sampleHookId = _sound->getJumpHookId(soundDesc, jumpId);
-		assert(sampleHookId != -1);
-		int fadeDelay = (60 * _sound->getJumpFade(soundDesc, jumpId)) / 1000;
-		if (fadeDelay) {
-			Track *fadeTrack = cloneToFadeOutTrack(track, fadeDelay);
-			if (fadeTrack) {
-				fadeTrack->dataOffset = _sound->getRegionOffset(fadeTrack->soundDesc, fadeTrack->curRegion);
-				fadeTrack->regionOffset = 0;
-				fadeTrack->curHookId = 0;
-			}
-		}
-		track->curRegion = region;
-		if (track->curHookId == sampleHookId)
-			track->curHookId = 0;
-		else if (track->curHookId == 0x80)
-			track->curHookId = 0;
-	}
-
-	Debug::debug(Debug::Sound, "Imuse::switchToNextRegion(): REGION %d: soundName:%s", (int)track->curRegion, track->soundName);
-	track->dataOffset = _sound->getRegionOffset(soundDesc, track->curRegion);
-	track->regionOffset = 0;
-}
-
-} // end of namespace Grim
diff --git a/engines/grim/imuse/imuse.h b/engines/grim/imuse/imuse.h
deleted file mode 100644
index ed4c5cb829b..00000000000
--- a/engines/grim/imuse/imuse.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#ifndef GRIM_IMUSE_H
-#define GRIM_IMUSE_H
-
-#include "common/mutex.h"
-
-#include "engines/grim/imuse/imuse_track.h"
-
-namespace Grim {
-
-#define MAX_IMUSE_TRACKS 16
-#define MAX_IMUSE_FADETRACKS 16
-
-struct ImuseTable;
-class SaveGame;
-
-class Imuse {
-private:
-
-	int _callbackFps;
-
-	Track *_track[MAX_IMUSE_TRACKS + MAX_IMUSE_FADETRACKS];
-
-	Common::Mutex _mutex;
-	ImuseSndMgr *_sound;
-
-	bool _pause;
-	bool _demo;
-
-	int32 _attributes[185];
-	int32 _curMusicState;
-	int32 _curMusicSeq;
-
-	const ImuseTable *_stateMusicTable;
-	const ImuseTable *_seqMusicTable;
-
-	int32 makeMixerFlags(int32 flags);
-	static void timerHandler(void *refConf);
-	void callback();
-	void switchToNextRegion(Track *track);
-	int allocSlot(int priority);
-	void selectVolumeGroup(const char *soundName, int volGroupId);
-
-	void fadeOutMusic(int fadeDelay);
-	void fadeOutMusicAndStartNew(int fadeDelay, const char *filename, int hookId, int vol, int pan);
-	Track *cloneToFadeOutTrack(Track *track, int fadeDelay);
-
-	void playMusic(const ImuseTable *table, int atribPos, bool sequence);
-
-	void flushTrack(Track *track);
-
-public:
-	Imuse(int fps, bool demo);
-	~Imuse();
-
-	bool startSound(const char *soundName, int volGroupId, int hookId, int volume, int pan, int priority, Track *otherTrack);
-	bool startVoice(const char *soundName, int volume = 127, int pan = 64);
-	void startMusic(const char *soundName, int hookId, int volume, int pan);
-	void startMusicWithOtherPos(const char *soundName, int hookId, int volume, int pan, Track *otherTrack);
-	void startSfx(const char *soundName, int priority = 127);
-
-	void restoreState(SaveGame *savedState);
-	void saveState(SaveGame *savedState);
-	void resetState();
-
-	Track *findTrack(const char *soundName);
-	void setPriority(const char *soundName, int priority);
-	void setVolume(const char *soundName, int volume);
-	int getVolume(const char *soundName);
-	void setPan(const char *soundName, int pan); /* pan: 0 .. 127 */
-	void setFadePan(const char *soundName, int destPan, int duration);
-	void setFadeVolume(const char *soundName, int destVolume, int duration);
-	void setHookId(const char *soundName, int hookId);
-	int getCountPlayedTracks(const char *soundName);
-	void stopSound(const char *soundName);
-	void stopAllSounds();
-	void pause(bool pause);
-	void setMusicState(int stateId);
-	int setMusicSequence(int seqId);
-	void refreshScripts();
-	void flushTracks();
-	bool isVoicePlaying();
-	char *getCurMusicSoundName();
-	int getCurMusicPan();
-	int getCurMusicVol();
-	bool getSoundStatus(const char *soundName);
-	int32 getPosIn16msTicks(const char *soundName);
-};
-
-extern Imuse *g_imuse;
-
-} // end of namespace Grim
-
-#endif
diff --git a/engines/grim/imuse/imuse_music.cpp b/engines/grim/imuse/imuse_music.cpp
deleted file mode 100644
index 6fd39a8bbf7..00000000000
--- a/engines/grim/imuse/imuse_music.cpp
+++ /dev/null
@@ -1,167 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#include "engines/grim/debug.h"
-
-#include "engines/grim/imuse/imuse.h"
-#include "engines/grim/imuse/imuse_tables.h"
-
-namespace Grim {
-
-void Imuse::setMusicState(int stateId) {
-	int l, num = -1;
-
-	if (stateId == 0)
-		stateId = 1000;
-
-	for (l = 0; _stateMusicTable[l].soundId != -1; l++) {
-		if (_stateMusicTable[l].soundId == stateId) {
-			num = l;
-			break;
-		}
-	}
-	assert(num != -1);
-
-	Debug::debug(Debug::Sound, "Imuse::setMusicState(): SoundId %d, filename: %s", _stateMusicTable[l].soundId, _stateMusicTable[l].filename);
-
-	if (_curMusicState == num)
-		return;
-
-	if (!_curMusicSeq) {
-		playMusic(&_stateMusicTable[num], num, false);
-	}
-
-	_curMusicState = num;
-}
-
-int Imuse::setMusicSequence(int seqId) {
-	int l, num = -1;
-
-	if (seqId == -1)
-		return _seqMusicTable[_curMusicSeq].soundId;
-
-	if (seqId == 0)
-		seqId = 2000;
-
-	for (l = 0; _seqMusicTable[l].soundId != -1; l++) {
-		if (_seqMusicTable[l].soundId == seqId) {
-			num = l;
-			break;
-		}
-	}
-
-	assert(num != -1);
-
-	Debug::debug(Debug::Sound, "Imuse::setMusicSequence(): SoundId %d, filename: %s", _seqMusicTable[l].soundId, _seqMusicTable[l].filename);
-
-	if (_curMusicSeq == num)
-		return _seqMusicTable[_curMusicSeq].soundId;
-
-	if (num) {
-		playMusic(&_seqMusicTable[num], 0, true);
-	} else {
-		playMusic(&_stateMusicTable[_curMusicState], _curMusicState, true);
-		num = 0;
-	}
-
-	_curMusicSeq = num;
-	return _seqMusicTable[_curMusicSeq].soundId;
-}
-
-void Imuse::playMusic(const ImuseTable *table, int atribPos, bool sequence) {
-	int hookId = 0;
-
-	if (atribPos) {
-		if (table->atribPos)
-			atribPos = table->atribPos;
-		hookId = _attributes[atribPos];
-		if (table->hookId) {
-			if (hookId && table->hookId > 1) {
-				_attributes[atribPos] = 2;
-			} else {
-				_attributes[atribPos] = hookId + 1;
-				if (table->hookId < hookId + 1)
-					_attributes[atribPos] = 1;
-			}
-		}
-	}
-	if (hookId == 0)
-		hookId = 100;
-
-	if (table->opcode == 0) {
-		fadeOutMusic(120);
-		return;
-	}
-
-	if (table->opcode == 2 || table->opcode == 3) {
-		if (table->filename[0] == 0) {
-			fadeOutMusic(60);
-			return;
-		}
-		char *soundName = getCurMusicSoundName();
-		int pan;
-
-		if (table->pan == 0)
-			pan = 64;
-		else
-			pan = table->pan;
-		if (!soundName) {
-			startMusic(table->filename, hookId, 0, pan);
-			setVolume(table->filename, 0);
-			setFadeVolume(table->filename, table->volume, table->fadeOut60TicksDelay);
-			return;
-		}
-		int old_pan = getCurMusicPan();
-		int old_vol = getCurMusicVol();
-		if (old_pan == -1)
-			old_pan = 64;
-		if (old_vol == -1)
-			old_vol = 127;
-
-		if (table->opcode == 2) {
-			fadeOutMusic(table->fadeOut60TicksDelay);
-			startMusic(table->filename, hookId, table->volume, pan);
-			setVolume(table->filename, 0);
-			setFadeVolume(table->filename, table->volume, table->fadeOut60TicksDelay);
-			setFadePan(table->filename, pan, table->fadeOut60TicksDelay);
-			return;
-		}
-		if (strcmp(soundName, table->filename) == 0) {
-			setFadeVolume(soundName, table->volume, table->fadeOut60TicksDelay);
-			setFadePan(soundName, pan, table->fadeOut60TicksDelay);
-			return;
-		}
-
-		if (!sequence && table->atribPos && table->atribPos == _stateMusicTable[_curMusicState].atribPos) {
-			fadeOutMusicAndStartNew(table->fadeOut60TicksDelay, table->filename, hookId, old_vol, old_pan);
-			setVolume(table->filename, 0);
-			setFadeVolume(table->filename, table->volume, table->fadeOut60TicksDelay);
-			setFadePan(table->filename, pan, table->fadeOut60TicksDelay);
-		} else {
-			fadeOutMusic(table->fadeOut60TicksDelay);
-			startMusic(table->filename, hookId, table->volume, pan);
-			setVolume(table->filename, 0);
-			setFadeVolume(table->filename, table->volume, table->fadeOut60TicksDelay);
-		}
-	}
-}
-
-} // end of namespace Grim
diff --git a/engines/grim/imuse/imuse_script.cpp b/engines/grim/imuse/imuse_script.cpp
deleted file mode 100644
index c357467fb1c..00000000000
--- a/engines/grim/imuse/imuse_script.cpp
+++ /dev/null
@@ -1,178 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#include "common/textconsole.h"
-
-#include "engines/grim/imuse/imuse.h"
-
-#include "engines/grim/debug.h"
-
-namespace Grim {
-
-void Imuse::flushTrack(Track *track) {
-	track->toBeRemoved = true;
-
-	if (track->stream) {
-		// Finalize the appendable stream, then remove our reference to it.
-		// Note that there might still be some data left in the buffers of the
-		// appendable stream. We play it nice and wait till all of it
-		// played. The audio mixer will take care of it afterwards (and dispose it).
-		track->stream->finish();
-		track->stream = nullptr;
-		if (track->soundDesc) {
-			_sound->closeSound(track->soundDesc);
-			track->soundDesc = nullptr;
-		}
-	}
-
-	if (!g_system->getMixer()->isSoundHandleActive(track->handle)) {
-		track->clear();
-	}
-}
-
-void Imuse::flushTracks() {
-	Common::StackLock lock(_mutex);
-	for (int l = 0; l < MAX_IMUSE_TRACKS + MAX_IMUSE_FADETRACKS; l++) {
-		Track *track = _track[l];
-		if (track->used && track->toBeRemoved && !g_system->getMixer()->isSoundHandleActive(track->handle)) {
-			track->clear();
-		}
-	}
-}
-
-void Imuse::refreshScripts() {
-	Common::StackLock lock(_mutex);
-	bool found = false;
-
-	for (int l = 0; l < MAX_IMUSE_TRACKS; l++) {
-		Track *track = _track[l];
-		if (track->used && !track->toBeRemoved && (track->volGroupId == IMUSE_VOLGRP_MUSIC)) {
-			found = true;
-		}
-	}
-
-	if (!found && _curMusicState) {
-		setMusicSequence(0);
-	}
-}
-
-bool Imuse::startVoice(const char *soundName, int volume, int pan) {
-	Debug::debug(Debug::Sound, "Imuse::startVoice(): SoundName %s, vol:%d, pan:%d", soundName, volume, pan);
-	return startSound(soundName, IMUSE_VOLGRP_VOICE, 0, volume, pan, 127, nullptr);
-}
-
-void Imuse::startMusic(const char *soundName, int hookId, int volume, int pan) {
-	Debug::debug(Debug::Sound, "Imuse::startMusic(): SoundName %s, hookId:%d, vol:%d, pan:%d", soundName, hookId, volume, pan);
-	startSound(soundName, IMUSE_VOLGRP_MUSIC, hookId, volume, pan, 126, nullptr);
-}
-
-void Imuse::startMusicWithOtherPos(const char *soundName, int hookId, int volume, int pan, Track *otherTrack) {
-	Debug::debug(Debug::Sound, "Imuse::startMusicWithOtherPos(): SoundName %s, hookId:%d, vol:%d, pan:%d", soundName, hookId, volume, pan);
-	startSound(soundName, IMUSE_VOLGRP_MUSIC, hookId, volume, pan, 126, otherTrack);
-}
-
-void Imuse::startSfx(const char *soundName, int priority) {
-	Debug::debug(Debug::Sound, "Imuse::startSfx(): SoundName %s, priority:%d", soundName, priority);
-	startSound(soundName, IMUSE_VOLGRP_SFX, 0, 127, 0, priority, nullptr);
-}
-
-int32 Imuse::getPosIn16msTicks(const char *soundName) {
-	Common::StackLock lock(_mutex);
-	Track *getTrack = nullptr;
-
-	getTrack = findTrack(soundName);
-	// Warn the user if the track was not found
-	if (getTrack == nullptr) {
-		Debug::warning(Debug::Sound, "Sound '%s' could not be found to get ticks", soundName);
-		return false;
-	}
-
-	int32 pos = (62.5 / 60.0) * (5 * (getTrack->dataOffset + getTrack->regionOffset)) / (getTrack->feedSize / 12); // 16ms is 62.5 Hz
-	return pos;
-}
-
-bool Imuse::isVoicePlaying() {
-	Common::StackLock lock(_mutex);
-	for (int l = 0; l < MAX_IMUSE_TRACKS; l++) {
-		Track *track = _track[l];
-		if (track->used && track->volGroupId == IMUSE_VOLGRP_VOICE) {
-			if (g_system->getMixer()->isSoundHandleActive(track->handle))
-				return true;
-		}
-	}
-
-	return false;
-}
-
-bool Imuse::getSoundStatus(const char *soundName) {
-	Common::StackLock lock(_mutex);
-	Track *track = nullptr;
-
-	// If there's no name then don't try to get the status!
-	if (strlen(soundName) == 0)
-		return false;
-
-	track = findTrack(soundName);
-	// Warn the user if the track was not found
-	if (track == nullptr || !g_system->getMixer()->isSoundHandleActive(track->handle)) {
-		// This debug warning should be "light" since this function gets called
-		// on occasion to see if a sound has stopped yet
-		Debug::debug(Debug::Sound, "Sound '%s' could not be found to get status, assume inactive.", soundName);
-		return false;
-	}
-	return true;
-}
-
-void Imuse::stopSound(const char *soundName) {
-	Common::StackLock lock(_mutex);
-	Debug::debug(Debug::Sound, "Imuse::stopSound(): SoundName %s", soundName);
-	Track *removeTrack = nullptr;
-
-	removeTrack = findTrack(soundName);
-	// Warn the user if the track was not found
-	if (removeTrack == nullptr) {
-		Debug::warning(Debug::Sound, "Sound track '%s' could not be found to stop", soundName);
-		return;
-	}
-	flushTrack(removeTrack);
-}
-
-void Imuse::stopAllSounds() {
-	Common::StackLock lock(_mutex);
-	Debug::debug(Debug::Sound, "Imuse::stopAllSounds()");
-
-	for (int l = 0; l < MAX_IMUSE_TRACKS + MAX_IMUSE_FADETRACKS; l++) {
-		Track *track = _track[l];
-		if (track->used) {
-			g_system->getMixer()->stopHandle(track->handle);
-			if (track->soundDesc) {
-				_sound->closeSound(track->soundDesc);
-			}
-			track->clear();
-		}
-	}
-}
-
-void Imuse::pause(bool p) {
-	_pause = p;
-}
-
-} // end of namespace Grim
diff --git a/engines/grim/imuse/imuse_sndmgr.cpp b/engines/grim/imuse/imuse_sndmgr.cpp
deleted file mode 100644
index f2edecca518..00000000000
--- a/engines/grim/imuse/imuse_sndmgr.cpp
+++ /dev/null
@@ -1,370 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#include "audio/decoders/raw.h"
-
-#include "common/endian.h"
-#include "common/stream.h"
-
-#include "engines/grim/resource.h"
-
-#include "engines/grim/imuse/imuse_sndmgr.h"
-#include "engines/grim/imuse/imuse_mcmp_mgr.h"
-
-namespace Grim {
-
-ImuseSndMgr::ImuseSndMgr(bool demo) {
-	_demo = demo;
-	for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
-		memset(&_sounds[l], 0, sizeof(SoundDesc));
-	}
-}
-
-ImuseSndMgr::~ImuseSndMgr() {
-	for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
-		closeSound(&_sounds[l]);
-	}
-}
-
-void ImuseSndMgr::countElements(SoundDesc *sound) {
-	uint32 tag;
-	int32 size = 0;
-	uint32 pos = sound->inStream->pos();
-
-	do {
-		tag = sound->inStream->readUint32BE();
-		switch(tag) {
-		case MKTAG('T','E','X','T'):
-		case MKTAG('S','T','O','P'):
-		case MKTAG('F','R','M','T'):
-			size = sound->inStream->readUint32BE();
-			sound->inStream->seek(size, SEEK_CUR);
-			break;
-		case MKTAG('R','E','G','N'):
-			sound->numRegions++;
-			size = sound->inStream->readUint32BE();
-			sound->inStream->seek(size, SEEK_CUR);
-			break;
-		case MKTAG('J','U','M','P'):
-			sound->numJumps++;
-			size = sound->inStream->readUint32BE();
-			sound->inStream->seek(size, SEEK_CUR);
-			break;
-		case MKTAG('D','A','T','A'):
-			break;
-		default:
-			error("ImuseSndMgr::countElements() Unknown MAP tag '%s'", Common::tag2string(tag).c_str());
-		}
-	} while (tag != MKTAG('D','A','T','A'));
-
-	sound->inStream->seek(pos, SEEK_SET);
-}
-
-void ImuseSndMgr::parseSoundHeader(SoundDesc *sound, int &headerSize) {
-	Common::SeekableReadStream *data = sound->inStream;
-
-	uint32 tag = data->readUint32BE();
-	if (tag == MKTAG('R','I','F','F')) {
-		sound->region = new Region[1];
-		sound->jump = new Jump[1];
-		sound->numJumps = 0;
-		sound->numRegions = 1;
-		sound->region[0].offset = 0;
-		data->seek(18, SEEK_CUR);
-		sound->channels = data->readByte();
-		data->readByte();
-		sound->freq = data->readUint32LE();
-		data->seek(6, SEEK_CUR);
-		sound->bits = data->readByte();
-		data->seek(5, SEEK_CUR);
-		sound->region[0].length = data->readUint32LE();
-		headerSize = 44;
-	} else if (tag == MKTAG('i','M','U','S')) {
-		int32 size = 0;
-		int32 headerStart = data->pos();
-		data->seek(12, SEEK_CUR);
-
-		int curIndexRegion = 0;
-		int curIndexJump = 0;
-
-		sound->numRegions = 0;
-		sound->numJumps = 0;
-		countElements(sound);
-		sound->region = new Region [sound->numRegions];
-		sound->jump = new Jump [sound->numJumps];
-
-		do {
-			tag = data->readUint32BE();
-			switch(tag) {
-			case MKTAG('F','R','M','T'):
-				data->seek(12, SEEK_CUR);
-				sound->bits = data->readUint32BE();
-				sound->freq = data->readUint32BE();
-				sound->channels = data->readUint32BE();
-				break;
-			case MKTAG('T','E','X','T'):
-			case MKTAG('S','T','O','P'):
-				size = data->readUint32BE();
-				data->seek(size, SEEK_CUR);
-				break;
-			case MKTAG('R','E','G','N'):
-				data->seek(4, SEEK_CUR);
-				sound->region[curIndexRegion].offset = data->readUint32BE();
-				sound->region[curIndexRegion].length = data->readUint32BE();
-				curIndexRegion++;
-				break;
-			case MKTAG('J','U','M','P'):
-				data->seek(4, SEEK_CUR);
-				sound->jump[curIndexJump].offset = data->readUint32BE();
-				sound->jump[curIndexJump].dest = data->readUint32BE();
-				sound->jump[curIndexJump].hookId = data->readUint32BE();
-				sound->jump[curIndexJump].fadeDelay = data->readUint32BE();
-				curIndexJump++;
-				break;
-			case MKTAG('D','A','T','A'):
-				data->seek(4, SEEK_CUR);
-				break;
-			default:
-				error("ImuseSndMgr::prepareSound(%s) Unknown MAP tag '%s'", sound->name, Common::tag2string(tag).c_str());
-			}
-		} while (tag != MKTAG('D','A','T','A'));
-		headerSize = data->pos() - headerStart;
-		int i;
-		for (i = 0; i < sound->numRegions; i++) {
-			sound->region[i].offset -= headerSize;
-		}
-		for (i = 0; i < sound->numJumps; i++) {
-			sound->jump[i].offset -= headerSize;
-			sound->jump[i].dest -= headerSize;
-		}
-	} else {
-		error("ImuseSndMgr::prepareSound() Unknown sound format");
-	}
-}
-
-ImuseSndMgr::SoundDesc *ImuseSndMgr::allocSlot() {
-	for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
-		if (!_sounds[l].inUse) {
-			_sounds[l].inUse = true;
-			return &_sounds[l];
-		}
-	}
-
-	return nullptr;
-}
-
-ImuseSndMgr::SoundDesc *ImuseSndMgr::openSound(const char *soundName, int volGroupId) {
-	Common::String s = soundName;
-	s.toLowercase();
-	soundName = s.c_str();
-	const char *extension = soundName + strlen(soundName) - 3;
-	int headerSize = 0;
-
-	SoundDesc *sound = allocSlot();
-	if (!sound) {
-		error("ImuseSndMgr::openSound() Can't alloc free sound slot");
-	}
-
-	Common::strcpy_s(sound->name, soundName);
-	sound->volGroupId = volGroupId;
-	sound->inStream = nullptr;
-
-	sound->inStream = g_resourceloader->openNewStreamFile(soundName);
-	if (!sound->inStream) {
-		closeSound(sound);
-		return nullptr;
-	}
-
-	if (!_demo && scumm_stricmp(extension, "imu") == 0) {
-		parseSoundHeader(sound, headerSize);
-		sound->mcmpData = false;
-		sound->headerSize = headerSize;
-	} else if (scumm_stricmp(extension, "wav") == 0 || scumm_stricmp(extension, "imc") == 0 ||
-			(_demo && scumm_stricmp(extension, "imu") == 0)) {
-		sound->mcmpMgr = new McmpMgr();
-		if (!sound->mcmpMgr->openSound(soundName, sound->inStream, headerSize)) {
-			closeSound(sound);
-			return nullptr;
-		}
-		parseSoundHeader(sound, headerSize);
-		sound->mcmpData = true;
-	} else {
-		error("ImuseSndMgr::openSound() Unrecognized extension for sound file %s", soundName);
-	}
-
-	return sound;
-}
-
-void ImuseSndMgr::closeSound(SoundDesc *sound) {
-	assert(checkForProperHandle(sound));
-
-	if (sound->mcmpMgr) {
-		delete sound->mcmpMgr;
-		sound->mcmpMgr = nullptr;
-	}
-
-	if (sound->region) {
-		delete[] sound->region;
-		sound->region = nullptr;
-	}
-
-	if (sound->jump) {
-		delete[] sound->jump;
-		sound->jump = nullptr;
-	}
-
-	if (sound->inStream) {
-		delete sound->inStream;
-		sound->inStream = nullptr;
-	}
-
-	memset(sound, 0, sizeof(SoundDesc));
-}
-
-ImuseSndMgr::SoundDesc *ImuseSndMgr::cloneSound(SoundDesc *sound) {
-	assert(checkForProperHandle(sound));
-
-	return openSound(sound->name, sound->volGroupId);
-}
-
-bool ImuseSndMgr::checkForProperHandle(SoundDesc *sound) {
-	if (!sound)
-		return false;
-
-	for (int l = 0; l < MAX_IMUSE_SOUNDS; l++) {
-		if (sound == &_sounds[l])
-			return true;
-	}
-
-	return false;
-}
-
-int ImuseSndMgr::getFreq(SoundDesc *sound) {
-	assert(checkForProperHandle(sound));
-	return sound->freq;
-}
-
-int ImuseSndMgr::getBits(SoundDesc *sound) {
-	assert(checkForProperHandle(sound));
-	return sound->bits;
-}
-
-int ImuseSndMgr::getChannels(SoundDesc *sound) {
-	assert(checkForProperHandle(sound));
-	return sound->channels;
-}
-
-bool ImuseSndMgr::isEndOfRegion(SoundDesc *sound, int region) {
-	assert(checkForProperHandle(sound));
-	assert(region >= 0 && region < sound->numRegions);
-	return sound->endFlag;
-}
-
-int ImuseSndMgr::getNumRegions(SoundDesc *sound) {
-	assert(checkForProperHandle(sound));
-	return sound->numRegions;
-}
-
-int ImuseSndMgr::getNumJumps(SoundDesc *sound) {
-	assert(checkForProperHandle(sound));
-	return sound->numJumps;
-}
-
-int ImuseSndMgr::getRegionOffset(SoundDesc *sound, int region) {
-	assert(checkForProperHandle(sound));
-	assert(region >= 0 && region < sound->numRegions);
-	return sound->region[region].offset;
-}
-
-int ImuseSndMgr::getRegionLength(SoundDesc *sound, int region) {
-	assert(checkForProperHandle(sound));
-	assert(region >= 0 && region < sound->numRegions);
-	return sound->region[region].length;
-}
-
-int ImuseSndMgr::getJumpIdByRegionAndHookId(SoundDesc *sound, int region, int hookId) {
-	assert(checkForProperHandle(sound));
-	assert(region >= 0 && region < sound->numRegions);
-	int32 offset = sound->region[region].offset;
-	for (int l = 0; l < sound->numJumps; l++) {
-		if (offset == sound->jump[l].offset) {
-			if (sound->jump[l].hookId == hookId)
-				return l;
-		}
-	}
-
-	return -1;
-}
-
-int ImuseSndMgr::getRegionIdByJumpId(SoundDesc *sound, int jumpId) {
-	assert(checkForProperHandle(sound));
-	assert(jumpId >= 0 && jumpId < sound->numJumps);
-	int32 dest = sound->jump[jumpId].dest;
-	for (int l = 0; l < sound->numRegions; l++) {
-		if (dest == sound->region[l].offset) {
-			return l;
-		}
-	}
-
-	return -1;
-}
-
-int ImuseSndMgr::getJumpHookId(SoundDesc *sound, int number) {
-	assert(checkForProperHandle(sound));
-	assert(number >= 0 && number < sound->numJumps);
-	return sound->jump[number].hookId;
-}
-
-int ImuseSndMgr::getJumpFade(SoundDesc *sound, int number) {
-	assert(checkForProperHandle(sound));
-	assert(number >= 0 && number < sound->numJumps);
-	return sound->jump[number].fadeDelay;
-}
-
-int32 ImuseSndMgr::getDataFromRegion(SoundDesc *sound, int region, byte **buf, int32 offset, int32 size, int32 *flags) {
-	assert(checkForProperHandle(sound));
-	assert(buf && offset >= 0 && size >= 0);
-	assert(region >= 0 && region < sound->numRegions);
-
-	int32 region_offset = sound->region[region].offset;
-	int32 region_length = sound->region[region].length;
-
-	if (offset + size > region_length) {
-		size = region_length - offset;
-		sound->endFlag = true;
-	} else {
-		sound->endFlag = false;
-	}
-
-	if (sound->mcmpData) {
-		size = sound->mcmpMgr->decompressSample(region_offset + offset, size, buf);
-		*flags |= Audio::FLAG_LITTLE_ENDIAN;
-	} else {
-		*buf = static_cast<byte *>(malloc(size));
-		sound->inStream->seek(region_offset + offset + sound->headerSize, SEEK_SET);
-		sound->inStream->read(*buf, size);
-		*flags &= ~Audio::FLAG_LITTLE_ENDIAN;
-	}
-
-	return size;
-}
-
-} // end of namespace Grim
diff --git a/engines/grim/imuse/imuse_sndmgr.h b/engines/grim/imuse/imuse_sndmgr.h
deleted file mode 100644
index 9ec55a7ba0a..00000000000
--- a/engines/grim/imuse/imuse_sndmgr.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#ifndef GRIM_IMUSE_OLD_SNDMGR_H
-#define GRIM_IMUSE_OLD_SNDMGR_H
-
-#include "audio/mixer.h"
-#include "audio/audiostream.h"
-
-namespace Grim {
-
-class McmpMgr;
-
-class ImuseSndMgr {
-public:
-
-// MAX_IMUSE_SOUNDS needs to be hardcoded, ask aquadran
-#define MAX_IMUSE_SOUNDS    16
-
-// The numbering below fixes talking to Domino in his office
-// and it also allows Manny to get the info for Mercedes
-// Colomar, without this the game hangs at these points!
-#define IMUSE_VOLGRP_BGND   0
-#define IMUSE_VOLGRP_SFX    1
-#define IMUSE_VOLGRP_VOICE  2
-#define IMUSE_VOLGRP_MUSIC  3
-#define IMUSE_VOLGRP_ACTION 4
-
-private:
-	struct Region {
-		int32 offset;       // offset of region
-		int32 length;       // length of region
-	};
-
-	struct Jump {
-		int32 offset;       // jump offset position
-		int32 dest;         // jump to dest position
-		byte hookId;        // id of hook
-		int16 fadeDelay;    // fade delay in ms
-	};
-
-public:
-
-	struct SoundDesc {
-		uint16 freq;        // frequency
-		byte channels;      // stereo or mono
-		byte bits;          // 8, 12, 16
-		int numJumps;       // number of Jumps
-		int numRegions;     // number of Regions
-		Region *region;
-		Jump *jump;
-		bool endFlag;
-		bool inUse;
-		char name[32];
-		McmpMgr *mcmpMgr;
-		int type;
-		int volGroupId;
-		bool mcmpData;
-		uint32 headerSize;
-		Common::SeekableReadStream *inStream;
-	};
-
-private:
-
-	SoundDesc _sounds[MAX_IMUSE_SOUNDS];
-	bool _demo;
-
-	bool checkForProperHandle(SoundDesc *soundDesc);
-	SoundDesc *allocSlot();
-	void parseSoundHeader(SoundDesc *sound, int &headerSize);
-	void countElements(SoundDesc *sound);
-
-public:
-
-	ImuseSndMgr(bool demo);
-	~ImuseSndMgr();
-
-	SoundDesc *openSound(const char *soundName, int volGroupId);
-	void closeSound(SoundDesc *sound);
-	SoundDesc *cloneSound(SoundDesc *sound);
-
-	int getFreq(SoundDesc *sound);
-	int getBits(SoundDesc *sound);
-	int getChannels(SoundDesc *sound);
-	bool isEndOfRegion(SoundDesc *sound, int region);
-	int getNumRegions(SoundDesc *sound);
-	int getNumJumps(SoundDesc *sound);
-	int getRegionOffset(SoundDesc *sound, int region);
-	int getRegionLength(SoundDesc *sound, int region);
-	int getJumpIdByRegionAndHookId(SoundDesc *sound, int region, int hookId);
-	int getRegionIdByJumpId(SoundDesc *sound, int jumpId);
-	int getJumpHookId(SoundDesc *sound, int number);
-	int getJumpFade(SoundDesc *sound, int number);
-
-	int32 getDataFromRegion(SoundDesc *sound, int region, byte **buf, int32 offset, int32 size, int32 *flags);
-};
-
-} // end of namespace Grim
-
-#endif
diff --git a/engines/grim/imuse/imuse_tables.cpp b/engines/grim/imuse/imuse_tables.cpp
deleted file mode 100644
index 39742472afa..00000000000
--- a/engines/grim/imuse/imuse_tables.cpp
+++ /dev/null
@@ -1,290 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#include "common/scummsys.h"
-
-#include "engines/grim/imuse/imuse_tables.h"
-
-namespace Grim {
-
-ImuseTable grimStateMusicTable[] = {
-	{0, 1000,   0, 0, 60, 127,   0, ""},
-	{0, 1999,   0, 0, 60, 127,   0, ""},
-	{3, 1001,   0, 0, 60, 127,   0, "1001 - Manny's Office.IMC" },
-	{3, 1002,   3, 8, 60,  20,  50, "1002 - Mr. Frustration.IMC"},
-	{3, 1003,   3, 8, 60,  80,  12, "1002 - Mr. Frustration.IMC"},
-	{3, 1004,   3, 8, 60,  90, 110, "1002 - Mr. Frustration.IMC"},
-	{3, 1005,   3, 8, 60,  60, 110, "1002 - Mr. Frustration.IMC"},
-	{3, 1006,   3, 8, 60,  80,  64, "1002 - Mr. Frustration.IMC"},
-	{3, 1007,   3, 8, 60,  60,  60, "1002 - Mr. Frustration.IMC"},
-	{3, 1008,   0, 0, 60, 127,   0, "1008 - Domino's Office.IMC"},
-	{3, 1009,   0, 0, 60, 127,   0, "1009 - Copal's Office.IMC"},
-	{3, 1010,   0, 0, 60, 127,   0, "1010 - Ledge.IMC"},
-	{3, 1011,   0, 0, 60, 127,   0, "1011 - Roof.IMC"},
-	{3, 1020,   0, 0, 60, 127,   0, "1020 - Tube Room.IMC"},
-	{3, 1021,   0, 0, 60, 127,   0, "1021 - Brennis.IMC"},
-	{3, 1022,   0, 0, 60, 127,   0, "1022 - Lobby.IMC"},
-	{3, 1023,   0, 0, 60, 127,   0, "1023 - Packing Room.IMC"},
-	{3, 1030,   0, 0, 60, 127,   0, "1030 - Garage.IMC"},
-	{3, 1031,   0, 0, 60, 127,   0, "1031 - Glottis' Shop.IMC"},
-	{3, 1032,   0, 0, 60, 127,   0, "1030 - Garage.IMC"},
-	{3, 1040,  21, 4, 30,  60,   0, "1040 - Festival Wet.IMC"},
-	{3, 1041,  21, 4, 12, 127,   0, "1041 - Festival Dry.IMC"},
-	{3, 1042,  21, 4, 12,  60,   0, "1041 - Festival Dry.IMC"},
-	{3, 1043,  21, 4, 12,  46,   0, "1041 - Festival Dry.IMC"},
-	{3, 1044,  21, 4, 12,  87,   0, "1040 - Festival Wet.IMC"},
-	{3, 1050,   0, 0, 60, 127,   0, "1050 - Headquarters.IMC"},
-	{2, 1060,   0, 0, 20,  80,   0, "1060 - Real World.IMC"},
-	{2, 1070,   0, 0, 60, 127,   0, "1070 - Stump Room.IMC"},
-	{2, 1071,   0, 3, 60, 127,   0, "1071 - Signpost Room.IMC"},
-	{2, 1072,   0, 0, 60, 127,   0, "1072 - Navigation.IMC"},
-	{2, 1073,   0, 3, 60, 127,   0, "1071 - Signpost Room.IMC"},
-	{2, 1074,   0, 0, 60, 127,   0, "1074 - Bone Wagon.IMC"},
-	{2, 1075,   0, 0, 60, 127,   0, "1075 - Spider's Eye.IMC"},
-	{2, 1076,   0, 0, 60, 127,   0, "1076 - Spider Room.IMC"},
-	{2, 1077,   0, 0, 60, 127,   0, "1077 - Tree Pump Amb.IMC"},
-	{2, 1078,   0, 0, 60, 127,   0, "1078 - Tree Pump.IMC"},
-	{2, 1079,   0, 3, 60, 127,   0, "1071 - Signpost Room.IMC"},
-	{2, 1080,   0, 0, 60, 127,   0, "1080 - Beaver Room Lobby.IMC"},
-	{2, 1081,   0, 0, 60, 127,   0, "1081 - Beaver Dam.IMC"},
-	{2, 1082,   0, 0, 60, 127,   0, "1083 - Beaver Room.IMC"},
-	{2, 1083,   0, 0, 60, 127,   0, "1083 - Beaver Room.IMC"},
-	{2, 1084,   0, 0, 60,  80,   0, "1084 - Foggy Cactus.IMC"},
-	{2, 1085,   0, 0, 60, 105,   0, "1085 - Rubamat Exterior.IMC"},
-	{2, 1086,   0, 4, 60,  80,  30, "1087 - Blue Hector.IMC"},
-	{2, 1100,   0, 0, 60, 127,   0, "1109 - Cafe Exterior.IMC"},
-	{3, 1101,  45, 5, 24,  60,   0, "1101 - Cafe Office.IMC"},
-	{3, 1102,  45, 0, 24, 127,   0, "1102 - Cafe Intercom.IMC"},
-	{3, 1103,  49, 4, 24,  60, 100, "1103 - Coat Check.IMC"},
-	{2, 1104,   0, 0, 20, 127,   0, "1104 - Lupe.IMC"},
-	{3, 1105,  49, 4, 24, 127,  75, "1106 - Glottis Noodle.IMC"},
-	{3, 1106,  49, 4, 24, 127,  75, "1106 - Glottis Noodle.IMC"},
-	{3, 1190,  49, 4, 24,  80,  45, "1106 - Glottis Noodle.IMC"},
-	{3, 1191,  49, 4, 24, 127, 127, "1106 - Glottis Noodle.IMC"},
-	{3, 1107,  45, 5, 24, 127,   0, "1101 - Cafe Office.IMC"},
-	{3, 1108,  45, 6, 24, 127,   0, "1108 - Casino Interior.IMC"},
-	{2, 1109,   0, 0, 24, 127,   0, "1109 - Cafe Exterior.IMC"},
-	{2, 1110,   0, 0, 24, 105,   0, "1110 - Cafe Ledge.IMC"},
-	{3, 1111,   0, 0, 24,  60,   0, "1108 - Casino Interior.IMC"},
-	{2, 1112,   0, 0, 24, 127,  68, "1112 - Rusty Sans Vox.IMC"},
-	{2, 1120,   0, 0, 60, 127,   0, "1120 - Elevator Station.IMC"},
-	{3, 1121,   0, 0, 24, 127,   0, "1122 - Blue Exterior.IMC"},
-	{3, 1122,   0, 0, 24, 127,   0, "1122 - Blue Exterior.IMC"},
-	{2, 1123,   0, 4, 41, 127,   0, "1123 - Blue Casket Ins.IMC"},
-	{2, 1124,   0, 0, 60, 127,   0, "1124 - Blue Casket Amb.IMC"},
-	{2, 1125,   0, 4, 60,  80,  75, "1125 - Smooth Hector.IMC"},
-	{3, 1126,   0, 0, 24, 127,   0, "1122 - Blue Exterior.IMC"},
-	{3, 1127,  66, 0, 60, 127,   0, "1127 - Limbo Dock.IMC"},
-	{2, 1128,   0, 0, 24, 127,   0, "1128 - Limbo Talk.IMC"},
-	{3, 1129,  66, 0, 60, 127,   0, "1129 - Limbo Poem.IMC"},
-	{2, 1130,   0, 0, 24, 127,   0, "1130 - Dry Dock.IMC"},
-	{2, 1131,   0, 0, 24, 127,   0, "1131 - Dry Dock Strike.IMC"},
-	{2, 1132,   0, 0, 60, 127,   0, "1132 - Lighthouse Ext.IMC"},
-	{2, 1133,   0, 0, 60, 127,   0, "1133 - Lola's Last.IMC"},
-	{3, 1140,   0, 0, 60, 127,   0, "1140 - Police Station.IMC"},
-	{2, 1141,   0, 0, 60, 105,   0, "1141 - Police Interior.IMC"},
-	{2, 1142,   0, 0, 60, 105,   0, "1141 - Police Interior.IMC"},
-	{2, 1143,   0, 0, 60, 105,   0, "1143 - Morgue.IMC"},
-	{3, 1144,   0, 0, 60, 105,   0, "1140 - Police Station.IMC"},
-	{2, 1145,   0, 0, 60, 127,   0, "1145 - Bridge Blimp.IMC"},
-	{2, 1146,   0, 0, 60,  80,   0, "1146 - LOL Security Ext.IMC"},
-	{2, 1147,   0, 0, 60, 127,   0, "1147 - LOL Security Int.IMC"},
-	{2, 1148,   0, 0, 60, 127,   0, "1148 - Carla's Life.IMC"},
-	{2, 1149,   0, 0, 24, 127,   0, "1149 - Bomb.IMC"},
-	{3, 1150,  83, 0, 60, 105,   0, "1152 - Track Stairs.IMC"},
-	{3, 1151,  83, 0, 60, 105,   0, "1152 - Track Stairs.IMC"},
-	{3, 1152,  83, 0, 60, 105,   0, "1152 - Track Stairs.IMC"},
-	{2, 1153,   0, 0, 24, 127,   0, "1153 - Track Base.IMC"},
-	{2, 1154,   0, 0, 60, 127,   0, "1154 - Kitty Hall.IMC"},
-	{2, 1155,   0, 0, 60, 127,   0, "1155 - Sanspoof.IMC"},
-	{2, 1156,   0, 0, 60, 127,   0, "1156 - Kitty Stables.IMC"},
-	{2, 1160,   0, 0, 60, 127,   0, "1160 - High Roller Hall.IMC"},
-	{3, 1161,   0, 0, 24, 127,   0, "1161 - High Roller Lnge.IMC"},
-	{2, 1162,   0, 0, 60, 127,   0, "1162 - Glottis Gambling.IMC"},
-	{3, 1163,   0, 0, 24, 127,   0, "1163 - Max's Office.IMC"},
-	{3, 1164,  94, 4, 24, 127,  80, "1125 - Hector Steps Out.IMC"},
-	{3, 1165,  94, 4, 24,  20,  64, "1125 - Hector Steps Out.IMC"},
-	{3, 1166,  94, 4, 24, 127,  10, "1125 - Hector Steps Out.IMC"},
-	{3, 1167,   0, 0, 60, 127,   0, "1167 - Dillopede Elev.IMC"},
-	{3, 1168,   0, 0, 60, 127,   0, "1167 - Dillopede Elev.IMC"},
-	{3, 1169,   0, 0, 60, 127,   0, "1167 - Dillopede Elev.IMC"},
-	{3, 1170,   0, 0, 24, 105,   0, "1170 - Extendo Bridge.IMC"},
-	{3, 1171,   0, 0, 24, 105,   0, "1170 - Extendo Bridge.IMC"},
-	{3, 1172,   0, 0, 24, 105,   0, "1170 - Extendo Bridge.IMC"},
-	{2, 1173,   0, 0, 24, 127,   0, "1173 - Scrimshaw Int.IMC"},
-	{2, 1174,   0, 0, 24, 127,   0, "1174 - Scrim Sleep.IMC"},
-	{2, 1180,   0, 0, 60,  72,   0, "1180 - Note to Manny.IMC"},
-	{2, 1181,   0, 0, 60, 127,   0, "1155 - Sanspoof.IMC"},
-	{2, 1201,   0, 0, 60, 127,   0, "1201 - Lola Zapata.IMC"},
-	{2, 1202,   0, 0, 60, 127,   0, "1202 - Inside the Lola.IMC"},
-	{2, 1203,   0, 0, 60, 127,   0, "1203 - Engine Room.IMC"},
-	{2, 1204,   0, 0, 60, 127,   0, "1204 - Porthole.IMC"},
-	{2, 1205,   0, 0, 60, 127,   0, "1204 - Porthole.IMC"},
-	{2, 1210,   0, 0, 60, 127,   0, "1210 - Sunken Lola.IMC"},
-	{2, 1211,   0, 0, 60, 127,   0, "1211 - Pearl Crater Sub.IMC"},
-	{3, 1220,   0, 0, 60, 127,   0, "1220 - Miner's Room.IMC"},
-	{3, 1221,   0, 0, 60, 127,   0, "1221 - Miner's Room.IMC"},
-	{2, 1222,   0, 0, 60, 127,   0, "1222 - Exterior Airlock.IMC"},
-	{2, 1223,   0, 4, 60, 127,   0, "1223 - Factory Hub.IMC"},
-	{2, 1224,   0, 0, 60, 127,   0, "1224 - Foreman's Office.IMC"},
-	{2, 1230,   0, 0, 60, 127,   0, "1230 - Vault Door.IMC"},
-	{2, 1231,   0, 0, 60, 127,   0, "1231 - Outer Vault.IMC"},
-	{2, 1232,   0, 0, 60, 127,   0, "1232 - Inner Vault.IMC"},
-	{2, 1233,   0, 0, 60, 127,   0, "1233 - Ashtray Room.IMC"},
-	{2, 1234,   0, 0, 60, 127,   0, "1234 - Ashtray Scary.IMC"},
-	{2, 1235,   0, 0, 60, 127,   0, "1235 - Ashtray Pensive.IMC"},
-	{2, 1236,   0, 0, 60, 127,   0, "1236 - Domino's Room.IMC"},
-	{3, 1240,   0, 4, 60, 127,   0, "1240 - Conveyor Under.IMC"},
-	{3, 1241,   0, 0, 60, 127,   0, "1240 - Conveyor Under.IMC"},
-	{2, 1242,   0, 0, 60, 127,   0, "1241 - Crane Intro.IMC"},
-	{3, 1243,   0, 0, 60, 127,   0, "1243 - Anchor Room.IMC"},
-	{2, 1244,   0, 0, 60, 127,   0, "1244 - Glottis Hanging.IMC"},
-	{2, 1245,   0, 0, 60, 127,   0, "1245 - End of the World.IMC"},
-	{2, 1246,   0, 0, 60, 127,   0, "1246 - End World Later.IMC"},
-	{2, 1247,   0, 0, 60, 127,   0, "1241 - Crane Intro.IMC"},
-	{3, 1250,   0, 0, 60, 127,   0, "1250 - Upper Beach.IMC"},
-	{3, 1251,   0, 0, 60, 127,   0, "1250 - Upper Beach.IMC"},
-	{3, 1252,   0, 0, 60, 127,   0, "1252 - Lower Beach Boat.IMC"},
-	{2, 1253,   0, 0, 60, 127,   0, "1253 - Lamancha Sub.IMC"},
-	{2, 1254,   0, 0, 60, 127,   0, "1254 - Crane Later.IMC"},
-	{3, 1301,   0, 0, 60, 127,   0, "1301 - Temple Gate.IMC"},
-	{3, 1302,   0, 0, 60, 127,   0, "1301 - Temple Gate.IMC"},
-	{2, 1303,   0, 0, 60, 105,   0, "1303 - Truck Depot.IMC"},
-	{3, 1304, 143, 0, 60, 127,   0, "1304 - Mayan Train Sta.IMC"},
-	{2, 1305,   0, 0, 60, 127,   0, "1305 - Mayan Workshop.IMC"},
-	{3, 1306, 143, 0, 60, 127,   0, "1306 - Mayan Train Pad.IMC"},
-	{2, 1307,   0, 4, 60,  40,  64, "1307 - Mechanic's Kitch.IMC"},
-	{3, 1310,   0, 0, 60, 127,   0, "1310 - Jello Bomb.IMC"},
-	{3, 1311,   0, 0, 60, 127,   0, "1310 - Jello Bomb.IMC"},
-	{3, 1312, 150, 4, 12,  20,  64, "1125 - Smooth Hector.IMC"},
-	{3, 1313, 150, 4, 12,  50,  32, "1125 - Smooth Hector.IMC"},
-	{3, 1314, 150, 4, 12, 105,  75, "1125 - Smooth Hector.IMC"},
-	{3, 1315,   0, 0, 60, 127,   0, "1122 - Blue Exterior.IMC"},
-	{3, 1316,   0, 0, 60, 127,   0, "1122 - Blue Exterior.IMC"},
-	{3, 1317,   0, 0, 60, 127,   0, "1122 - Blue Exterior.IMC"},
-	{3, 1318,   0, 0, 60, 127,   0, "1332 - Hector's Foyer.IMC"},
-	{2, 1319,   0, 0, 60, 127,   0, "1319 - Florist Video.IMC"},
-	{2, 1320,   0, 0, 60, 127,   0, "1320 - New LSA HQ.IMC"},
-	{3, 1321,   0, 0, 60, 127,   0, "1321 - LSA Sewer.IMC"},
-	{3, 1322,   0, 0, 60, 127,   0, "1321 - LSA Sewer.IMC"},
-	{3, 1323,   0, 2, 60, 127,   0, "1323 - Sewer Maze.IMC"},
-	{3, 1324,   0, 0, 60, 127,   0, "1324 - Albinozod.IMC"},
-	{3, 1325, 162, 0, 60, 127,   0, "1325 - Florist Shop.IMC"},
-	{3, 1326, 162, 0, 60, 127,   0, "1326 - Florist Shop Int.IMC"},
-	{2, 1327,   0, 0, 60, 127,   0, "1327 - Florist OK.IMC"},
-	{3, 1328,   0, 2, 60, 127,   0, "1323 - Sewer Maze.IMC"},
-	{2, 1329,   0, 4, 60, 127,   0, "1329 - Theater Backstag.IMC"},
-	{2, 1330,   0, 0, 60, 127,   0, "1330 - Lemans Lobby.IMC"},
-	{2, 1331,   0, 0, 60,  60,   0, "1330 - Lemans Lobby.IMC"},
-	{3, 1332,   0, 0, 60, 127,   0, "1332 - Hector's Foyer.IMC"},
-	{2, 1333,   0, 0, 60, 127,   0, "1333 - Brennis Talk.IMC"},
-	{3, 1334,   0, 0, 60, 127,   0, "1334 - Albino Trap.IMC"},
-	{2, 1340,   0, 0, 60, 127,   0, "1342 - Neon Ledge.IMC"},
-	{2, 1350,   0, 0, 60, 127,   0, "1350 - Meadow Flowers.IMC"},
-	{2, 1351,   0, 0, 60, 127,   0, "1351 - Meadow.IMC"},
-	{2, 1352,   0, 0, 60, 127,   0, "1352 - Car Head.IMC"},
-	{2, 1353,   0, 0, 60, 127,   0, "1353 - Greenhouse Appr.IMC"},
-	{2, 1354,   0, 0, 60, 127,   0, "1354 - Game Ending.IMC"},
-	{2, 1355,   0, 0, 60, 127,   0, "1355 - Shootout.IMC"},
-	{2, 1400,   0, 0,  1, 105,   0, "1400 - Start Credits.IMC"},
-	{2, 1401,   0, 0, 60, 127,   0, "1401 - Smooth Hector.IMC"},
-	{0, 1500,   0, 0, 60, 127,   0, ""},
-	{0,   -1,   0, 0,  0,   0,   0, ""}
-};
-
-ImuseTable grimSeqMusicTable[] = {
-	{0, 2000,   0, 0, 20, 127,   0, ""},
-	{2, 2001,   0, 0, 20, 127,   0, "2001 - Climb Rope.IMC"},
-	{2, 2010,   0, 0, 20, 127,   0, "2010 - Glottis OK.IMC"},
-	{2, 2020,   0, 0, 20, 127,   0, "2020 - Reap Bruno.IMC"},
-	{2, 2030,   0, 0, 20, 127,   0, "2030 - Ledgepeckers.IMC"},
-	{2, 2050,   0, 0, 20, 105,   0, "2050 - Glottis Heart.IMC"},
-	{2, 2055,   0, 0, 20, 127,   0, "2055 - Slingshot Bone.IMC"},
-	{2, 2060,   0, 0, 20, 127,   0, "2060 - Glott Tree Fall.IMC"},
-	{2, 2070,   0, 0, 20, 127,   0, "2070 - Beaver Fly.IMC"},
-	{2, 2071,   0, 0, 20, 127,   0, "2071 - Beaver Sink.IMC"},
-	{2, 2080,   0, 0, 20, 127,   0, "2080 - Meet Velasco.IMC"},
-	{2, 2140,   0, 0, 20, 127,  75, "2140 - Ooo Bonewagon.IMC"},
-	{2, 2141,   0, 0, 20, 127,  75, "2141 - Ooo Meche.IMC"},
-	{2, 2155,   0, 0, 20, 127,   0, "2155 - Find Detector.IMC"},
-	{2, 2156,   0, 0, 20, 127,   0, "2156 - Glott Drink Wine.IMC"},
-	{2, 2157,   0, 0, 20, 127,   0, "2157 - Glott No Wine.IMC"},
-	{2, 2161,   0, 0, 20, 127,   0, "2161 - Raoul Appears.IMC"},
-	{2, 2162,   0, 0, 20, 127,   0, "2162 - Raoul KO.IMC"},
-	{2, 2163,   0, 0, 20, 127,   0, "2163 - Raoul Dissed.IMC"},
-	{2, 2165,   0, 0, 20, 127,   0, "2165 - Fake Tix.IMC"},
-	{2, 2180,   0, 0, 20, 127,   0, "2180 - Befriend Commies.IMC"},
-	{2, 2186,   0, 0, 20, 127,   0, "2186 - Nick Punchout.IMC"},
-	{2, 2200,   0, 0, 20, 127,   0, "2200 - Year 3 Iris.IMC"},
-	{2, 2210,   0, 0, 41, 127,   0, "2210 - Hit Men.IMC"},
-	{2, 2230,   0, 0, 20, 127,   0, "2230 - Open Vault.IMC"},
-	{2, 2235,   0, 0, 20, 127,   0, "2235 - Dead Tix.IMC"},
-	{2, 2240,   0, 0, 30, 127,   0, "2240 - Sprinkler.IMC"},
-	{2, 2250,   0, 0, 20, 127,   0, "2250 - Crane Track.IMC"},
-	{2, 2255,   0, 0, 20, 127,   0, "2255 - Crane Fall.IMC"},
-	{2, 2300,   0, 0, 20, 127,   0, "2300 - Yr 4 Iris.IMC"},
-	{2, 2301,   0, 0, 20, 127,   0, "2301 - Pop Bruno Casket.IMC"},
-	{2, 2310,   0, 0, 20, 127,   0, "2310 - Rocket Idea.IMC"},
-	{2, 2320,   0, 0, 20, 127,   0, "2320 - Jello Suspense.IMC"},
-	{2, 2325,   0, 0, 20, 127,   0, "2325 - Lumbago Lemo.IMC"},
-	{2, 2327,   0, 0, 20, 127,   0, "2327 - Breath Mint.IMC"},
-	{2, 2330,   0, 0, 20, 127,   0, "2330 - Pigeon Fly.IMC"},
-	{2, 2340,   0, 0, 20, 127,   0, "2340 - Coffee On Boys.IMC"},
-	{2, 2350,   0, 0, 20, 127,   0, "2350 - Sprout Aha.IMC"},
-	{2, 2360,   0, 0, 20, 127,   0, "2360 - Chowchilla Bye.IMC"},
-	{2, 2370,   0, 0, 20, 127,   0, "2370 - Salvador Death.IMC"},
-	{2, 2399,   0, 0, 12, 127,   0, "2399 - End Credits.IMC"},
-	{0,   -1,   0, 0,  0,   0,   0, ""}
-};
-
-ImuseTable grimDemoStateMusicTable[] = {
-	{0, 0,      0, 0, 60, 127,   0, ""},
-	{0, 1000,   0, 0, 60, 127,   0, ""},
-	{3, 1001,   0, 0, 60, 127,   0, "MO - Manny's Office.IMC"},
-	{3, 1002,   0, 0, 60, 127,   0, "MO - Manny's Office.IMC"},
-	{3, 1003,   0, 0, 60, 127,   0, "MO - Manny's Office.IMC"},
-	{3, 1004,   0, 0, 60, 127,   0, "DO - Domino's Office.IMC"},
-	{3, 1005,   0, 0, 60, 127,   0, "CO - Copal's Office.IMC"},
-	{3, 1010,   0, 0, 60, 127,   0, "LE - Ledge.IMC"},
-	{3, 1011,   0, 0, 60, 127,   0, "RF - Roof.IMC"},
-	{3, 1020,   0, 0, 60, 127,   0, "TU - Tube Room.IMC"},
-	{3, 1021,   0, 0, 60, 127,   0, "LO - Lobby.IMC"},
-	{3, 1022,   0, 0, 60, 127,   0, "PK - Packing Room.IMC"},
-	{3, 1030,   0, 0, 60, 127,   0, "PK - Packing Room.IMC"},
-	{3, 1031,   0, 0, 60, 127,   0, "PK - Packing Room.IMC"},
-	{3, 1040,   1, 0,  5,  60,   0, "Festival Wet.IMC"},
-	{3, 1041,   1, 0, 60, 127,   0, "Festival Dry.IMC"},
-	{3, 1042,   1, 0,  5,  50,   0, "Festival Dry.IMC"},
-	{3, 1043,   1, 0,  5,  64,   0, "Festival Dry.IMC"},
-	{3, 1044,   1, 0,  5,  75,   0, "Festival Wet.IMC"},
-	{3, 1050,   0, 0, 60, 127,   0, "HQ - Headquarters.IMC"},
-	{3, 1060,   0, 0, 60, 127,   0, ""},
-	{0, 5000,   0, 0, 60, 127,   0, ""},
-	{0,   -1,   0, 0,  0,   0,   0, ""}
-};
-
-ImuseTable grimDemoSeqMusicTable[] = {
-	{0, 2000,   0, 0, 60, 127,   0, ""},
-	{3, 2100,   0, 0, 60, 127,   0, "Rope Climb.IMC"},
-	{0,   -1,   0, 0,  0,   0,   0, ""}
-};
-
-} // end of namespace Grim
diff --git a/engines/grim/imuse/imuse_tables.h b/engines/grim/imuse/imuse_tables.h
deleted file mode 100644
index 1cf0564208d..00000000000
--- a/engines/grim/imuse/imuse_tables.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#ifndef GRIM_IMUSE_OLD_TABLES_H
-#define GRIM_IMUSE_OLD_TABLES_H
-
-namespace Grim {
-
-struct ImuseTable {
-	byte opcode;
-	int16 soundId;
-	byte atribPos;
-	byte hookId;
-	int16 fadeOut60TicksDelay;
-	byte volume;
-	byte pan;
-	char filename[32];
-};
-
-} // end of namespace Grim
-
-#endif
diff --git a/engines/grim/imuse/imuse_track.cpp b/engines/grim/imuse/imuse_track.cpp
deleted file mode 100644
index 5d83fd1a313..00000000000
--- a/engines/grim/imuse/imuse_track.cpp
+++ /dev/null
@@ -1,411 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#include "common/textconsole.h"
-
-#include "engines/grim/debug.h"
-
-#include "engines/grim/imuse/imuse.h"
-
-namespace Grim {
-
-int Imuse::allocSlot(int priority) {
-	int l, lowest_priority = 127;
-	int trackId = -1;
-
-	// allocSlot called by startSound so no locking is necessary
-	for (l = 0; l < MAX_IMUSE_TRACKS; l++) {
-		if (!_track[l]->used) {
-			trackId = l;
-			break;
-		}
-	}
-
-	if (trackId == -1) {
-		Debug::warning(Debug::Sound, "Imuse::startSound(): All slots are full");
-		for (l = 0; l < MAX_IMUSE_TRACKS; l++) {
-			Track *track = _track[l];
-			if (track->used && !track->toBeRemoved &&
-					(lowest_priority > track->priority)) {
-				lowest_priority = track->priority;
-				trackId = l;
-			}
-		}
-		if (lowest_priority <= priority) {
-			assert(trackId != -1);
-			Track *track = _track[trackId];
-
-			// Stop the track immediately
-			g_system->getMixer()->stopHandle(track->handle);
-			if (track->soundDesc) {
-				_sound->closeSound(track->soundDesc);
-			}
-
-			// Mark it as unused
-			track->clear();
-		} else {
-			return -1;
-		}
-	}
-
-	return trackId;
-}
-
-bool Imuse::startSound(const char *soundName, int volGroupId, int hookId, int volume, int pan, int priority, Track *otherTrack) {
-	Common::StackLock lock(_mutex);
-	Track *track = nullptr;
-	int i;
-
-	// If the track is fading out bring it back to the normal running tracks
-	for (i = MAX_IMUSE_TRACKS; i < MAX_IMUSE_TRACKS + MAX_IMUSE_FADETRACKS; i++) {
-		if (!scumm_stricmp(_track[i]->soundName, soundName) && !_track[i]->toBeRemoved) {
-
-			Track *fadeTrack = _track[i];
-			track = _track[i - MAX_IMUSE_TRACKS];
-
-			if (track->used) {
-				flushTrack(track);
-				g_system->getMixer()->stopHandle(track->handle);
-			}
-
-			// Clone the settings of the given track
-			memcpy(track, fadeTrack, sizeof(Track));
-			track->trackId = i - MAX_IMUSE_TRACKS;
-			// Reset the track
-			fadeTrack->clear();
-			// Mark as used for now so the track won't be reused again this frame
-			track->used = true;
-
-			return true;
-		}
-	}
-
-	// If the track is already playing then there is absolutely no
-	// reason to start it again, the existing track should be modified
-	// instead of starting a new copy of the track
-	for (i = 0; i < MAX_IMUSE_TRACKS; i++) {
-		// Filenames are case insensitive, see findTrack
-		if (!scumm_stricmp(_track[i]->soundName, soundName)) {
-			Debug::debug(Debug::Sound, "Imuse::startSound(): Track '%s' already playing.", soundName);
-			return true;
-		}
-	}
-
-	// Priority Level 127 appears to mean "load but don't play", so
-	// within our paradigm this is a much lower priority than everything
-	// else we're doing
-	if (priority == 127)
-		priority = -1;
-
-	int l = allocSlot(priority);
-	if (l == -1) {
-		Debug::warning(Debug::Sound, "Imuse::startSound() Can't start sound - no free slots");
-		return false;
-	}
-
-	track = _track[l];
-	// Reset the track
-	track->clear();
-
-	track->pan = pan * 1000;
-	track->vol = volume * 1000;
-	track->volGroupId = volGroupId;
-	track->curHookId = hookId;
-	track->priority = priority;
-	track->curRegion = -1;
-	track->trackId = l;
-
-
-	Common::strcpy_s(track->soundName, soundName);
-	track->soundDesc = _sound->openSound(soundName, volGroupId);
-
-	if (!track->soundDesc)
-		return false;
-
-	const int bits = _sound->getBits(track->soundDesc);
-	const int channels = _sound->getChannels(track->soundDesc);
-	const int freq = _sound->getFreq(track->soundDesc);
-
-	assert(bits == 8 || bits == 12 || bits == 16);
-	assert(channels == 1 || channels == 2);
-	assert(0 < freq && freq <= 65535);
-	(void)bits;
-
-	track->feedSize = freq * channels * 2;
-	track->mixerFlags = kFlag16Bits;
-	if (channels == 2)
-		track->mixerFlags |= kFlagStereo | kFlagReverseStereo;
-
-	if (otherTrack && otherTrack->used && !otherTrack->toBeRemoved) {
-		track->curRegion = otherTrack->curRegion;
-		track->dataOffset = otherTrack->dataOffset;
-		track->regionOffset = otherTrack->regionOffset;
-	}
-
-	track->stream = Audio::makeQueuingAudioStream(freq, track->mixerFlags & kFlagStereo);
-	g_system->getMixer()->playStream(track->getType(), &track->handle, track->stream, -1,
-											track->getVol(), track->getPan(), DisposeAfterUse::YES,
-											false, (track->mixerFlags & kFlagReverseStereo) != 0);
-	track->used = true;
-
-	return true;
-}
-
-Track *Imuse::findTrack(const char *soundName) {
-	for (int l = 0; l < MAX_IMUSE_TRACKS; l++) {
-		Track *track = _track[l];
-
-		// Since the audio (at least for Eva's keystrokes) can be referenced
-		// two ways: keyboard.IMU and keyboard.imu, make a case insensitive
-		// search for the track to make sure we can find it
-		if (track->used && !track->toBeRemoved
-				&& strlen(track->soundName) != 0 && scumm_stricmp(track->soundName, soundName) == 0) {
-			return track;
-		}
-	}
-	return nullptr;
-}
-
-void Imuse::setPriority(const char *soundName, int priority) {
-	Common::StackLock lock(_mutex);
-	Track *changeTrack = nullptr;
-	assert ((priority >= 0) && (priority <= 127));
-
-	changeTrack = findTrack(soundName);
-	// Check to make sure we found the track
-	if (changeTrack == nullptr) {
-		Debug::warning(Debug::Sound, "Unable to find track '%s' to change priority", soundName);
-		return;
-	}
-	changeTrack->priority = priority;
-}
-
-void Imuse::setVolume(const char *soundName, int volume) {
-	Common::StackLock lock(_mutex);
-	Track *changeTrack;
-
-	changeTrack = findTrack(soundName);
-	if (changeTrack == nullptr) {
-		Debug::warning(Debug::Sound, "Unable to find track '%s' to change volume", soundName);
-		return;
-	}
-	changeTrack->vol = volume * 1000;
-}
-
-void Imuse::setPan(const char *soundName, int pan) {
-	Common::StackLock lock(_mutex);
-	Track *changeTrack;
-
-	changeTrack = findTrack(soundName);
-	if (changeTrack == nullptr) {
-		Debug::warning(Debug::Sound, "Unable to find track '%s' to change pan", soundName);
-		return;
-	}
-	changeTrack->pan = pan * 1000;
-}
-
-int Imuse::getVolume(const char *soundName) {
-	Common::StackLock lock(_mutex);
-	Track *getTrack;
-
-	getTrack = findTrack(soundName);
-	if (getTrack == nullptr) {
-		Debug::warning(Debug::Sound, "Unable to find track '%s' to get volume", soundName);
-		return 0;
-	}
-	return getTrack->vol / 1000;
-}
-
-void Imuse::setHookId(const char *soundName, int hookId) {
-	Common::StackLock lock(_mutex);
-	Track *changeTrack;
-
-	changeTrack = findTrack(soundName);
-	if (changeTrack == nullptr) {
-		Debug::warning(Debug::Sound, "Unable to find track '%s' to change hook id", soundName);
-		return;
-	}
-	changeTrack->curHookId = hookId;
-}
-
-int Imuse::getCountPlayedTracks(const char *soundName) {
-	Common::StackLock lock(_mutex);
-	int count = 0;
-
-	for (int l = 0; l < MAX_IMUSE_TRACKS; l++) {
-		Track *track = _track[l];
-		if (track->used && !track->toBeRemoved && (scumm_stricmp(track->soundName, soundName) == 0)) {
-			count++;
-		}
-	}
-
-	return count;
-}
-
-void Imuse::selectVolumeGroup(const char *soundName, int volGroupId) {
-	Common::StackLock lock(_mutex);
-	Track *changeTrack;
-	assert((volGroupId >= 1) && (volGroupId <= 4));
-
-	if (volGroupId == 4)
-		volGroupId = 3;
-
-	changeTrack = findTrack(soundName);
-	if (changeTrack == nullptr) {
-		Debug::warning(Debug::Sound, "Unable to find track '%s' to change volume group id", soundName);
-		return;
-	}
-	changeTrack->volGroupId = volGroupId;
-}
-
-void Imuse::setFadeVolume(const char *soundName, int destVolume, int duration) {
-	Common::StackLock lock(_mutex);
-	Track *changeTrack;
-
-	changeTrack = findTrack(soundName);
-	if (changeTrack == nullptr) {
-		Debug::warning(Debug::Sound, "Unable to find track '%s' to change fade volume", soundName);
-		return;
-	}
-	changeTrack->volFadeDelay = duration;
-	changeTrack->volFadeDest = destVolume * 1000;
-	changeTrack->volFadeStep = (changeTrack->volFadeDest - changeTrack->vol) * 60 * (1000 / _callbackFps) / (1000 * duration);
-	changeTrack->volFadeUsed = true;
-}
-
-void Imuse::setFadePan(const char *soundName, int destPan, int duration) {
-	Common::StackLock lock(_mutex);
-	Track *changeTrack;
-
-	changeTrack = findTrack(soundName);
-	if (changeTrack == nullptr) {
-		Debug::warning(Debug::Sound, "Unable to find track '%s' to change fade pan", soundName);
-		return;
-	}
-	changeTrack->panFadeDelay = duration;
-	changeTrack->panFadeDest = destPan * 1000;
-	changeTrack->panFadeStep = (changeTrack->panFadeDest - changeTrack->pan) * 60 * (1000 / _callbackFps) / (1000 * duration);
-	changeTrack->panFadeUsed = true;
-}
-
-char *Imuse::getCurMusicSoundName() {
-	Common::StackLock lock(_mutex);
-	for (int l = 0; l < MAX_IMUSE_TRACKS; l++) {
-		Track *track = _track[l];
-		if (track->used && !track->toBeRemoved && (track->volGroupId == IMUSE_VOLGRP_MUSIC)) {
-			return track->soundName;
-		}
-	}
-	return nullptr;
-}
-
-int Imuse::getCurMusicPan() {
-	Common::StackLock lock(_mutex);
-	for (int l = 0; l < MAX_IMUSE_TRACKS; l++) {
-		Track *track = _track[l];
-		if (track->used && !track->toBeRemoved && (track->volGroupId == IMUSE_VOLGRP_MUSIC)) {
-			return track->pan / 1000;
-		}
-	}
-	return 0;
-}
-
-int Imuse::getCurMusicVol() {
-	Common::StackLock lock(_mutex);
-	for (int l = 0; l < MAX_IMUSE_TRACKS; l++) {
-		Track *track = _track[l];
-		if (track->used && !track->toBeRemoved && (track->volGroupId == IMUSE_VOLGRP_MUSIC)) {
-			return track->vol / 1000;
-		}
-	}
-	return 0;
-}
-
-void Imuse::fadeOutMusic(int duration) {
-	Common::StackLock lock(_mutex);
-	for (int l = 0; l < MAX_IMUSE_TRACKS; l++) {
-		Track *track = _track[l];
-		if (track->used && !track->toBeRemoved && (track->volGroupId == IMUSE_VOLGRP_MUSIC)) {
-			cloneToFadeOutTrack(track, duration);
-			flushTrack(track);
-			return;
-		}
-	}
-}
-
-void Imuse::fadeOutMusicAndStartNew(int fadeDelay, const char *filename, int hookId, int vol, int pan) {
-	Common::StackLock lock(_mutex);
-
-	for (int l = 0; l < MAX_IMUSE_TRACKS; l++) {
-		Track *track = _track[l];
-		if (track->used && !track->toBeRemoved && (track->volGroupId == IMUSE_VOLGRP_MUSIC)) {
-			startMusicWithOtherPos(filename, 0, vol, pan, track);
-			cloneToFadeOutTrack(track, fadeDelay);
-			flushTrack(track);
-			break;
-		}
-	}
-}
-
-Track *Imuse::cloneToFadeOutTrack(Track *track, int fadeDelay) {
-	assert(track);
-	Track *fadeTrack;
-
-	if (track->toBeRemoved) {
-		error("cloneToFadeOutTrack: Tried to clone a track to be removed, please bug report");
-		return nullptr;
-	}
-
-	assert(track->trackId < MAX_IMUSE_TRACKS);
-	fadeTrack = _track[track->trackId + MAX_IMUSE_TRACKS];
-
-	if (fadeTrack->used) {
-		flushTrack(fadeTrack);
-		g_system->getMixer()->stopHandle(fadeTrack->handle);
-	}
-
-	// Clone the settings of the given track
-	memcpy(fadeTrack, track, sizeof(Track));
-	fadeTrack->trackId = track->trackId + MAX_IMUSE_TRACKS;
-
-	// Clone the sound.
-	// leaving bug number for now #3005
-	ImuseSndMgr::SoundDesc *soundDesc = _sound->cloneSound(track->soundDesc);
-	assert(soundDesc);
-	track->soundDesc = soundDesc;
-
-	// Set the volume fading parameters to indicate a fade out
-	fadeTrack->volFadeDelay = fadeDelay;
-	fadeTrack->volFadeDest = 0;
-	fadeTrack->volFadeStep = (fadeTrack->volFadeDest - fadeTrack->vol) * 60 * (1000 / _callbackFps) / (1000 * fadeDelay);
-	fadeTrack->volFadeUsed = true;
-
-	// Create an appendable output buffer
-	fadeTrack->stream = Audio::makeQueuingAudioStream(_sound->getFreq(fadeTrack->soundDesc), track->mixerFlags & kFlagStereo);
-	g_system->getMixer()->playStream(track->getType(), &fadeTrack->handle, fadeTrack->stream, -1, fadeTrack->getVol(),
-											fadeTrack->getPan(), DisposeAfterUse::YES, false,
-											(track->mixerFlags & kFlagReverseStereo) != 0);
-	fadeTrack->used = true;
-
-	return fadeTrack;
-}
-
-} // end of namespace Grim
diff --git a/engines/grim/imuse/imuse_track.h b/engines/grim/imuse/imuse_track.h
deleted file mode 100644
index e17e42325c1..00000000000
--- a/engines/grim/imuse/imuse_track.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#ifndef GRIM_IMUSE_TRACK_H
-#define GRIM_IMUSE_TRACK_H
-
-#include "engines/grim/imuse/imuse_sndmgr.h"
-
-namespace Grim {
-
-enum {
-	kFlagUnsigned = 1 << 0,
-	kFlag16Bits = 1 << 1,
-	kFlagLittleEndian = 1 << 2,
-	kFlagStereo = 1 << 3,
-	kFlagReverseStereo = 1 << 4
-};
-
-struct Track {
-	int trackId;
-
-	int32 pan;
-	int32 panFadeDest;
-	int32 panFadeStep;
-	int32 panFadeDelay;
-	bool panFadeUsed;
-	int32 vol;
-	int32 volFadeDest;
-	int32 volFadeStep;
-	int32 volFadeDelay;
-	bool volFadeUsed;
-
-	char soundName[32];
-	bool used;
-	bool toBeRemoved;
-	int32 priority;
-	int32 regionOffset;
-	int32 dataOffset;
-	int32 curRegion;
-	int32 curHookId;
-	int32 volGroupId;
-	int32 feedSize;
-	int32 mixerFlags;
-
-	ImuseSndMgr::SoundDesc *soundDesc;
-	Audio::SoundHandle handle;
-	Audio::QueuingAudioStream *stream;
-
-	Track() {
-		clear();
-	}
-
-	void clear() {
-		trackId = 0;
-
-		pan = 0;
-		panFadeDest = 0;
-		panFadeStep = 0;
-		panFadeDelay = 0;
-		panFadeUsed = 0;
-		vol = 0;
-		volFadeDest = 0;
-		volFadeStep = 0;
-		volFadeDelay = 0;
-		volFadeUsed = 0;
-
-		for (uint i = 0; i < ARRAYSIZE(soundName); i++) {
-			soundName[i] = 0;
-		}
-		used = false;
-		toBeRemoved = false;
-		priority = 0;
-		regionOffset = 0;
-		dataOffset = 0;
-		curRegion = 0;
-		curHookId = 0;
-		volGroupId = 0;
-		feedSize = 0;
-		mixerFlags = 0;
-
-		soundDesc = nullptr;
-		// handle not cleared. FIXME: Clear by resetting _val to default (0xFFFFFFFF not 0)?
-		stream = nullptr;
-	}
-
-	/* getPan() returns -127 ... 127 */
-	int getPan() const { return (pan != 64000) ? 2 * (pan / 1000) - 127 : 0; }
-	int getVol() const { return vol / 1000; }
-	Audio::Mixer::SoundType getType() const {
-		Audio::Mixer::SoundType type = Audio::Mixer::kPlainSoundType;
-		if (volGroupId == IMUSE_VOLGRP_VOICE)
-			type = Audio::Mixer::kSpeechSoundType;
-		else if (volGroupId == IMUSE_VOLGRP_SFX)
-			type = Audio::Mixer::kSFXSoundType;
-		else if (volGroupId == IMUSE_VOLGRP_MUSIC)
-			type = Audio::Mixer::kMusicSoundType;
-		else if (volGroupId == IMUSE_VOLGRP_BGND)
-			type = Audio::Mixer::kPlainSoundType;
-		else if (volGroupId == IMUSE_VOLGRP_ACTION)
-			type = Audio::Mixer::kPlainSoundType;
-		return type;
-	}
-};
-
-} // end of namespace Grim
-
-#endif
diff --git a/engines/grim/module.mk b/engines/grim/module.mk
index 83a8c9d1940..467c189b3fe 100644
--- a/engines/grim/module.mk
+++ b/engines/grim/module.mk
@@ -43,7 +43,6 @@ MODULE_OBJS := \
 	emi/lua_v2_sound.o \
 	emi/emi_registry.o \
 	imuse/dimuse_cmds.o \
-	imuse/dimuse_codecs.o \
 	imuse/dimuse_dispatch.o \
 	imuse/dimuse_engine.o \
 	imuse/dimuse_fades.o \


Commit: d8df7ed005162e81a89e4f6fd12ad0e34cda7d48
    https://github.com/scummvm/scummvm/commit/d8df7ed005162e81a89e4f6fd12ad0e34cda7d48
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Mass renames to new iMUSE files

Now that the old implementation is removed, we bring
back some order on filenames, classes and so on...

Changed paths:
  A engines/grim/imuse/imuse_cmds.cpp
  A engines/grim/imuse/imuse_defs.h
  A engines/grim/imuse/imuse_dispatch.cpp
  A engines/grim/imuse/imuse_engine.cpp
  A engines/grim/imuse/imuse_engine.h
  A engines/grim/imuse/imuse_fades.cpp
  A engines/grim/imuse/imuse_fades.h
  A engines/grim/imuse/imuse_files.cpp
  A engines/grim/imuse/imuse_groups.cpp
  A engines/grim/imuse/imuse_groups.h
  A engines/grim/imuse/imuse_hmi.cpp
  A engines/grim/imuse/imuse_internalmixer.cpp
  A engines/grim/imuse/imuse_internalmixer.h
  A engines/grim/imuse/imuse_scripts.cpp
  A engines/grim/imuse/imuse_streamer.cpp
  A engines/grim/imuse/imuse_tables.cpp
  A engines/grim/imuse/imuse_tables.h
  A engines/grim/imuse/imuse_tracks.cpp
  A engines/grim/imuse/imuse_triggers.cpp
  A engines/grim/imuse/imuse_triggers.h
  A engines/grim/imuse/imuse_utils.cpp
  A engines/grim/imuse/imuse_waveout.cpp
  R engines/grim/imuse/dimuse_cmds.cpp
  R engines/grim/imuse/dimuse_defs.h
  R engines/grim/imuse/dimuse_dispatch.cpp
  R engines/grim/imuse/dimuse_engine.cpp
  R engines/grim/imuse/dimuse_engine.h
  R engines/grim/imuse/dimuse_fades.cpp
  R engines/grim/imuse/dimuse_fades.h
  R engines/grim/imuse/dimuse_files.cpp
  R engines/grim/imuse/dimuse_groups.cpp
  R engines/grim/imuse/dimuse_groups.h
  R engines/grim/imuse/dimuse_hmi.cpp
  R engines/grim/imuse/dimuse_internalmixer.cpp
  R engines/grim/imuse/dimuse_internalmixer.h
  R engines/grim/imuse/dimuse_scripts.cpp
  R engines/grim/imuse/dimuse_streamer.cpp
  R engines/grim/imuse/dimuse_tables.cpp
  R engines/grim/imuse/dimuse_tables.h
  R engines/grim/imuse/dimuse_tracks.cpp
  R engines/grim/imuse/dimuse_triggers.cpp
  R engines/grim/imuse/dimuse_triggers.h
  R engines/grim/imuse/dimuse_utils.cpp
  R engines/grim/imuse/dimuse_waveout.cpp
    engines/grim/actor.cpp
    engines/grim/costume/sound_component.cpp
    engines/grim/grim.cpp
    engines/grim/lua_v1_graphics.cpp
    engines/grim/lua_v1_sound.cpp
    engines/grim/module.mk
    engines/grim/set.cpp
    engines/grim/sound.cpp


diff --git a/engines/grim/actor.cpp b/engines/grim/actor.cpp
index 0f6979e508b..f70bc9f44ef 100644
--- a/engines/grim/actor.cpp
+++ b/engines/grim/actor.cpp
@@ -29,7 +29,7 @@
 #include "engines/grim/lipsync.h"
 #include "engines/grim/movie/movie.h"
 #include "engines/grim/sound.h"
-#include "engines/grim/imuse/dimuse_defs.h"
+#include "engines/grim/imuse/imuse_defs.h"
 #include "engines/grim/lua.h"
 #include "engines/grim/resource.h"
 #include "engines/grim/savegame.h"
diff --git a/engines/grim/costume/sound_component.cpp b/engines/grim/costume/sound_component.cpp
index fc171a3175d..6db290f0a13 100644
--- a/engines/grim/costume/sound_component.cpp
+++ b/engines/grim/costume/sound_component.cpp
@@ -24,7 +24,7 @@
 #include "engines/grim/debug.h"
 #include "engines/grim/costume.h"
 #include "engines/grim/costume/sound_component.h"
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 
 namespace Grim {
 
@@ -51,10 +51,10 @@ void SoundComponent::setKey(int val) {
 		if (!g_imuse->soundsIsSoundPlaying(_name.c_str())) {
 			if (isComponentType('I','M','S','S')) {
 				g_imuse->soundStartVoiceStream(_name.c_str(), _maxVolume, _pan);
-				g_imuse->soundsSetParam(_name.c_str(), DIMUSE_P_GROUP, DIMUSE_GROUP_SFX);
-				g_imuse->soundsSetParam(_name.c_str(), DIMUSE_P_PRIORITY, _priority);
+				g_imuse->soundsSetParam(_name.c_str(), IMUSE_P_GROUP, IMUSE_GROUP_SFX);
+				g_imuse->soundsSetParam(_name.c_str(), IMUSE_P_PRIORITY, _priority);
 			} else {
-				g_imuse->soundsLoadStartSound(_name.c_str(), _priority, DIMUSE_GROUP_SFX);
+				g_imuse->soundsLoadStartSound(_name.c_str(), _priority, IMUSE_GROUP_SFX);
 
 				Set *currSet = g_grim->getCurrSet();
 				if (currSet) {
diff --git a/engines/grim/grim.cpp b/engines/grim/grim.cpp
index c0d128b63df..bd9ee00e2c6 100644
--- a/engines/grim/grim.cpp
+++ b/engines/grim/grim.cpp
@@ -77,7 +77,7 @@
 #include "engines/grim/remastered/overlay.h"
 #include "engines/grim/remastered/lua_remastered.h"
 #include "engines/grim/remastered/commentary.h"
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 #include "engines/grim/emi/sound/emisound.h"
 #include "engines/grim/lua/lua.h"
 
@@ -384,24 +384,24 @@ Common::Error GrimEngine::run() {
 			g_movie = CreateBinkPlayer(demo);
 	}
 	if (getGameType() == GType_GRIM) {
-		int sampleRate = DIMUSE_BASE_SAMPLERATE;
-		ConfMan.registerDefault("dimuse_sample_rate", DIMUSE_BASE_SAMPLERATE);
-		if (ConfMan.hasKey("dimuse_sample_rate", _targetName)) {
+		int sampleRate = IMUSE_BASE_SAMPLERATE;
+		ConfMan.registerDefault("imuse_sample_rate", IMUSE_BASE_SAMPLERATE);
+		if (ConfMan.hasKey("imuse_sample_rate", _targetName)) {
 			// Only accept sample rates which are a multiple or submultiple of 22050
-			int configSampleRate = ConfMan.getInt("dimuse_sample_rate");
-			if ((configSampleRate % (DIMUSE_BASE_SAMPLERATE / 2)) == 0 &&
-				configSampleRate >= DIMUSE_BASE_SAMPLERATE / 2 &&
-				configSampleRate <= DIMUSE_BASE_SAMPLERATE * 4) {
+			int configSampleRate = ConfMan.getInt("imuse_sample_rate");
+			if ((configSampleRate % (IMUSE_BASE_SAMPLERATE / 2)) == 0 &&
+				configSampleRate >= IMUSE_BASE_SAMPLERATE / 2 &&
+				configSampleRate <= IMUSE_BASE_SAMPLERATE * 4) {
 				sampleRate = configSampleRate;
 			}
 		}
 
 		bool lowLatencyMode = false;
-		ConfMan.registerDefault("dimuse_low_latency_mode", false);
-		if (ConfMan.hasKey("dimuse_low_latency_mode", _targetName))
-			lowLatencyMode = ConfMan.getBool("dimuse_low_latency_mode");
+		ConfMan.registerDefault("imuse_low_latency_mode", false);
+		if (ConfMan.hasKey("imuse_low_latency_mode", _targetName))
+			lowLatencyMode = ConfMan.getBool("imuse_low_latency_mode");
 
-		g_imuse = new IMuseDigital(sampleRate, _mixer, &_imuseMutex, lowLatencyMode);
+		g_imuse = new IMuse(sampleRate, _mixer, &_imuseMutex, lowLatencyMode);
 		g_emiSound = nullptr;
 		if (g_grim->isRemastered()) {
 			// This must happen here, since we need the resource loader set up.
@@ -789,7 +789,7 @@ void GrimEngine::handleDebugLoadResource() {
 		resource = (void *)g_movie->play(buf, false, 0, 0);
 	else if (strstr(buf, ".wav") || strstr(buf, ".imu")) {
 		if (g_imuse)
-			g_imuse->soundsLoadStartSound(buf, 127, DIMUSE_GROUP_SFX);
+			g_imuse->soundsLoadStartSound(buf, 127, IMUSE_GROUP_SFX);
 		resource = (void *)1;
 	} else if (strstr(buf, ".mat")) {
 		CMap *cmap = g_resourceloader->loadColormap("item.cmp");
@@ -1210,7 +1210,7 @@ void GrimEngine::savegameRestore() {
 	if (!_savedState || !_savedState->isCompatible())
 		return;
 	if (g_imuse)
-		g_imuse->diMUSEStopAllSounds();
+		g_imuse->imStopAllSounds();
 	g_movie->stop();
 	if (g_imuse)
 		g_imuse->pause(true);
@@ -1238,7 +1238,7 @@ void GrimEngine::savegameRestore() {
 	Debug::debug(Debug::Engine, "Sets restored successfully.");
 
 	if (g_imuse)
-		g_imuse->floodMusicBuffer();
+		g_imuse->soundsFloodMusicBuffer();
 
 	TextObject::getPool().restoreObjects(_savedState);
 	Debug::debug(Debug::Engine, "TextObjects restored successfully.");
@@ -1550,7 +1550,7 @@ void GrimEngine::setSet(Set *scene) {
 		return;
 
 	if (g_imuse)
-		g_imuse->floodMusicBuffer();
+		g_imuse->soundsFloodMusicBuffer();
 
 	if (getGameType() == GType_MONKEY4) {
 		for (PoolSound *s : PoolSound::getPool()) {
diff --git a/engines/grim/imuse/dimuse_cmds.cpp b/engines/grim/imuse/dimuse_cmds.cpp
deleted file mode 100644
index 5f0eb0bef96..00000000000
--- a/engines/grim/imuse/dimuse_cmds.cpp
+++ /dev/null
@@ -1,90 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#include "engines/grim/imuse/dimuse_engine.h"
-
-namespace Grim {
-
-// We have some uintptr arguments as commands 17, 18, 19 and 29 actually require pointer arguments
-// Unfortunately this makes function calls for other command a little less pretty...
-int IMuseDigital::cmdsHandleCmd(int cmd, uint8 *ptr, int a, int b, int c, int d, int e,
-	int f, int g, int h, int i, int j, int k, int l, int m, int n) {
-
-	char *marker = (char *)ptr;
-
-	if (!_initialized)
-		return -1;
-
-	switch (cmd) {
-	case DIMUSE_C_INIT:
-		return diMUSEInitialize();
-	case DIMUSE_C_TERMINATE:
-		return diMUSETerminate();
-	case 2:
-		return cmd;
-	case DIMUSE_C_PAUSE:
-		diMUSEPause();
-		return cmd;
-	case DIMUSE_C_RESUME:
-		diMUSEResume();
-		return cmd;
-	case DIMUSE_C_SET_GRP_VOL:
-		return diMUSESetGroupVol(a, b);
-	case DIMUSE_C_START_SND:
-		return diMUSEStartSound(a, b);
-	case DIMUSE_C_STOP_SND:
-		return diMUSEStopSound(a);
-	case DIMUSE_C_STOP_ALL_SNDS:
-		return diMUSEStopAllSounds();
-	case DIMUSE_C_GET_NEXT_SND:
-		return diMUSEGetNextSound(a);
-	case DIMUSE_C_SET_PARAM:
-		return diMUSESetParam(a, b, c);
-	case DIMUSE_C_GET_PARAM:
-		return diMUSEGetParam(a, b);
-	case DIMUSE_C_FADE_PARAM:
-		return diMUSEFadeParam(a, b, c, d);
-	case DIMUSE_C_SET_HOOK:
-		return diMUSESetHook(a, b);
-	case DIMUSE_C_GET_HOOK:
-		return diMUSEGetHook(a);
-	case DIMUSE_C_SET_TRIGGER:
-		return diMUSESetTrigger(a, marker, c, d, e, f, g, h, i, j, k, l, m, n);
-	case DIMUSE_C_CHECK_TRIGGER:
-		return diMUSECheckTrigger(a, marker, c);
-	case DIMUSE_C_CLEAR_TRIGGER:
-		return diMUSEClearTrigger(a, marker, c);
-	case DIMUSE_C_DEFER_CMD:
-		return diMUSEDeferCommand(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
-	case DIMUSE_C_START_STREAM:
-		return diMUSEStartStream(a, b, c);
-	case DIMUSE_C_SWITCH_STREAM:
-		return diMUSESwitchStream(a, b, c, d, e);
-	case DIMUSE_C_PROCESS_STREAMS:
-		return diMUSEProcessStreams();
-	case DIMUSE_C_FEED_STREAM:
-		return diMUSEFeedStream(a, ptr, c, d);
-	default:
-		return -1;
-	}
-}
-
-} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_defs.h b/engines/grim/imuse/dimuse_defs.h
deleted file mode 100644
index f5b9988845b..00000000000
--- a/engines/grim/imuse/dimuse_defs.h
+++ /dev/null
@@ -1,327 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#ifndef GRIM_IMUSE_DEFS_H
-#define GRIM_IMUSE_DEFS_H
-
-namespace Common {
-class SeekableReadStream;
-}
-
-namespace Grim {
-
-#define DIMUSE_MAX_GROUPS      16
-#define DIMUSE_MAX_FADES       16
-#define DIMUSE_MAX_TRIGGERS    8
-#define DIMUSE_MAX_DEFERS      8
-#define DIMUSE_MAX_TRACKS      9
-#define DIMUSE_MAX_MAP_SIZE    512
-#define DIMUSE_MAX_DISPATCHES  9
-#define DIMUSE_MAX_STREAMZONES 50
-#define DIMUSE_MAX_FADE_VOLUME 8323072
-#define DIMUSE_MAX_STREAMS     3
-#define DIMUSE_MAX_SOUND_LIST  10
-#define DIMUSE_MAX_OPEN_FILES  5
-#define DIMUSE_MAX_CACHED_SOUNDS 32
-#define DIMUSE_SOUNDS_MEMORY_LIMIT 300000
-#define DIMUSE_MAX_LIPSYNCS    4
-#define DIMUSE_LIPSYNC_MAX_SIZE 2000
-#define DIMUSE_PHONEME_NONE    95
-#define DIMUSE_HMI_HEAP_SIZE   150000
-#define DIMUSE_HMI_TAIL_SIZE   18000
-
-#define DIMUSE_LARGE_FADES    1
-#define DIMUSE_SMALL_FADES    2
-#define DIMUSE_LARGE_FADE_DIM 100000
-#define DIMUSE_SMALL_FADE_DIM 44100
-
-#define DIMUSE_BASE_SAMPLERATE 22050
-#define DIMUSE_BASE_FEEDSIZE   512
-#define DIMUSE_NUM_WAVE_BUFS   8
-#define DIMUSE_SMUSH_SOUNDID   12345678
-
-enum {
-	kTalkSoundID = 10000
-};
-
-#define DIMUSE_BUN_CHUNK_SIZE  0x2000
-#define DIMUSE_GROUP_SFX       1
-#define DIMUSE_GROUP_SPEECH    2
-#define DIMUSE_GROUP_MUSIC     3
-#define DIMUSE_GROUP_MUSICEFF  4
-#define DIMUSE_BUFFER_SPEECH   1
-#define DIMUSE_BUFFER_MUSIC    2
-#define DIMUSE_BUFFER_SFX      3
-
-#define DIMUSE_TIMER_BASE_RATE_HZ       50
-#define DIMUSE_TIMER_BASE_RATE_USEC     20000  // 1000000 / 50Hz
-#define DIMUSE_TIMER_GAIN_RED_RATE_USEC 200000 // 1000000 / 5Hz
-#define DIMUSE_TIMER_FADES_RATE_USEC    20000  // 1000000 / 50Hz
-
-// Parameters IDs
-#define DIMUSE_P_BOGUS_ID       0x0
-#define DIMUSE_P_SND_TRACK_NUM  0x100
-#define DIMUSE_P_TRIGS_SNDS     0x200
-#define DIMUSE_P_MARKER         0x300
-#define DIMUSE_P_GROUP          0x400
-#define DIMUSE_P_PRIORITY       0x500
-#define DIMUSE_P_VOLUME         0x600
-#define DIMUSE_P_PAN            0x700
-#define DIMUSE_P_DETUNE         0x800
-#define DIMUSE_P_TRANSPOSE      0x900
-#define DIMUSE_P_MAILBOX        0xA00
-#define DIMUSE_P_UNKNOWN        0xF00
-#define DIMUSE_P_SND_HAS_STREAM 0x1800
-#define DIMUSE_P_STREAM_BUFID   0x1900
-#define DIMUSE_P_SND_POS_IN_MS  0x1A00
-
-// Soundkludge command IDs
-#define DIMUSE_C_KLUDGE_SET_STATE        0x1000
-#define DIMUSE_C_KLUDGE_SET_SEQUENCE     0x1001
-#define DIMUSE_C_KLUDGE_SET_CUE_POINT    0x1002
-#define DIMUSE_C_KLUDGE_SET_ATTRIBUTE    0x1003
-#define DIMUSE_C_KLUDGE_SET_SFX_VOLUME   0x2000
-#define DIMUSE_C_KLUDGE_SET_VOICE_VOLUME 0x2001
-#define DIMUSE_C_KLUDGE_SET_MUSIC_VOLUME 0x2002
-#define DIMUSE_C_KLUDGE_STOP_ALL_SNDS    10
-#define DIMUSE_C_KLUDGE_SET_PARAM        12
-#define DIMUSE_C_KLUDGE_FADE_PARAM       14
-#define DIMUSE_C_KLUDGE_START_STREAM     25
-#define DIMUSE_C_KLUDGE_SWITCH_STREAM    26
-
-// Script command IDs
-#define DIMUSE_C_SCRIPT_INIT          0
-#define DIMUSE_C_SCRIPT_TERMINATE     1
-#define DIMUSE_C_SCRIPT_SAVE          2
-#define DIMUSE_C_SCRIPT_RESTORE       3
-#define DIMUSE_C_SCRIPT_REFRESH       4
-#define DIMUSE_C_SCRIPT_SET_STATE     5
-#define DIMUSE_C_SCRIPT_SET_SEQUENCE  6
-#define DIMUSE_C_SCRIPT_CUE_POINT     7
-#define DIMUSE_C_SCRIPT_SET_ATTRIBUTE 8
-
-// Internal command IDs
-#define DIMUSE_C_INIT             0
-#define DIMUSE_C_TERMINATE        1
-#define DIMUSE_C_PAUSE            3
-#define DIMUSE_C_RESUME           4
-#define DIMUSE_C_SET_GRP_VOL      7
-#define DIMUSE_C_START_SND        8
-#define DIMUSE_C_STOP_SND         9
-#define DIMUSE_C_STOP_ALL_SNDS    10
-#define DIMUSE_C_GET_NEXT_SND     11
-#define DIMUSE_C_SET_PARAM        12
-#define DIMUSE_C_GET_PARAM        13
-#define DIMUSE_C_FADE_PARAM       14
-#define DIMUSE_C_SET_HOOK         15
-#define DIMUSE_C_GET_HOOK         16
-#define DIMUSE_C_SET_TRIGGER      17
-#define DIMUSE_C_CHECK_TRIGGER    18
-#define DIMUSE_C_CLEAR_TRIGGER    19
-#define DIMUSE_C_DEFER_CMD        20
-#define DIMUSE_C_START_STREAM     25
-#define DIMUSE_C_SWITCH_STREAM    26
-#define DIMUSE_C_PROCESS_STREAMS  27
-#define DIMUSE_C_FEED_STREAM      29
-
-// Trigger callback command ID
-#define DIMUSE_C_SCRIPT_CALLBACK  0
-
-class IMuseDigital;
-
-struct IMuseDigiDispatch;
-struct IMuseDigiTrack;
-struct IMuseDigiStreamZone;
-
-typedef struct {
-	int sound;
-	char text[256];
-	int opcode;
-	int a;
-	int b;
-	int c;
-	int d;
-	int e;
-	int f;
-	int g;
-	int h;
-	int i;
-	int j;
-	int clearLater;
-} IMuseDigiTrigger;
-
-typedef struct {
-	int counter;
-	int opcode;
-	int a;
-	int b;
-	int c;
-	int d;
-	int e;
-	int f;
-	int g;
-	int h;
-	int i;
-	int j;
-} IMuseDigiDefer;
-
-typedef struct {
-	int status;
-	int sound;
-	int param;
-	int currentVal;
-	int counter;
-	int length;
-	int slope;
-	int slopeMod;
-	int modOvfloCounter;
-	int nudge;
-} IMuseDigiFade;
-
-struct IMuseDigiTrack {
-	int index;
-	IMuseDigiTrack *prev;
-	IMuseDigiTrack *next;
-	IMuseDigiDispatch *dispatchPtr;
-	int soundId;
-	int marker;
-	int group;
-	int priority;
-	int vol;
-	int effVol;
-	int pan;
-	int detune;
-	int transpose;
-	int pitchShift;
-	int mailbox;
-	int jumpHook;
-};
-
-struct IMuseDigiStreamZone {
-	IMuseDigiStreamZone *prev;
-	IMuseDigiStreamZone *next;
-	int useFlag;
-	int32 offset;
-	int32 size;
-	int fadeFlag;
-};
-
-typedef struct {
-	int soundId;
-	int32 curOffset;
-	int32 endOffset;
-	int bufId;
-	uint8 *buf;
-	int32 bufFreeSize;
-	int32 loadSize;
-	int32 criticalSize;
-	int32 maxRead;
-	int32 loadIndex;
-	int32 readIndex;
-	int paused;
-} IMuseDigiStream;
-
-typedef struct {
-	uint8 *buffer;
-	int32 bufSize;
-	int32 loadSize;
-	int32 criticalSize;
-} IMuseDigiSndBuffer;
-
-struct IMuseDigiSoundList {
-	IMuseDigiSoundList *prev;
-	IMuseDigiSoundList *next;
-	int soundId;
-	char filename[36];
-	int refCount;
-};
-
-struct IMuseDigiResource {
-	Common::SeekableReadStream *resId;
-	bool hasMcmp;
-	int32 resSize;
-	int32 fileCurOffset;
-	int32 compBlocksNum;
-	uint8 *mcmpBlockPtr;
-	uint8 **compBlockPtr;
-	int32 *decompBlockSize;
-	int32 *compBlockOffset;
-	int32 *compBlockSize;
-	int32 *vimaOffsets;
-	int32 curProcessedCompBlock;
-	int32 curDecompBlockSize;
-	uint8 *decompDataBuffer;
-	char filename[80];
-};
-
-struct IMuseDigiCachedSound {
-	char soundFilename[32];
-	int luaSoundId;
-	uint32 tsOfAllocation;
-	uint8 *soundUncompData;
-	uint8 *soundAddrData;
-	uint8 *soundMap;
-	int uncompResourceSize;
-	int flag;
-	int priority;
-};
-
-struct IMuseDigiOpenAudioFile {
-	IMuseDigiResource *resourcePtr;
-	char soundName[32];
-	int refCount;
-};
-
-struct IMuseDigiDispatch {
-	IMuseDigiTrack *trackPtr;
-	int wordSize;
-	int sampleRate;
-	int channelCount;
-	int swapEndiannessFlag;
-	int32 currentOffset;
-	int32 audioRemaining;
-	int32 map[DIMUSE_MAX_MAP_SIZE];
-	IMuseDigiStream *streamPtr;
-	int streamBufID;
-	IMuseDigiStreamZone *streamZoneList;
-	int streamErrFlag;
-	uint8 *fadeBuf;
-	int32 fadeOffset;
-	int32 fadeRemaining;
-	int fadeWordSize;
-	int fadeSampleRate;
-	int fadeChannelCount;
-	int fadeSyncFlag;
-	int32 fadeSyncDelta;
-	int fadeVol;
-	int fadeSlope;
-};
-
-typedef struct {
-	int bytesPerSample;
-	int numChannels;
-	uint8 *mixBuf;
-	int mixBufSize;
-	int sizeSampleKB;
-} waveOutParamsStruct;
-
-} // End of namespace Grim
-#endif
diff --git a/engines/grim/imuse/dimuse_scripts.cpp b/engines/grim/imuse/dimuse_scripts.cpp
deleted file mode 100644
index d14a7a61473..00000000000
--- a/engines/grim/imuse/dimuse_scripts.cpp
+++ /dev/null
@@ -1,434 +0,0 @@
-/* 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 3 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, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#include "engines/grim/imuse/dimuse_engine.h"
-
-namespace Grim {
-
-#define GRIM_STATE_OFFSET   3
-#define GRIM_SEQ_OFFSET     185
-#define GRIM_STOP_SEQ_ATTR  227
-
-int IMuseDigital::scriptParse(int cmd, int a, int b) {
-	if (_scriptInitializedFlag || !cmd) {
-		switch (cmd) {
-		case DIMUSE_C_SCRIPT_INIT:
-			if (_scriptInitializedFlag) {
-				debug(5, "IMuseDigital::scriptParse(): script module already initialized");
-				return -1;
-			} else {
-				_scriptInitializedFlag = true;
-				return scriptInit();
-			}
-		case DIMUSE_C_SCRIPT_TERMINATE:
-			_scriptInitializedFlag = false;
-			return scriptTerminate();
-		case DIMUSE_C_SCRIPT_SAVE:
-		case DIMUSE_C_SCRIPT_RESTORE:
-			break;
-		case DIMUSE_C_SCRIPT_REFRESH:
-			scriptRefresh();
-			return 0;
-		case DIMUSE_C_SCRIPT_SET_STATE:
-			scriptSetState(a);
-			return 0;
-		case DIMUSE_C_SCRIPT_SET_SEQUENCE:
-			scriptSetSequence(a);
-			return 0;
-		case DIMUSE_C_SCRIPT_CUE_POINT:
-			scriptSetCuePoint(a);
-			return 0;
-		case DIMUSE_C_SCRIPT_SET_ATTRIBUTE:
-			return scriptSetAttribute(a, b);
-		default:
-			debug(5, "IMuseDigital::scriptParse(): unrecognized opcode (%d)", cmd);
-			return -1;
-		}
-	} else {
-		debug(5, "IMuseDigital::scriptParse(): script module not initialized");
-		return -1;
-	}
-
-	return -1;
-}
-
-int IMuseDigital::scriptInit() {
-	diMUSEInitFilelist();
-
-	_curMusicState = 0;
-	_curMusicSeq = 0;
-	_nextSeqToPlay = 0;
-	memset(_attributes, 0, sizeof(_attributes));
-	return 0;
-}
-
-int IMuseDigital::scriptTerminate() {
-	scriptDeinit();
-
-	_curMusicState = 0;
-	_curMusicSeq = 0;
-	_nextSeqToPlay = 0;
-	memset(_attributes, 0, sizeof(_attributes));
-	return 0;
-}
-
-void IMuseDigital::scriptRefresh() {
-	int soundId;
-
-	if (_attributes[GRIM_STOP_SEQ_ATTR]) {
-		scriptSetSequence(0);
-		_attributes[GRIM_STOP_SEQ_ATTR] = 0;
-	}
-
-	soundId = diMUSEGetNextSound(0);
-	while (soundId) {
-		if (diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM) && diMUSEGetParam(soundId, DIMUSE_P_STREAM_BUFID) == DIMUSE_BUFFER_MUSIC)
-			break;
-
-		soundId = diMUSEGetNextSound(soundId);
-	}
-
-	if (!soundId) {
-		if (_curMusicSeq)
-			scriptSetSequence(0);
-	}
-
-	diMUSEFlushSounds();
-}
-
-void IMuseDigital::scriptSetState(int stateId) {
-	int num;
-
-	if (stateId == -1)
-		return;
-
-	for (num = 0; num < ARRAYSIZE(_grimStateMusicTable); num++) {
-		if (_grimStateMusicTable[num].soundId == stateId)
-			break;
-	}
-
-	if (num == ARRAYSIZE(_grimStateMusicTable))
-		return;
-
-	debug(5, "IMuseDigital::scriptSetState(): Set music state: %s", _grimStateMusicTable[num].internalName);
-
-	if (num != _curMusicState) {
-		if (!_curMusicSeq)
-			scriptPlayMusic(num ? &_grimStateMusicTable[num] : nullptr, num, false);
-
-		_curMusicState = num;
-	}
-}
-
-void IMuseDigital::scriptSetSequence(int seqId) {
-	int num;
-
-	if (seqId == -1)
-		return;
-
-	if (seqId == 0)
-		seqId = 2000;
-
-	for (num = 0; num < ARRAYSIZE(_grimSeqMusicTable); num++) {
-		if (_grimSeqMusicTable[num].soundId == seqId)
-			break;
-	}
-
-	if (num == ARRAYSIZE(_grimSeqMusicTable)) {
-		debug(5, "IMuseDigital::scriptSetSequence(): bogus sequence");
-		return;
-	}
-
-	debug(5, "IMuseDigital::scriptSetSequence(): Set music sequence: %s", _grimSeqMusicTable[num].internalName);
-
-	if (num == _curMusicSeq)
-		return;
-
-	if (num) {
-		if (_curMusicSeq && (_grimSeqMusicTable[_curMusicSeq].transitionId == 4 || _grimSeqMusicTable[_curMusicSeq].transitionId == 6)) {
-			_nextSeqToPlay = num;
-			return;
-		}
-
-		scriptPlayMusic(&_grimSeqMusicTable[num], 0, true);
-		_nextSeqToPlay = 0;
-		_attributes[GRIM_SEQ_OFFSET + num] = 1;
-		_curMusicSeq = num;
-	} else {
-		if (_nextSeqToPlay) {
-			scriptPlayMusic(&_grimSeqMusicTable[_nextSeqToPlay], 0, true);
-			_curMusicSeq = _nextSeqToPlay;
-			_nextSeqToPlay = 0;
-			_attributes[GRIM_SEQ_OFFSET + _curMusicSeq] = 1;
-			return;
-		}
-
-		scriptPlayMusic(_curMusicState ? &_grimStateMusicTable[_curMusicState] : nullptr, _curMusicState, true);
-		_curMusicSeq = 0;
-	}
-}
-
-void IMuseDigital::scriptSetCuePoint(int cueId) {
-}
-
-int IMuseDigital::scriptSetAttribute(int attrIndex, int attrVal) {
-	if (attrIndex == -1) {
-		if (attrVal == 0) {
-			diMUSEPause();
-		} else if (attrVal == 1) {
-			diMUSEResume();
-		} else if (attrVal == -1) {
-			memset(_attributes, 0, sizeof(_attributes));
-		}
-	} else if (attrIndex == 10000) {
-		char *dest = (char *)(intptr)attrVal;
-
-		for (int i = 0; i < ARRAYSIZE(_grimStateMusicTable); i++) {
-			memcpy(dest, _grimStateMusicTable[i].name, strlen(_grimStateMusicTable[i].name) + 1);
-			dest += strlen(_grimStateMusicTable[i].name) + 1;
-		}
-
-		for (int i = 0; i < ARRAYSIZE(_grimSeqMusicTable); i++) {
-			memcpy(dest, _grimSeqMusicTable[i].name, strlen(_grimSeqMusicTable[i].name) + 1);
-			dest += strlen(_grimSeqMusicTable[i].name) + 1;
-		}
-	} else if ((uint32)attrIndex >= ARRAYSIZE(_attributes)) {
-		debug(5, "IMuseDigital::scriptSetAttribute(): bogus attribute");
-	} else if (attrVal != -1) {
-		debug(5, "IMuseDigital::scriptSetAttribute(): Set attr %u to %u", attrIndex, attrVal);
-		_attributes[attrIndex] = attrVal;
-	}
-
-	return 0;
-}
-
-void IMuseDigital::scriptSaveLoad(Common::Serializer &ser) {
-	if (ser.isLoading()) {
-		diMUSEUnloadAll();
-		diMUSECloseAll();
-	}
-
-	ser.syncAsSint32LE(_curMusicState, VER(30));
-	ser.syncAsSint32LE(_curMusicSeq, VER(30));
-	ser.syncAsSint32LE(_nextSeqToPlay, VER(30));
-	ser.syncArray(_attributes, ARRAYSIZE(_attributes), Common::Serializer::Sint32LE, VER(30));
-	diMUSESaveLoadFilelist(ser);
-}
-
-void IMuseDigital::scriptDeinit() {
-	diMUSEStopAllSounds();
-	diMUSEUnloadAll();
-	diMUSECloseAll();
-}
-
-int IMuseDigital::scriptTriggerCallback(char *marker) {
-	if (marker[0] != '_') {
-		debug(5, "IMuseDigital::scriptTriggerCallback(): got marker != '_end', callback ignored");
-		return -1;
-	}
-	_attributes[GRIM_STOP_SEQ_ATTR] = 1;
-	return 0;
-}
-
-void IMuseDigital::scriptPlayMusic(const IMuseDigiStateTable *tableEntry, int curSongEntryId, int isSequence) {
-	int hookId = 0;
-	int attribPos, oldSoundId, newSoundId, soundId;
-	int fadeTime, fadeDelay, fadeLength;
-	char fileName[64];
-
-	Common::StackLock lock(*_mutex);
-
-	if (tableEntry) {
-		attribPos = curSongEntryId;
-		if (curSongEntryId) {
-			if (tableEntry->attribPos)
-				attribPos = tableEntry->attribPos;
-
-			hookId = _attributes[GRIM_STATE_OFFSET + attribPos];
-
-			if (tableEntry->hookId) {
-				if (hookId || tableEntry->hookId <= 1) {
-					_attributes[GRIM_STATE_OFFSET + attribPos] = hookId + 1;
-					if (hookId + 1 > tableEntry->hookId)
-						_attributes[GRIM_STATE_OFFSET + attribPos] = 1;
-				} else {
-					_attributes[GRIM_STATE_OFFSET + attribPos] = 2;
-				}
-			}
-		}
-	}
-
-	if (!hookId)
-		hookId = 100;
-
-	// Fade out any music track which is not streamed
-	for (soundId = diMUSEGetNextSound(0); soundId; soundId = diMUSEGetNextSound(soundId)) {
-		if (diMUSEGetParam(soundId, DIMUSE_P_GROUP) == DIMUSE_GROUP_MUSICEFF && !diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM))
-			diMUSEFadeParam(soundId, DIMUSE_P_VOLUME, 0, 120);
-	}
-
-	oldSoundId = 0;
-	for (soundId = diMUSEGetNextSound(0); soundId; soundId = diMUSEGetNextSound(soundId)) {
-		if (diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM) && diMUSEGetParam(soundId, DIMUSE_P_STREAM_BUFID) == DIMUSE_BUFFER_MUSIC) {
-			oldSoundId = soundId;
-			break;
-		}
-	}
-
-	if (!tableEntry) {
-		if (oldSoundId)
-			diMUSEFadeParam(oldSoundId, DIMUSE_P_VOLUME, 0, 120);
-		return;
-	}
-
-	fadeTime = tableEntry->fadeTime;
-	if (!fadeTime)
-		fadeTime = 1000;
-
-	fadeDelay = fadeTime;
-	fadeLength = (3 * fadeTime) / 50;
-
-	switch (tableEntry->transitionId) {
-	case 0:
-		debug(5, "IMuseDigital::scriptPlayMusic(): NULL transition, ignored");
-		break;
-	case 2:
-	case 3:
-	case 4:
-	case 10:
-	case 11:
-	case 12:
-		// TODO
-		// The original remaps the name through a table which always appends ".IMC"
-		Common::strlcpy(fileName, tableEntry->name, sizeof(fileName));
-		Common::strlcat(fileName, ".IMC", sizeof(fileName));
-
-		debug(5, "IMuseDigital::scriptPlayMusic(): opening %s", fileName);
-		newSoundId = diMUSEOpenSound(fileName, 0);
-
-		if (!newSoundId) {
-			debug(5, "IMuseDigital::scriptPlayMusic(): unable to open %s", fileName);
-			if (oldSoundId)
-				diMUSEFadeParam(oldSoundId, DIMUSE_P_VOLUME, 0, 60);
-			return;
-		}
-
-		if (tableEntry->transitionId == 4) {
-			_attributes[GRIM_STOP_SEQ_ATTR] = 0;
-			diMUSESetTrigger(newSoundId, "_end", DIMUSE_C_SCRIPT_CALLBACK);
-		}
-
-		debug(5, "IMuseDigital::scriptPlayMusic(): HOOK=%d", hookId);
-
-		if (!oldSoundId) {
-			debug(5, "IMuseDigital::scriptPlayMusic(): no stream sound");
-			if (diMUSEStartStream(newSoundId, 126, DIMUSE_BUFFER_MUSIC))
-				debug(5, "IMuseDigital::scriptPlayMusic(): failed to start the stream for sound %d", newSoundId);
-
-			diMUSESetParam(newSoundId, DIMUSE_P_VOLUME, 0);
-			diMUSEFadeParam(newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
-			diMUSESetParam(newSoundId, DIMUSE_P_PAN, tableEntry->pan);
-			diMUSESetParam(newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-			diMUSESetHook(newSoundId, hookId);
-		} else if (tableEntry->transitionId == 2) {
-			diMUSESwitchStream(oldSoundId, newSoundId, fadeDelay, 0, 0);
-			debug(5, "IMuseDigital::scriptPlayMusic(): FADE=%d, vol=%d", fadeDelay, tableEntry->volume);
-			diMUSEFadeParam(newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
-			diMUSEFadeParam(newSoundId, DIMUSE_P_PAN, tableEntry->pan, fadeLength);
-			diMUSESetParam(newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-			diMUSESetHook(newSoundId, hookId);
-			diMUSEProcessStreams();
-		} else if (oldSoundId == newSoundId) {
-			diMUSEFadeParam(newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
-			debug(5, "IMuseDigital::scriptPlayMusic(): fading VOL=%d", tableEntry->volume);
-			if (tableEntry->pan) {
-				diMUSEFadeParam(newSoundId, DIMUSE_P_PAN, tableEntry->pan, fadeLength);
-				debug(5, "IMuseDigital::scriptPlayMusic(): and PAN=%d", tableEntry->pan);
-			}
-		} else if (!isSequence && tableEntry->attribPos && tableEntry->attribPos == _grimStateMusicTable[_curMusicState].attribPos) {
-			diMUSESwitchStream(oldSoundId, newSoundId, fadeDelay, 0, 1);
-			diMUSEFadeParam(newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
-			diMUSEFadeParam(newSoundId, DIMUSE_P_PAN, tableEntry->pan, fadeLength);
-			diMUSESetParam(newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-			if (hookId == 100)
-				diMUSESetHook(newSoundId, 100);
-			diMUSEProcessStreams();
-		} else if (tableEntry->transitionId == 10 || tableEntry->transitionId == 12) {
-			if (tableEntry->transitionId == 12) {
-				diMUSESetHook(oldSoundId, 99);
-				diMUSESetTrigger(oldSoundId, "clear", DIMUSE_C_SET_HOOK, oldSoundId, 128);
-			}
-
-			diMUSESetTrigger(oldSoundId, "exit", DIMUSE_C_SWITCH_STREAM, oldSoundId, newSoundId, fadeDelay, 1, 0);
-			diMUSESetTrigger(oldSoundId, "exit", DIMUSE_C_FADE_PARAM, newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
-			diMUSESetTrigger(oldSoundId, "exit", DIMUSE_C_FADE_PARAM, newSoundId, DIMUSE_P_PAN, tableEntry->pan, fadeLength);
-			diMUSESetTrigger(oldSoundId, "exit", DIMUSE_C_SET_PARAM, newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-			diMUSESetTrigger(oldSoundId, "exit", DIMUSE_C_SET_HOOK, newSoundId, hookId);
-			diMUSEProcessStreams();
-		} else if (tableEntry->transitionId == 11) {
-			diMUSESetTrigger(oldSoundId, "exit2", DIMUSE_C_SWITCH_STREAM, oldSoundId, newSoundId, fadeDelay, 1, 0);
-			diMUSESetTrigger(oldSoundId, "exit2", DIMUSE_C_FADE_PARAM, newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
-			diMUSESetTrigger(oldSoundId, "exit2", DIMUSE_C_FADE_PARAM, newSoundId, DIMUSE_P_PAN, tableEntry->pan, fadeLength);
-			diMUSESetTrigger(oldSoundId, "exit2", DIMUSE_C_SET_PARAM, newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-			diMUSESetTrigger(oldSoundId, "exit2", DIMUSE_C_SET_HOOK, newSoundId, hookId);
-			diMUSEProcessStreams();
-		} else {
-			diMUSESwitchStream(oldSoundId, newSoundId, fadeDelay, 0, 0);
-			debug(5, "IMuseDigital::scriptPlayMusic(): FADE=%d, vol=%d", fadeDelay, tableEntry->volume);
-			diMUSEFadeParam(newSoundId, DIMUSE_P_VOLUME, tableEntry->volume, fadeLength);
-			diMUSEFadeParam(newSoundId, DIMUSE_P_PAN, tableEntry->pan, fadeLength);
-			debug(5, "IMuseDigital::scriptPlayMusic(): set pan=%d", tableEntry->pan);
-			diMUSESetParam(newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-			diMUSESetHook(newSoundId, hookId);
-			diMUSEProcessStreams();
-		}
-
-		diMUSECloseSound(newSoundId);
-		diMUSESetParam(newSoundId, DIMUSE_P_GROUP, DIMUSE_GROUP_MUSICEFF);
-		break;
-	case 5:
-		break;
-	case 6:
-		_attributes[GRIM_STOP_SEQ_ATTR] = 0;
-		diMUSESetTrigger(DIMUSE_SMUSH_SOUNDID + DIMUSE_BUFFER_MUSIC, "_end", DIMUSE_C_SCRIPT_CALLBACK);
-		break;
-	case 7:
-		if (oldSoundId)
-			diMUSEFadeParam(oldSoundId, DIMUSE_P_VOLUME, 0, 60);
-		break;
-	case 8:
-		if (oldSoundId)
-			diMUSESetHook(oldSoundId, 100);
-		break;
-	case 9:
-		if (oldSoundId)
-			diMUSESetHook(oldSoundId, 99);
-
-		_attributes[GRIM_STOP_SEQ_ATTR] = 0;
-		diMUSESetTrigger(oldSoundId, "_end", DIMUSE_C_SCRIPT_CALLBACK);
-		break;
-	default:
-		debug(5, "IMuseDigital::scriptPlayMusic(): bogus transition type, ignored");
-		break;
-	}
-}
-
-} // End of namespace Grim
diff --git a/engines/grim/imuse/imuse_cmds.cpp b/engines/grim/imuse/imuse_cmds.cpp
new file mode 100644
index 00000000000..090e0accbba
--- /dev/null
+++ b/engines/grim/imuse/imuse_cmds.cpp
@@ -0,0 +1,90 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/imuse_engine.h"
+
+namespace Grim {
+
+// We have some uintptr arguments as commands 17, 18, 19 and 29 actually require pointer arguments
+// Unfortunately this makes function calls for other command a little less pretty...
+int IMuse::imSoundCall(int cmd, uint8 *ptr, int a, int b, int c, int d, int e,
+	int f, int g, int h, int i, int j, int k, int l, int m, int n) {
+
+	char *marker = (char *)ptr;
+
+	if (!_initialized)
+		return -1;
+
+	switch (cmd) {
+	case IMUSE_C_INIT:
+		return imInitialize();
+	case IMUSE_C_TERMINATE:
+		return imTerminate();
+	case 2:
+		return cmd;
+	case IMUSE_C_PAUSE:
+		imPause();
+		return cmd;
+	case IMUSE_C_RESUME:
+		imResume();
+		return cmd;
+	case IMUSE_C_SET_GRP_VOL:
+		return imSetGroupVol(a, b);
+	case IMUSE_C_START_SND:
+		return imStartSound(a, b);
+	case IMUSE_C_STOP_SND:
+		return imStopSound(a);
+	case IMUSE_C_STOP_ALL_SNDS:
+		return imStopAllSounds();
+	case IMUSE_C_GET_NEXT_SND:
+		return imGetNextSound(a);
+	case IMUSE_C_SET_PARAM:
+		return imSetParam(a, b, c);
+	case IMUSE_C_GET_PARAM:
+		return imGetParam(a, b);
+	case IMUSE_C_FADE_PARAM:
+		return imFadeParam(a, b, c, d);
+	case IMUSE_C_SET_HOOK:
+		return imSetHook(a, b);
+	case IMUSE_C_GET_HOOK:
+		return imGetHook(a);
+	case IMUSE_C_SET_TRIGGER:
+		return imSetTrigger(a, marker, c, d, e, f, g, h, i, j, k, l, m, n);
+	case IMUSE_C_CHECK_TRIGGER:
+		return imCheckTrigger(a, marker, c);
+	case IMUSE_C_CLEAR_TRIGGER:
+		return imClearTrigger(a, marker, c);
+	case IMUSE_C_DEFER_CMD:
+		return imDeferCommand(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
+	case IMUSE_C_START_STREAM:
+		return imStartStream(a, b, c);
+	case IMUSE_C_SWITCH_STREAM:
+		return imSwitchStream(a, b, c, d, e);
+	case IMUSE_C_PROCESS_STREAMS:
+		return imProcessStreams();
+	case IMUSE_C_FEED_STREAM:
+		return imFeedStream(a, ptr, c, d);
+	default:
+		return -1;
+	}
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/imuse_defs.h b/engines/grim/imuse/imuse_defs.h
new file mode 100644
index 00000000000..6a490d4c3a8
--- /dev/null
+++ b/engines/grim/imuse/imuse_defs.h
@@ -0,0 +1,327 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef GRIM_IMUSE_DEFS_H
+#define GRIM_IMUSE_DEFS_H
+
+namespace Common {
+class SeekableReadStream;
+}
+
+namespace Grim {
+
+#define IMUSE_MAX_GROUPS      16
+#define IMUSE_MAX_FADES       16
+#define IMUSE_MAX_TRIGGERS    8
+#define IMUSE_MAX_DEFERS      8
+#define IMUSE_MAX_TRACKS      9
+#define IMUSE_MAX_MAP_SIZE    512
+#define IMUSE_MAX_DISPATCHES  9
+#define IMUSE_MAX_STREAMZONES 50
+#define IMUSE_MAX_FADE_VOLUME 8323072
+#define IMUSE_MAX_STREAMS     3
+#define IMUSE_MAX_SOUND_LIST  10
+#define IMUSE_MAX_OPEN_FILES  5
+#define IMUSE_MAX_CACHED_SOUNDS 32
+#define IMUSE_SOUNDS_MEMORY_LIMIT 300000
+#define IMUSE_MAX_LIPSYNCS    4
+#define IMUSE_LIPSYNC_MAX_SIZE 2000
+#define IMUSE_PHONEME_NONE    95
+#define IMUSE_HMI_HEAP_SIZE   150000
+#define IMUSE_HMI_TAIL_SIZE   18000
+
+#define IMUSE_LARGE_FADES    1
+#define IMUSE_SMALL_FADES    2
+#define IMUSE_LARGE_FADE_DIM 100000
+#define IMUSE_SMALL_FADE_DIM 44100
+
+#define IMUSE_BASE_SAMPLERATE 22050
+#define IMUSE_BASE_FEEDSIZE   512
+#define IMUSE_NUM_WAVE_BUFS   8
+#define IMUSE_SMUSH_SOUNDID   12345678
+
+enum {
+	kTalkSoundID = 10000
+};
+
+#define IMUSE_BUN_CHUNK_SIZE  0x2000
+#define IMUSE_GROUP_SFX       1
+#define IMUSE_GROUP_SPEECH    2
+#define IMUSE_GROUP_MUSIC     3
+#define IMUSE_GROUP_MUSICEFF  4
+#define IMUSE_BUFFER_SPEECH   1
+#define IMUSE_BUFFER_MUSIC    2
+#define IMUSE_BUFFER_SFX      3
+
+#define IMUSE_TIMER_BASE_RATE_HZ       50
+#define IMUSE_TIMER_BASE_RATE_USEC     20000  // 1000000 / 50Hz
+#define IMUSE_TIMER_GAIN_RED_RATE_USEC 200000 // 1000000 / 5Hz
+#define IMUSE_TIMER_FADES_RATE_USEC    20000  // 1000000 / 50Hz
+
+// Parameters IDs
+#define IMUSE_P_BOGUS_ID       0x0
+#define IMUSE_P_SND_TRACK_NUM  0x100
+#define IMUSE_P_TRIGS_SNDS     0x200
+#define IMUSE_P_MARKER         0x300
+#define IMUSE_P_GROUP          0x400
+#define IMUSE_P_PRIORITY       0x500
+#define IMUSE_P_VOLUME         0x600
+#define IMUSE_P_PAN            0x700
+#define IMUSE_P_DETUNE         0x800
+#define IMUSE_P_TRANSPOSE      0x900
+#define IMUSE_P_MAILBOX        0xA00
+#define IMUSE_P_UNKNOWN        0xF00
+#define IMUSE_P_SND_HAS_STREAM 0x1800
+#define IMUSE_P_STREAM_BUFID   0x1900
+#define IMUSE_P_SND_POS_IN_MS  0x1A00
+
+// Soundkludge command IDs
+#define IMUSE_C_KLUDGE_SET_STATE        0x1000
+#define IMUSE_C_KLUDGE_SET_SEQUENCE     0x1001
+#define IMUSE_C_KLUDGE_SET_CUE_POINT    0x1002
+#define IMUSE_C_KLUDGE_SET_ATTRIBUTE    0x1003
+#define IMUSE_C_KLUDGE_SET_SFX_VOLUME   0x2000
+#define IMUSE_C_KLUDGE_SET_VOICE_VOLUME 0x2001
+#define IMUSE_C_KLUDGE_SET_MUSIC_VOLUME 0x2002
+#define IMUSE_C_KLUDGE_STOP_ALL_SNDS    10
+#define IMUSE_C_KLUDGE_SET_PARAM        12
+#define IMUSE_C_KLUDGE_FADE_PARAM       14
+#define IMUSE_C_KLUDGE_START_STREAM     25
+#define IMUSE_C_KLUDGE_SWITCH_STREAM    26
+
+// Script command IDs
+#define IMUSE_C_SCRIPT_INIT          0
+#define IMUSE_C_SCRIPT_TERMINATE     1
+#define IMUSE_C_SCRIPT_SAVE          2
+#define IMUSE_C_SCRIPT_RESTORE       3
+#define IMUSE_C_SCRIPT_REFRESH       4
+#define IMUSE_C_SCRIPT_SET_STATE     5
+#define IMUSE_C_SCRIPT_SET_SEQUENCE  6
+#define IMUSE_C_SCRIPT_CUE_POINT     7
+#define IMUSE_C_SCRIPT_SET_ATTRIBUTE 8
+
+// Internal command IDs
+#define IMUSE_C_INIT             0
+#define IMUSE_C_TERMINATE        1
+#define IMUSE_C_PAUSE            3
+#define IMUSE_C_RESUME           4
+#define IMUSE_C_SET_GRP_VOL      7
+#define IMUSE_C_START_SND        8
+#define IMUSE_C_STOP_SND         9
+#define IMUSE_C_STOP_ALL_SNDS    10
+#define IMUSE_C_GET_NEXT_SND     11
+#define IMUSE_C_SET_PARAM        12
+#define IMUSE_C_GET_PARAM        13
+#define IMUSE_C_FADE_PARAM       14
+#define IMUSE_C_SET_HOOK         15
+#define IMUSE_C_GET_HOOK         16
+#define IMUSE_C_SET_TRIGGER      17
+#define IMUSE_C_CHECK_TRIGGER    18
+#define IMUSE_C_CLEAR_TRIGGER    19
+#define IMUSE_C_DEFER_CMD        20
+#define IMUSE_C_START_STREAM     25
+#define IMUSE_C_SWITCH_STREAM    26
+#define IMUSE_C_PROCESS_STREAMS  27
+#define IMUSE_C_FEED_STREAM      29
+
+// Trigger callback command ID
+#define IMUSE_C_SCRIPT_CALLBACK  0
+
+class IMuse;
+
+struct IMuseDispatch;
+struct IMuseTrack;
+struct IMuseStreamZone;
+
+typedef struct {
+	int sound;
+	char text[256];
+	int opcode;
+	int a;
+	int b;
+	int c;
+	int d;
+	int e;
+	int f;
+	int g;
+	int h;
+	int i;
+	int j;
+	int clearLater;
+} IMuseTrigger;
+
+typedef struct {
+	int counter;
+	int opcode;
+	int a;
+	int b;
+	int c;
+	int d;
+	int e;
+	int f;
+	int g;
+	int h;
+	int i;
+	int j;
+} IMuseDefer;
+
+typedef struct {
+	int status;
+	int sound;
+	int param;
+	int currentVal;
+	int counter;
+	int length;
+	int slope;
+	int slopeMod;
+	int modOvfloCounter;
+	int nudge;
+} IMuseFade;
+
+struct IMuseTrack {
+	int index;
+	IMuseTrack *prev;
+	IMuseTrack *next;
+	IMuseDispatch *dispatchPtr;
+	int soundId;
+	int marker;
+	int group;
+	int priority;
+	int vol;
+	int effVol;
+	int pan;
+	int detune;
+	int transpose;
+	int pitchShift;
+	int mailbox;
+	int jumpHook;
+};
+
+struct IMuseStreamZone {
+	IMuseStreamZone *prev;
+	IMuseStreamZone *next;
+	int useFlag;
+	int32 offset;
+	int32 size;
+	int fadeFlag;
+};
+
+typedef struct {
+	int soundId;
+	int32 curOffset;
+	int32 endOffset;
+	int bufId;
+	uint8 *buf;
+	int32 bufFreeSize;
+	int32 loadSize;
+	int32 criticalSize;
+	int32 maxRead;
+	int32 loadIndex;
+	int32 readIndex;
+	int paused;
+} IMuseStream;
+
+typedef struct {
+	uint8 *buffer;
+	int32 bufSize;
+	int32 loadSize;
+	int32 criticalSize;
+} IMuseSndBuffer;
+
+struct IMuseSoundList {
+	IMuseSoundList *prev;
+	IMuseSoundList *next;
+	int soundId;
+	char filename[36];
+	int refCount;
+};
+
+struct IMuseResource {
+	Common::SeekableReadStream *resId;
+	bool hasMcmp;
+	int32 resSize;
+	int32 fileCurOffset;
+	int32 compBlocksNum;
+	uint8 *mcmpBlockPtr;
+	uint8 **compBlockPtr;
+	int32 *decompBlockSize;
+	int32 *compBlockOffset;
+	int32 *compBlockSize;
+	int32 *vimaOffsets;
+	int32 curProcessedCompBlock;
+	int32 curDecompBlockSize;
+	uint8 *decompDataBuffer;
+	char filename[80];
+};
+
+struct IMuseCachedSound {
+	char soundFilename[32];
+	int luaSoundId;
+	uint32 tsOfAllocation;
+	uint8 *soundUncompData;
+	uint8 *soundAddrData;
+	uint8 *soundMap;
+	int uncompResourceSize;
+	int flag;
+	int priority;
+};
+
+struct IMuseOpenAudioFile {
+	IMuseResource *resourcePtr;
+	char soundName[32];
+	int refCount;
+};
+
+struct IMuseDispatch {
+	IMuseTrack *trackPtr;
+	int wordSize;
+	int sampleRate;
+	int channelCount;
+	int swapEndiannessFlag;
+	int32 currentOffset;
+	int32 audioRemaining;
+	int32 map[IMUSE_MAX_MAP_SIZE];
+	IMuseStream *streamPtr;
+	int streamBufID;
+	IMuseStreamZone *streamZoneList;
+	int streamErrFlag;
+	uint8 *fadeBuf;
+	int32 fadeOffset;
+	int32 fadeRemaining;
+	int fadeWordSize;
+	int fadeSampleRate;
+	int fadeChannelCount;
+	int fadeSyncFlag;
+	int32 fadeSyncDelta;
+	int fadeVol;
+	int fadeSlope;
+};
+
+typedef struct {
+	int bytesPerSample;
+	int numChannels;
+	uint8 *mixBuf;
+	int mixBufSize;
+	int sizeSampleKB;
+} waveOutParamsStruct;
+
+} // End of namespace Grim
+#endif
diff --git a/engines/grim/imuse/dimuse_dispatch.cpp b/engines/grim/imuse/imuse_dispatch.cpp
similarity index 79%
rename from engines/grim/imuse/dimuse_dispatch.cpp
rename to engines/grim/imuse/imuse_dispatch.cpp
index bf439fe69bf..b90bb0221d5 100644
--- a/engines/grim/imuse/dimuse_dispatch.cpp
+++ b/engines/grim/imuse/imuse_dispatch.cpp
@@ -19,27 +19,27 @@
  *
  */
 
-#include "engines/grim/imuse/dimuse_engine.h"
-#include "engines/grim/imuse/dimuse_defs.h"
+#include "engines/grim/imuse/imuse_engine.h"
+#include "engines/grim/imuse/imuse_defs.h"
 
 namespace Grim {
 
-int IMuseDigital::dispatchInit() {
-	_dispatchBuffer = (uint8 *)malloc(DIMUSE_SMALL_FADES * DIMUSE_SMALL_FADE_DIM + DIMUSE_LARGE_FADE_DIM * DIMUSE_LARGE_FADES);
+int IMuse::dispatchInit() {
+	_dispatchBuffer = (uint8 *)malloc(IMUSE_SMALL_FADES * IMUSE_SMALL_FADE_DIM + IMUSE_LARGE_FADE_DIM * IMUSE_LARGE_FADES);
 
 	if (_dispatchBuffer) {
 		_dispatchLargeFadeBufs = _dispatchBuffer;
-		_dispatchSmallFadeBufs = _dispatchBuffer + (DIMUSE_LARGE_FADE_DIM * DIMUSE_LARGE_FADES);
+		_dispatchSmallFadeBufs = _dispatchBuffer + (IMUSE_LARGE_FADE_DIM * IMUSE_LARGE_FADES);
 
-		for (int i = 0; i < DIMUSE_LARGE_FADES; i++) {
+		for (int i = 0; i < IMUSE_LARGE_FADES; i++) {
 			_dispatchLargeFadeFlags[i] = 0;
 		}
 
-		for (int i = 0; i < DIMUSE_SMALL_FADES; i++) {
+		for (int i = 0; i < IMUSE_SMALL_FADES; i++) {
 			_dispatchSmallFadeFlags[i] = 0;
 		}
 
-		for (int i = 0; i < DIMUSE_MAX_STREAMZONES; i++) {
+		for (int i = 0; i < IMUSE_MAX_STREAMZONES; i++) {
 			_streamZones[i].useFlag = 0;
 			_streamZones[i].fadeFlag = 0;
 			_streamZones[i].prev = nullptr;
@@ -48,7 +48,7 @@ int IMuseDigital::dispatchInit() {
 			_streamZones[i].offset = 0;
 		}
 
-		for (int i = 0; i < DIMUSE_MAX_DISPATCHES; i++) {
+		for (int i = 0; i < IMUSE_MAX_DISPATCHES; i++) {
 			_dispatches[i].trackPtr = nullptr;
 			_dispatches[i].wordSize = 0;
 			_dispatches[i].sampleRate = 0;
@@ -74,33 +74,33 @@ int IMuseDigital::dispatchInit() {
 		}
 
 	} else {
-		debug(5, "IMuseDigital::dispatchInit(): ERROR: couldn't allocate buffers\n");
+		debug(5, "IMuse::dispatchInit(): ERROR: couldn't allocate buffers\n");
 		return -1;
 	}
 
 	return 0;
 }
 
-int IMuseDigital::dispatchTerminate() {
+int IMuse::dispatchTerminate() {
 	free(_dispatchBuffer);
 	_dispatchBuffer = nullptr;
 	return 0;
 }
 
-IMuseDigiDispatch *IMuseDigital::dispatchGetDispatchByTrackId(int trackId) {
+IMuseDispatch *IMuse::dispatchGetDispatchByTrackId(int trackId) {
 	return &_dispatches[trackId];
 }
 
-void IMuseDigital::dispatchSaveLoad(Common::Serializer &ser) {
+void IMuse::dispatchSaveLoad(Common::Serializer &ser) {
 
-	for (int l = 0; l < DIMUSE_MAX_DISPATCHES; l++) {
+	for (int l = 0; l < IMUSE_MAX_DISPATCHES; l++) {
 		ser.syncAsSint32LE(_dispatches[l].wordSize, VER(30));
 		ser.syncAsSint32LE(_dispatches[l].sampleRate, VER(30));
 		ser.syncAsSint32LE(_dispatches[l].channelCount, VER(30));
 		ser.syncAsSint32LE(_dispatches[l].swapEndiannessFlag, VER(30));
 		ser.syncAsSint32LE(_dispatches[l].currentOffset, VER(30));
 		ser.syncAsSint32LE(_dispatches[l].audioRemaining, VER(30));
-		ser.syncArray(_dispatches[l].map, DIMUSE_MAX_MAP_SIZE, Common::Serializer::Sint32LE, VER(30));
+		ser.syncArray(_dispatches[l].map, IMUSE_MAX_MAP_SIZE, Common::Serializer::Sint32LE, VER(30));
 
 		// This is only needed to signal if the sound originally had a stream associated with it
 		int hasStream = 0;
@@ -110,7 +110,7 @@ void IMuseDigital::dispatchSaveLoad(Common::Serializer &ser) {
 			ser.syncAsSint32LE(hasStream, VER(30));
 		} else {
 			ser.syncAsSint32LE(hasStream, VER(30));
-			_dispatches[l].streamPtr = hasStream ? (IMuseDigiStream *)1 : nullptr;
+			_dispatches[l].streamPtr = hasStream ? (IMuseStream *)1 : nullptr;
 		}
 
 		ser.syncAsSint32LE(_dispatches[l].streamBufID, VER(30));
@@ -127,23 +127,23 @@ void IMuseDigital::dispatchSaveLoad(Common::Serializer &ser) {
 	}
 
 	if (ser.isLoading()) {
-		for (int i = 0; i < DIMUSE_LARGE_FADES; i++) {
+		for (int i = 0; i < IMUSE_LARGE_FADES; i++) {
 			_dispatchLargeFadeFlags[i] = 0;
 		}
 
-		for (int i = 0; i < DIMUSE_SMALL_FADES; i++) {
+		for (int i = 0; i < IMUSE_SMALL_FADES; i++) {
 			_dispatchSmallFadeFlags[i] = 0;
 		}
 
-		for (int i = 0; i < DIMUSE_MAX_STREAMZONES; i++) {
+		for (int i = 0; i < IMUSE_MAX_STREAMZONES; i++) {
 			_streamZones[i].useFlag = 0;
 		}
 	}
 }
 
-int IMuseDigital::dispatchRestoreStreamZones() {
-	IMuseDigiDispatch *curDispatchPtr;
-	IMuseDigiStreamZone *curStreamZone;
+int IMuse::dispatchRestoreStreamZones() {
+	IMuseDispatch *curDispatchPtr;
+	IMuseStreamZone *curStreamZone;
 	int32 sizeToFeed = 0x4000;
 
 	curDispatchPtr = _dispatches;
@@ -168,19 +168,19 @@ int IMuseDigital::dispatchRestoreStreamZones() {
 						curStreamZone->size = 0;
 						curStreamZone->fadeFlag = 0;
 					} else {
-						debug(5, "IMuseDigital::dispatchRestoreStreamZones(): unable to allocate streamZone during restore");
+						debug(5, "IMuse::dispatchRestoreStreamZones(): unable to allocate streamZone during restore");
 					}
 				}
 			} else {
-				debug(5, "IMuseDigital::dispatchRestoreStreamZones(): unable to start stream during restore");
+				debug(5, "IMuse::dispatchRestoreStreamZones(): unable to start stream during restore");
 			}
 		}
 	}
 	return 0;
 }
 
-int IMuseDigital::dispatchAllocateSound(IMuseDigiTrack *trackPtr, int groupId) {
-	IMuseDigiDispatch *trackDispatch;
+int IMuse::dispatchAllocateSound(IMuseTrack *trackPtr, int groupId) {
+	IMuseDispatch *trackDispatch;
 	int navigateMapResult;
 	int32 sizeToFeed = 0x4000;
 
@@ -196,7 +196,7 @@ int IMuseDigital::dispatchAllocateSound(IMuseDigiTrack *trackPtr, int groupId) {
 		trackDispatch->streamBufID = groupId;
 
 		if (!trackDispatch->streamPtr) {
-			debug(5, "IMuseDigital::dispatchAllocateSound(): unable to allocate stream for sound %d", trackPtr->soundId);
+			debug(5, "IMuse::dispatchAllocateSound(): unable to allocate stream for sound %d", trackPtr->soundId);
 			return -1;
 		}
 
@@ -209,7 +209,7 @@ int IMuseDigital::dispatchAllocateSound(IMuseDigiTrack *trackPtr, int groupId) {
 	navigateMapResult = dispatchNavigateMap(trackDispatch);
 	if (navigateMapResult && navigateMapResult != -3) {
 		// At this point, something went wrong, so let's release the dispatch
-		debug(5, "IMuseDigital::dispatchAllocateSound(): problem starting sound (%d) in dispatch", trackPtr->soundId);
+		debug(5, "IMuse::dispatchAllocateSound(): problem starting sound (%d) in dispatch", trackPtr->soundId);
 		dispatchRelease(trackPtr);
 		return -1;
 	}
@@ -217,9 +217,9 @@ int IMuseDigital::dispatchAllocateSound(IMuseDigiTrack *trackPtr, int groupId) {
 	return 0;
 }
 
-int IMuseDigital::dispatchRelease(IMuseDigiTrack *trackPtr) {
-	IMuseDigiDispatch *dispatchToDeallocate;
-	IMuseDigiStreamZone *streamZoneList;
+int IMuse::dispatchRelease(IMuseTrack *trackPtr) {
+	IMuseDispatch *dispatchToDeallocate;
+	IMuseStreamZone *streamZoneList;
 
 	dispatchToDeallocate = trackPtr->dispatchPtr;
 
@@ -244,10 +244,10 @@ int IMuseDigital::dispatchRelease(IMuseDigiTrack *trackPtr) {
 	return 0;
 }
 
-int IMuseDigital::dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeLength, int exitTriggerSyncFlag, int offsetFadeSyncFlag) {
+int IMuse::dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeLength, int exitTriggerSyncFlag, int offsetFadeSyncFlag) {
 	int32 effFadeLen, effFadeSize, strZnSize;
 	int getMapResult, i;
-	IMuseDigiDispatch *curDispatch = _dispatches;
+	IMuseDispatch *curDispatch = _dispatches;
 
 	effFadeLen = fadeLength;
 
@@ -262,13 +262,13 @@ int IMuseDigital::dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeL
 	}
 
 	if (i >= _trackCount) {
-		debug(5, "IMuseDigital::dispatchSwitchStream(): couldn't find sound, index went past _trackCount (%d)", _trackCount);
+		debug(5, "IMuse::dispatchSwitchStream(): couldn't find sound, index went past _trackCount (%d)", _trackCount);
 		return -1;
 	}
 
 	if (curDispatch->streamZoneList) {
 		if (!curDispatch->wordSize) {
-			debug(5, "IMuseDigital::dispatchSwitchStream(): found streamZoneList but NULL wordSize");
+			debug(5, "IMuse::dispatchSwitchStream(): found streamZoneList but NULL wordSize");
 			return -1;
 		}
 
@@ -301,7 +301,7 @@ int IMuseDigital::dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeL
 			curDispatch->fadeChannelCount = curDispatch->channelCount;
 			curDispatch->fadeSyncFlag = exitTriggerSyncFlag | offsetFadeSyncFlag;
 			curDispatch->fadeSyncDelta = 0;
-			curDispatch->fadeVol = DIMUSE_MAX_FADE_VOLUME;
+			curDispatch->fadeVol = IMUSE_MAX_FADE_VOLUME;
 			curDispatch->fadeSlope = 0;
 
 			while (curDispatch->fadeRemaining < _dispatchFadeSize) {
@@ -321,7 +321,7 @@ int IMuseDigital::dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeL
 				curDispatch->fadeRemaining += effFadeSize;
 			}
 		} else {
-			debug(5, "IMuseDigital::dispatchSwitchStream(): WARNING: couldn't allocate fade buffer (from sound %d to sound %d)", oldSoundId, newSoundId);
+			debug(5, "IMuse::dispatchSwitchStream(): WARNING: couldn't allocate fade buffer (from sound %d to sound %d)", oldSoundId, newSoundId);
 		}
 	}
 
@@ -361,15 +361,15 @@ int IMuseDigital::dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeL
 		if (!getMapResult || getMapResult == -3) {
 			return 0;
 		} else {
-			debug(5, "IMuseDigital::dispatchSwitchStream(): problem switching stream in dispatch (from sound %d to sound %d)", oldSoundId, newSoundId);
+			debug(5, "IMuse::dispatchSwitchStream(): problem switching stream in dispatch (from sound %d to sound %d)", oldSoundId, newSoundId);
 			tracksClear(curDispatch->trackPtr);
 			return -1;
 		}
 	}
 }
 
-void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedSize, int sampleRate) {
-	IMuseDigiDispatch *dispatchPtr;
+void IMuse::dispatchProcessDispatches(IMuseTrack *trackPtr, int feedSize, int sampleRate) {
+	IMuseDispatch *dispatchPtr;
 	int32 effFeedSize, effWordSize, effRemainingAudio, effRemainingFade, effSampleRate;
 	int32 inFrameCount, mixVolume, mixStartingPoint, elapsedFadeDelta;
 	int navigateMapResult;
@@ -421,7 +421,7 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 				dispatchPtr->fadeBuf = nullptr;
 			}
 		} else {
-			debug(5, "IMuseDigital::dispatchProcessDispatches(): WARNING: fade for sound %d ends with incomplete frame", trackPtr->soundId);
+			debug(5, "IMuse::dispatchProcessDispatches(): WARNING: fade for sound %d ends with incomplete frame", trackPtr->soundId);
 
 			// Fade ended, deallocate it
 			dispatchDeallocateFade(dispatchPtr, "dispatchProcessDispatches");
@@ -531,7 +531,7 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 		} else {
 			soundAddrData = filesGetSoundAddrData(trackPtr->soundId);
 			if (!soundAddrData) {
-				debug(5, "IMuseDigital::dispatchProcessDispatches(): ERROR: soundAddrData for sound %d is NULL", trackPtr->soundId);
+				debug(5, "IMuse::dispatchProcessDispatches(): ERROR: soundAddrData for sound %d is NULL", trackPtr->soundId);
 				return;
 			}
 
@@ -593,7 +593,7 @@ void IMuseDigital::dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedS
 		dispatchPtr->fadeSyncDelta += feedSize;
 }
 
-void IMuseDigital::dispatchPredictFirstStream() {
+void IMuse::dispatchPredictFirstStream() {
 	Common::StackLock lock(*_mutex);
 
 	for (int i = 0; i < _trackCount; i++) {
@@ -602,7 +602,7 @@ void IMuseDigital::dispatchPredictFirstStream() {
 	}
 }
 
-int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
+int IMuse::dispatchNavigateMap(IMuseDispatch *dispatchPtr) {
 	uint8 *mapCurEvent;
 	int32 blockTag, effFadeSize, elapsedFadeSize, soundId;
 	char *marker = NULL;
@@ -613,7 +613,7 @@ int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
 
 	if (dispatchPtr->audioRemaining
 		|| (dispatchPtr->streamPtr && dispatchPtr->streamZoneList->offset != dispatchPtr->currentOffset)) {
-		debug(5, "IMuseDigital::dispatchNavigateMap(): ERROR: navigation error in dispatch");
+		debug(5, "IMuse::dispatchNavigateMap(): ERROR: navigation error in dispatch");
 		return -1;
 	}
 
@@ -622,7 +622,7 @@ int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
 		mapCurEvent = dispatchGetNextMapEvent(dispatchPtr->map, dispatchPtr->currentOffset, mapCurEvent);
 
 		if (!mapCurEvent) {
-			debug(5, "IMuseDigital::dispatchNavigateMap(): ERROR: no more map events at offset %dx", dispatchPtr->currentOffset);
+			debug(5, "IMuse::dispatchNavigateMap(): ERROR: no more map events at offset %dx", dispatchPtr->currentOffset);
 			return -1;
 		}
 
@@ -642,11 +642,11 @@ int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
 				dispatchPtr->currentOffset = READ_UINT32(mapCurEvent + 12);
 				if (dispatchPtr->streamPtr) {
 					if (dispatchPtr->streamZoneList->size || !dispatchPtr->streamZoneList->next) {
-						debug(5, "IMuseDigital::dispatchNavigateMap(): next streamZone is unallocated, calling dispatchPrepareToJump()");
+						debug(5, "IMuse::dispatchNavigateMap(): next streamZone is unallocated, calling dispatchPrepareToJump()");
 						dispatchPrepareToJump(dispatchPtr, dispatchPtr->streamZoneList, mapCurEvent, 1);
 					}
 
-					debug(5, "IMuseDigital::dispatchNavigateMap(): \n"
+					debug(5, "IMuse::dispatchNavigateMap(): \n"
 							 "\tJUMP found for sound %d with valid candidateHookId (%d), \n"
 							 "\tgoing to offset %d with a crossfade of %d ms",
 						  dispatchPtr->trackPtr->soundId, (int)READ_UINT32(mapCurEvent + 16),
@@ -674,7 +674,7 @@ int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
 							dispatchPtr->fadeRemaining = 0;
 							dispatchPtr->fadeSyncFlag = 0;
 							dispatchPtr->fadeSyncDelta = 0;
-							dispatchPtr->fadeVol = DIMUSE_MAX_FADE_VOLUME;
+							dispatchPtr->fadeVol = IMUSE_MAX_FADE_VOLUME;
 							dispatchPtr->fadeSlope = 0;
 
 							// Clone the old sound in the fade buffer for just the duration of the fade
@@ -747,14 +747,14 @@ int IMuseDigital::dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr) {
 		case MKTAG('S', 'T', 'O', 'P'):
 			return -1;
 		default:
-			debug(5, "IMuseDigital::dispatchNavigateMap(): ERROR: Unrecognized map event at offset %dx", dispatchPtr->currentOffset);
+			debug(5, "IMuse::dispatchNavigateMap(): ERROR: Unrecognized map event at offset %dx", dispatchPtr->currentOffset);
 			return -1;
 		};
 	}
 	return -1;
 }
 
-int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
+int IMuse::dispatchGetMap(IMuseDispatch *dispatchPtr) {
 	int32 *dstMap;
 	uint8 *rawMap, *copiedBuf, *soundAddrData, *extFrmtBufPtr;
 	uint8 bufferHeader[80];
@@ -767,7 +767,7 @@ int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
 	// If there's no map, try to fetch it
 	if (dispatchPtr->map[0] != MKTAG('M', 'A', 'P', ' ') || (dispatchPtr->streamPtr && !dispatchPtr->streamZoneList)) {
 		if (dispatchPtr->currentOffset) {
-			debug(5, "IMuseDigital::dispatchNavigateMap(): found offset but no map");
+			debug(5, "IMuse::dispatchNavigateMap(): found offset but no map");
 			return -1;
 		}
 
@@ -784,7 +784,7 @@ int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
 				// A WAV file: build an iMUS map for it on the fly
 				extFrmtBufPtr = soundsGetExtFormatBuffer(copiedBuf, nullptr, &targetSampleRate, nullptr, &targetNumChannels, nullptr, &curChunkPos);
 				if (!extFrmtBufPtr) {
-					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: couldn't find the data chunk of the WAV file");
+					debug(5, "IMuse::dispatchGetMap(): ERROR: couldn't find the data chunk of the WAV file");
 					return -1;
 				}
 
@@ -803,18 +803,18 @@ int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
 				}
 				rawMap = (uint8 *)streamerGetStreamBuffer(dispatchPtr->streamPtr, size);
 				if (!rawMap) {
-					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: stream read failed after view succeeded");
+					debug(5, "IMuse::dispatchGetMap(): ERROR: stream read failed after view succeeded");
 					return -1;
 				}
 
 				dispatchPtr->currentOffset = size;
 			} else {
-				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: unrecognized file format in stream buffer");
+				debug(5, "IMuse::dispatchGetMap(): ERROR: unrecognized file format in stream buffer");
 				return -1;
 			}
 
 			if (dispatchConvertMap(rawMap + 8, dstMap)) {
-				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: dispatchConvertMap() failed");
+				debug(5, "IMuse::dispatchGetMap(): ERROR: dispatchConvertMap() failed");
 				return -1;
 			}
 
@@ -825,22 +825,22 @@ int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
 			}
 
 			if (dispatchPtr->map[2] != MKTAG('F', 'R', 'M', 'T')) {
-				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected 'FRMT' at start of map");
+				debug(5, "IMuse::dispatchGetMap(): ERROR: expected 'FRMT' at start of map");
 				return -1;
 			}
 
 			if (dispatchPtr->map[4] != dispatchPtr->currentOffset) {
-				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected data to follow map");
+				debug(5, "IMuse::dispatchGetMap(): ERROR: expected data to follow map");
 				return -1;
 			} else {
 				if (dispatchPtr->streamZoneList) {
-					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected NULL streamZoneList");
+					debug(5, "IMuse::dispatchGetMap(): ERROR: expected NULL streamZoneList");
 					return -1;
 				}
 
 				dispatchPtr->streamZoneList = dispatchAllocateStreamZone();
 				if (!dispatchPtr->streamZoneList) {
-					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: couldn't allocate zone");
+					debug(5, "IMuse::dispatchGetMap(): ERROR: couldn't allocate zone");
 					return -1;
 				}
 
@@ -854,28 +854,28 @@ int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
 			soundAddrData = filesFetchMap(dispatchPtr->trackPtr->soundId);
 
 			if (!soundAddrData) {
-				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: couldn't get sound address");
+				debug(5, "IMuse::dispatchGetMap(): ERROR: couldn't get sound address");
 				return -1;
 			}
 
 			if (READ_BE_UINT32(soundAddrData) == MKTAG('i', 'M', 'U', 'S') && READ_BE_UINT32(soundAddrData + 8) == MKTAG('M', 'A', 'P', ' ')) {
 				dispatchPtr->currentOffset = READ_BE_UINT32(soundAddrData + 12) + 24;
 				if (dispatchConvertMap((soundAddrData + 8), dstMap)) {
-					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: dispatchConvertMap() failure");
+					debug(5, "IMuse::dispatchGetMap(): ERROR: dispatchConvertMap() failure");
 					return -1;
 				}
 
 				if (dispatchPtr->map[2] != MKTAG('F', 'R', 'M', 'T')) {
-					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected 'FRMT' at start of map");
+					debug(5, "IMuse::dispatchGetMap(): ERROR: expected 'FRMT' at start of map");
 					return -1;
 				}
 
 				if (dispatchPtr->map[4] != dispatchPtr->currentOffset) {
-					debug(5, "IMuseDigital::dispatchGetMap(): ERROR: expected data to follow map");
+					debug(5, "IMuse::dispatchGetMap(): ERROR: expected data to follow map");
 					return -1;
 				}
 			} else {
-				debug(5, "IMuseDigital::dispatchGetMap(): ERROR: unrecognized file format in stream buffer");
+				debug(5, "IMuse::dispatchGetMap(): ERROR: unrecognized file format in stream buffer");
 				return -1;
 			}
 		}
@@ -884,7 +884,7 @@ int IMuseDigital::dispatchGetMap(IMuseDigiDispatch *dispatchPtr) {
 	return 0;
 }
 
-int IMuseDigital::dispatchConvertMap(uint8 *rawMap, int32 *destMap) {
+int IMuse::dispatchConvertMap(uint8 *rawMap, int32 *destMap) {
 	int32 effMapSize;
 	uint8 *mapCurPos;
 	int32 blockName;
@@ -959,33 +959,33 @@ int IMuseDigital::dispatchConvertMap(uint8 *rawMap, int32 *destMap) {
 			if ((uint8 *)destMap + bytesUntilEndOfMap - mapCurPos == -8) {
 				return 0;
 			} else {
-				debug(5, "IMuseDigital::dispatchConvertMap(): ERROR: converted wrong number of bytes");
+				debug(5, "IMuse::dispatchConvertMap(): ERROR: converted wrong number of bytes");
 				return -1;
 			}
 		} else {
-			debug(5, "IMuseDigital::dispatchConvertMap(): ERROR: map is too big (%d)", effMapSize);
+			debug(5, "IMuse::dispatchConvertMap(): ERROR: map is too big (%d)", effMapSize);
 			return -1;
 		}
 	} else {
-		debug(5, "IMuseDigital::dispatchConvertMap(): ERROR: got bogus map");
+		debug(5, "IMuse::dispatchConvertMap(): ERROR: got bogus map");
 		return -1;
 	}
 
 	return 0;
 }
 
-uint8 *IMuseDigital::dispatchGetNextMapEvent(int32 *mapPtr, int32 soundOffset, uint8 *mapEvent) {
+uint8 *IMuse::dispatchGetNextMapEvent(int32 *mapPtr, int32 soundOffset, uint8 *mapEvent) {
 	if (mapEvent) {
 		// Advance the map to the next block (READ_UINT32(mapEvent + 4) + 8 is the size of the block)
 		mapEvent = mapEvent + READ_UINT32(mapEvent + 4) + 8;
 
 		if ((uint8 *)&mapPtr[2] + mapPtr[1] > mapEvent) {
 			if ((int32)READ_UINT32(mapEvent + 8) != soundOffset) {
-				debug(5, "IMuseDigital::dispatchGetNextMapEvent(): ERROR: no more events at offset %d", soundOffset);
+				debug(5, "IMuse::dispatchGetNextMapEvent(): ERROR: no more events at offset %d", soundOffset);
 				return nullptr;
 			}
 		} else {
-			debug(5, "IMuseDigital::dispatchGetNextMapEvent(): ERROR: map overrun");
+			debug(5, "IMuse::dispatchGetNextMapEvent(): ERROR: map overrun");
 			return nullptr;
 		}
 
@@ -1001,7 +1001,7 @@ uint8 *IMuseDigital::dispatchGetNextMapEvent(int32 *mapPtr, int32 soundOffset, u
 			mapEvent = mapEvent + READ_UINT32(mapEvent + 4) + 8;
 
 			if ((uint8 *)&mapPtr[2] + mapPtr[1] <= mapEvent) {
-				debug(5, "IMuseDigital::dispatchGetNextMapEvent(): ERROR: couldn't find event at offset %d", soundOffset);
+				debug(5, "IMuse::dispatchGetNextMapEvent(): ERROR: couldn't find event at offset %d", soundOffset);
 				return nullptr;
 			}
 		}
@@ -1010,13 +1010,13 @@ uint8 *IMuseDigital::dispatchGetNextMapEvent(int32 *mapPtr, int32 soundOffset, u
 	return mapEvent;
 }
 
-void IMuseDigital::dispatchPredictStream(IMuseDigiDispatch *dispatchPtr) {
-	IMuseDigiStreamZone *szTmp, *lastStreamInList, *curStrZn;
+void IMuse::dispatchPredictStream(IMuseDispatch *dispatchPtr) {
+	IMuseStreamZone *szTmp, *lastStreamInList, *curStrZn;
 	int32 cumulativeStreamOffset;
 	uint8 *jumpParameters;
 
 	if (!dispatchPtr->streamPtr || !dispatchPtr->streamZoneList) {
-		debug(5, "IMuseDigital::dispatchPredictStream(): ERROR: NULL streamId or streamZoneList");
+		debug(5, "IMuse::dispatchPredictStream(): ERROR: NULL streamId or streamZoneList");
 		return;
 	}
 
@@ -1047,7 +1047,7 @@ void IMuseDigital::dispatchPredictStream(IMuseDigiDispatch *dispatchPtr) {
 	}
 }
 
-uint8 *IMuseDigital::dispatchCheckForJump(int32 *mapPtr, IMuseDigiStreamZone *strZnPtr, int &candidateHookId) {
+uint8 *IMuse::dispatchCheckForJump(int32 *mapPtr, IMuseStreamZone *strZnPtr, int &candidateHookId) {
 	uint8 *curMapPlace = (uint8 *)&mapPtr[2];
 	uint8 *endOfMap = (uint8 *)&mapPtr[2] + mapPtr[1];
 	int32 mapPlaceTag, jumpHookPos, jumpHookId, bytesUntilNextPlace;
@@ -1072,13 +1072,13 @@ uint8 *IMuseDigital::dispatchCheckForJump(int32 *mapPtr, IMuseDigiStreamZone *st
 	return nullptr;
 }
 
-void IMuseDigital::dispatchPrepareToJump(IMuseDigiDispatch *dispatchPtr, IMuseDigiStreamZone *strZnPtr, uint8 *jumpParams, int calledFromNavigateMap) {
+void IMuse::dispatchPrepareToJump(IMuseDispatch *dispatchPtr, IMuseStreamZone *strZnPtr, uint8 *jumpParams, int calledFromNavigateMap) {
 	int32 hookPosition, jumpDestination, fadeTime;
-	IMuseDigiStreamZone *nextStreamZone;
-	IMuseDigiStreamZone *zoneForJump = nullptr;
-	IMuseDigiStreamZone *zoneAfterJump;
+	IMuseStreamZone *nextStreamZone;
+	IMuseStreamZone *zoneForJump = nullptr;
+	IMuseStreamZone *zoneAfterJump;
 	uint32 streamOffset;
-	IMuseDigiStreamZone *zoneCycle;
+	IMuseStreamZone *zoneCycle;
 
 	// jumpParams format (assuming jumpParams is int32*):
 	// jumpParams[0]: four bytes which form the string 'JUMP'
@@ -1141,14 +1141,14 @@ void IMuseDigital::dispatchPrepareToJump(IMuseDigiDispatch *dispatchPtr, IMuseDi
 	if (_dispatchSize) {
 		zoneForJump = dispatchAllocateStreamZone();
 		if (!zoneForJump) {
-			debug(5, "IMuseDigital::dispatchPrepareToJump(): ERROR: couldn't allocate streamZone");
+			debug(5, "IMuse::dispatchPrepareToJump(): ERROR: couldn't allocate streamZone");
 			return;
 		}
 	}
 
 	zoneAfterJump = dispatchAllocateStreamZone();
 	if (!zoneAfterJump) {
-		debug(5, "IMuseDigital::dispatchPrepareToJump(): ERROR: couldn't allocate streamZone");
+		debug(5, "IMuse::dispatchPrepareToJump(): ERROR: couldn't allocate streamZone");
 		return;
 	}
 
@@ -1193,9 +1193,9 @@ void IMuseDigital::dispatchPrepareToJump(IMuseDigiDispatch *dispatchPtr, IMuseDi
 	zoneAfterJump->fadeFlag = 0;
 }
 
-void IMuseDigital::dispatchStreamNextZone(IMuseDigiDispatch *dispatchPtr, IMuseDigiStreamZone *strZnPtr) {
+void IMuse::dispatchStreamNextZone(IMuseDispatch *dispatchPtr, IMuseStreamZone *strZnPtr) {
 	int32 cumulativeStreamOffset;
-	IMuseDigiStreamZone *szTmp;
+	IMuseStreamZone *szTmp;
 
 	if (strZnPtr->next) {
 		cumulativeStreamOffset = strZnPtr->size;
@@ -1221,8 +1221,8 @@ void IMuseDigital::dispatchStreamNextZone(IMuseDigiDispatch *dispatchPtr, IMuseD
 	}
 }
 
-IMuseDigiStreamZone *IMuseDigital::dispatchAllocateStreamZone() {
-	for (int i = 0; i < DIMUSE_MAX_STREAMZONES; i++) {
+IMuseStreamZone *IMuse::dispatchAllocateStreamZone() {
+	for (int i = 0; i < IMUSE_MAX_STREAMZONES; i++) {
 		if (_streamZones[i].useFlag == 0) {
 			_streamZones[i].prev = 0;
 			_streamZones[i].next = 0;
@@ -1234,59 +1234,59 @@ IMuseDigiStreamZone *IMuseDigital::dispatchAllocateStreamZone() {
 			return &_streamZones[i];
 		}
 	}
-	debug(5, "IMuseDigital::dispatchAllocateStreamZone(): ERROR: out of streamZones");
+	debug(5, "IMuse::dispatchAllocateStreamZone(): ERROR: out of streamZones");
 	return nullptr;
 }
 
-uint8 *IMuseDigital::dispatchAllocateFade(int32 &fadeSize, const char *function) {
+uint8 *IMuse::dispatchAllocateFade(int32 &fadeSize, const char *function) {
 	uint8 *allocatedFadeBuf = nullptr;
-	if (fadeSize > DIMUSE_LARGE_FADE_DIM) {
-		debug(5, "IMuseDigital::dispatchAllocateFade(): WARNING: requested fade too large (%d) in %s()", fadeSize, function);
-		fadeSize = DIMUSE_LARGE_FADE_DIM;
+	if (fadeSize > IMUSE_LARGE_FADE_DIM) {
+		debug(5, "IMuse::dispatchAllocateFade(): WARNING: requested fade too large (%d) in %s()", fadeSize, function);
+		fadeSize = IMUSE_LARGE_FADE_DIM;
 	}
 
-	if (fadeSize <= DIMUSE_SMALL_FADE_DIM) { // Small fade
-		for (int i = 0; i <= DIMUSE_SMALL_FADES; i++) {
-			if (i == DIMUSE_SMALL_FADES) {
-				debug(5, "IMuseDigital::dispatchAllocateFade(): couldn't allocate small fade buffer in %s()", function);
+	if (fadeSize <= IMUSE_SMALL_FADE_DIM) { // Small fade
+		for (int i = 0; i <= IMUSE_SMALL_FADES; i++) {
+			if (i == IMUSE_SMALL_FADES) {
+				debug(5, "IMuse::dispatchAllocateFade(): couldn't allocate small fade buffer in %s()", function);
 				allocatedFadeBuf = nullptr;
 				break;
 			}
 
 			if (!_dispatchSmallFadeFlags[i]) {
 				_dispatchSmallFadeFlags[i] = 1;
-				allocatedFadeBuf = &_dispatchSmallFadeBufs[DIMUSE_SMALL_FADE_DIM * i];
+				allocatedFadeBuf = &_dispatchSmallFadeBufs[IMUSE_SMALL_FADE_DIM * i];
 				break;
 			}
 		}
 	} else { // Large fade
-		for (int i = 0; i <= DIMUSE_LARGE_FADES; i++) {
-			if (i == DIMUSE_LARGE_FADES) {
-				debug(5, "IMuseDigital::dispatchAllocateFade(): couldn't allocate large fade buffer in %s()", function);
+		for (int i = 0; i <= IMUSE_LARGE_FADES; i++) {
+			if (i == IMUSE_LARGE_FADES) {
+				debug(5, "IMuse::dispatchAllocateFade(): couldn't allocate large fade buffer in %s()", function);
 				allocatedFadeBuf = nullptr;
 				break;
 			}
 
 			if (!_dispatchLargeFadeFlags[i]) {
 				_dispatchLargeFadeFlags[i] = 1;
-				allocatedFadeBuf = &_dispatchLargeFadeBufs[DIMUSE_LARGE_FADE_DIM * i];
+				allocatedFadeBuf = &_dispatchLargeFadeBufs[IMUSE_LARGE_FADE_DIM * i];
 				break;
 			}
 		}
 
 		// Fallback to a small fade if large fades are unavailable
 		if (!allocatedFadeBuf) {
-			fadeSize = DIMUSE_SMALL_FADE_DIM;
-			for (int i = 0; i <= DIMUSE_SMALL_FADES; i++) {
-				if (i == DIMUSE_SMALL_FADES) {
-					debug(5, "IMuseDigital::dispatchAllocateFade(): couldn't allocate small fade buffer in %s()", function);
+			fadeSize = IMUSE_SMALL_FADE_DIM;
+			for (int i = 0; i <= IMUSE_SMALL_FADES; i++) {
+				if (i == IMUSE_SMALL_FADES) {
+					debug(5, "IMuse::dispatchAllocateFade(): couldn't allocate small fade buffer in %s()", function);
 					allocatedFadeBuf = nullptr;
 					break;
 				}
 
 				if (!_dispatchSmallFadeFlags[i]) {
 					_dispatchSmallFadeFlags[i] = 1;
-					allocatedFadeBuf = &_dispatchSmallFadeBufs[DIMUSE_SMALL_FADE_DIM * i];
+					allocatedFadeBuf = &_dispatchSmallFadeBufs[IMUSE_SMALL_FADE_DIM * i];
 					break;
 				}
 			}
@@ -1296,14 +1296,14 @@ uint8 *IMuseDigital::dispatchAllocateFade(int32 &fadeSize, const char *function)
 	return allocatedFadeBuf;
 }
 
-void IMuseDigital::dispatchDeallocateFade(IMuseDigiDispatch *dispatchPtr, const char *function) {
+void IMuse::dispatchDeallocateFade(IMuseDispatch *dispatchPtr, const char *function) {
 	// This function flags the fade corresponding to our fadeBuf as unused
 
 	// First, check if our fade buffer is one of the large fade buffers
-	for (int i = 0; i < DIMUSE_LARGE_FADES; i++) {
-		if (_dispatchLargeFadeBufs + (DIMUSE_LARGE_FADE_DIM * i) == dispatchPtr->fadeBuf) { // Found it!
+	for (int i = 0; i < IMUSE_LARGE_FADES; i++) {
+		if (_dispatchLargeFadeBufs + (IMUSE_LARGE_FADE_DIM * i) == dispatchPtr->fadeBuf) { // Found it!
 			if (_dispatchLargeFadeFlags[i] == 0) {
-				debug(5, "IMuseDigital::dispatchDeallocateFade(): redundant large fade buf de-allocation in %s()", function);
+				debug(5, "IMuse::dispatchDeallocateFade(): redundant large fade buf de-allocation in %s()", function);
 			}
 			_dispatchLargeFadeFlags[i] = 0;
 			return;
@@ -1311,40 +1311,40 @@ void IMuseDigital::dispatchDeallocateFade(IMuseDigiDispatch *dispatchPtr, const
 	}
 
 	// If not, check between the small fade buffers
-	for (int j = 0; j < DIMUSE_SMALL_FADES; j++) {
-		if (_dispatchSmallFadeBufs + (DIMUSE_SMALL_FADE_DIM * j) == dispatchPtr->fadeBuf) { // Found it!
+	for (int j = 0; j < IMUSE_SMALL_FADES; j++) {
+		if (_dispatchSmallFadeBufs + (IMUSE_SMALL_FADE_DIM * j) == dispatchPtr->fadeBuf) { // Found it!
 			if (_dispatchSmallFadeFlags[j] == 0) {
-				debug(5, "IMuseDigital::dispatchDeallocateFade(): redundant small fade buf de-allocation in %s()", function);
+				debug(5, "IMuse::dispatchDeallocateFade(): redundant small fade buf de-allocation in %s()", function);
 			}
 			_dispatchSmallFadeFlags[j] = 0;
 			return;
 		}
 	}
 
-	debug(5, "IMuseDigital::dispatchDeallocateFade(): couldn't find fade buf to de-allocate in %s()", function);
+	debug(5, "IMuse::dispatchDeallocateFade(): couldn't find fade buf to de-allocate in %s()", function);
 }
 
-int IMuseDigital::dispatchGetFadeSize(IMuseDigiDispatch *dispatchPtr, int fadeLength) {
+int IMuse::dispatchGetFadeSize(IMuseDispatch *dispatchPtr, int fadeLength) {
 	return (dispatchPtr->wordSize * dispatchPtr->channelCount * (dispatchPtr->sampleRate * fadeLength / 1000)) / 8;
 }
 
-void IMuseDigital::dispatchValidateFadeSize(IMuseDigiDispatch *dispatchPtr, int32 &dispatchSize) {
+void IMuse::dispatchValidateFadeSize(IMuseDispatch *dispatchPtr, int32 &dispatchSize) {
 	dispatchSize -= dispatchSize & (dispatchPtr->channelCount * (dispatchPtr->wordSize >> 3) - 1);
 }
 
-int IMuseDigital::dispatchUpdateFadeMixVolume(IMuseDigiDispatch *dispatchPtr, int32 remainingFade) {
+int IMuse::dispatchUpdateFadeMixVolume(IMuseDispatch *dispatchPtr, int32 remainingFade) {
 	int mixVolume = (((dispatchPtr->fadeVol / 65536) + 1) * dispatchPtr->trackPtr->effVol) / 128;
 	dispatchPtr->fadeVol += remainingFade * dispatchPtr->fadeSlope;
 
 	if (dispatchPtr->fadeVol < 0)
 		dispatchPtr->fadeVol = 0;
-	if (dispatchPtr->fadeVol > DIMUSE_MAX_FADE_VOLUME)
-		dispatchPtr->fadeVol = DIMUSE_MAX_FADE_VOLUME;
+	if (dispatchPtr->fadeVol > IMUSE_MAX_FADE_VOLUME)
+		dispatchPtr->fadeVol = IMUSE_MAX_FADE_VOLUME;
 
 	return mixVolume;
 }
 
-int IMuseDigital::dispatchUpdateFadeSlope(IMuseDigiDispatch *dispatchPtr) {
+int IMuse::dispatchUpdateFadeSlope(IMuseDispatch *dispatchPtr) {
 	int32 updatedVolume, effRemainingFade;
 
 	updatedVolume = (dispatchPtr->trackPtr->effVol * (128 - (dispatchPtr->fadeVol / 65536))) / 128;
@@ -1352,7 +1352,7 @@ int IMuseDigital::dispatchUpdateFadeSlope(IMuseDigiDispatch *dispatchPtr) {
 		effRemainingFade = dispatchPtr->fadeRemaining;
 		if (effRemainingFade <= 1)
 			effRemainingFade = 2;
-		dispatchPtr->fadeSlope = -(DIMUSE_MAX_FADE_VOLUME / effRemainingFade);
+		dispatchPtr->fadeSlope = -(IMUSE_MAX_FADE_VOLUME / effRemainingFade);
 	}
 
 	return updatedVolume;
diff --git a/engines/grim/imuse/dimuse_engine.cpp b/engines/grim/imuse/imuse_engine.cpp
similarity index 61%
rename from engines/grim/imuse/dimuse_engine.cpp
rename to engines/grim/imuse/imuse_engine.cpp
index e7c9707cd11..8d3f2c0fad4 100644
--- a/engines/grim/imuse/dimuse_engine.cpp
+++ b/engines/grim/imuse/imuse_engine.cpp
@@ -22,9 +22,9 @@
 #include "common/system.h"
 #include "common/timer.h"
 
-#include "engines/grim/imuse/dimuse_engine.h"
-#include "engines/grim/imuse/dimuse_defs.h"
-#include "engines/grim/imuse/dimuse_tables.h"
+#include "engines/grim/imuse/imuse_engine.h"
+#include "engines/grim/imuse/imuse_defs.h"
+#include "engines/grim/imuse/imuse_tables.h"
 
 #include "engines/grim/movie/codecs/vima.h"
 
@@ -35,24 +35,24 @@
 
 namespace Grim {
 
-IMuseDigital *g_imuse = nullptr;
+IMuse *g_imuse = nullptr;
 
-void IMuseDigital::timer_handler(void *refCon) {
-	IMuseDigital *diMUSE = (IMuseDigital *)refCon;
-	diMUSE->diMUSEHeartbeat();
+void IMuse::timer_handler(void *refCon) {
+	IMuse *imuse = (IMuse *)refCon;
+	imuse->imHeartbeat();
 }
 
-IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode)
+IMuse::IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode)
 	: _mixer(mixer), _mutex(mutex) {
 	assert(mixer);
 
 	// 50 Hz rate for the callback
-	_callbackFps = DIMUSE_TIMER_BASE_RATE_HZ;
-	_usecPerInt = DIMUSE_TIMER_BASE_RATE_USEC;
+	_callbackFps = IMUSE_TIMER_BASE_RATE_HZ;
+	_usecPerInt = IMUSE_TIMER_BASE_RATE_USEC;
 
 	_lowLatencyMode = lowLatencyMode;
 	_internalSampleRate = sampleRate;
-	_internalFeedSize = (int)(DIMUSE_BASE_FEEDSIZE * ((float)_internalSampleRate / DIMUSE_BASE_SAMPLERATE));
+	_internalFeedSize = (int)(IMUSE_BASE_FEEDSIZE * ((float)_internalSampleRate / IMUSE_BASE_SAMPLERATE));
 
 	if (_lowLatencyMode) {
 		_internalFeedSize *= 2;
@@ -85,10 +85,10 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 	_underrunCooldown = 0;
 
 	_emptyMarker[0] = '\0';
-	_internalMixer = new IMuseDigiInternalMixer(mixer, _internalSampleRate, _lowLatencyMode);
-	_groupsHandler = new IMuseDigiGroupsHandler(this, mutex);
-	_fadesHandler = new IMuseDigiFadesHandler(this, mutex);
-	_triggersHandler = new IMuseDigiTriggersHandler(this, mutex);
+	_internalMixer = new IMuseInternalMixer(mixer, _internalSampleRate, _lowLatencyMode);
+	_groupsHandler = new IMuseGroupsHandler(this, mutex);
+	_fadesHandler = new IMuseFadesHandler(this, mutex);
+	_triggersHandler = new IMuseTriggersHandler(this, mutex);
 
 	memset(_soundCache, 0, sizeof(_soundCache));
 	_currentSoundSlot = 0;
@@ -118,12 +118,12 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 	_voiceRemainderSize = 0;
 	_voiceRemainderCapacity = 0;
 	_voiceRemainderPos = 0;
-	setupHMI(DIMUSE_HMI_HEAP_SIZE);
+	setupHMI(IMUSE_HMI_HEAP_SIZE);
 
-	diMUSEInitialize();
-	soundsAllocateBuffer(DIMUSE_BUFFER_MUSIC, 440000, 44000, 352000);
-	soundsAllocateBuffer(DIMUSE_BUFFER_SPEECH, 88000, 44000, 88000);
-	diMUSEInitializeScript();
+	imInitialize();
+	soundsAllocateBuffer(IMUSE_BUFFER_MUSIC, 440000, 44000, 352000);
+	soundsAllocateBuffer(IMUSE_BUFFER_SPEECH, 88000, 44000, 88000);
+	imInitializeScript();
 
 	if (_mixer->getOutputBufSize() != 0) {
 		// Let's find the optimal value for the maximum number of streams which can stay in the queue at once;
@@ -139,7 +139,7 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 		// The lower optimal bound is always 4, except if we're operating in low latency mode
 		_maxQueuedStreams = MAX(_mixer->getOutputBufSize() <= 1024 ? 3 : 4, _maxQueuedStreams);
 	} else {
-		debug(5, "IMuseDigital::IMuseDigital(): WARNING: output audio buffer size not specified for this platform, defaulting _maxQueuedStreams to 4");
+		debug(5, "IMuse::IMuse(): WARNING: output audio buffer size not specified for this platform, defaulting _maxQueuedStreams to 4");
 		_maxQueuedStreams = 4;
 	}
 
@@ -151,12 +151,12 @@ IMuseDigital::IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *m
 	_nominalBufferCount = _maxQueuedStreams;
 	_underrunCooldown = _maxQueuedStreams;
 
-	g_system->getTimerManager()->installTimerProc(timer_handler, 1000000 / _callbackFps, this, "IMuseDigital");
+	g_system->getTimerManager()->installTimerProc(timer_handler, 1000000 / _callbackFps, this, "IMuse");
 }
 
-IMuseDigital::~IMuseDigital() {
+IMuse::~IMuse() {
 	g_system->getTimerManager()->removeTimerProc(timer_handler);
-	diMUSETerminateScript();
+	imTerminateScript();
 
 	soundsTerminateProcessing();
 	free(_voiceSrcBuf);
@@ -166,11 +166,11 @@ IMuseDigital::~IMuseDigital() {
 	_voiceRemainderBuf = nullptr;
 	delete _hmiFxLib;
 
-	diMUSETerminate();
+	imTerminate();
 
 	cacheReset();
-	soundsDeallocateBuffer(DIMUSE_BUFFER_SPEECH);
-	soundsDeallocateBuffer(DIMUSE_BUFFER_MUSIC);
+	soundsDeallocateBuffer(IMUSE_BUFFER_SPEECH);
+	soundsDeallocateBuffer(IMUSE_BUFFER_MUSIC);
 
 	delete _internalMixer;
 	delete _groupsHandler;
@@ -185,7 +185,7 @@ IMuseDigital::~IMuseDigital() {
 	_waveOutLowLatencyOutputBuffer = nullptr;
 }
 
-int IMuseDigital::roundRobinSetBufferCount() {
+int IMuse::roundRobinSetBufferCount() {
 	int minStreams = MAX<int>(_nominalBufferCount - 5, 1);
 	int maxStreams = _nominalBufferCount + 5;
 	_maxQueuedStreams++;
@@ -197,24 +197,24 @@ int IMuseDigital::roundRobinSetBufferCount() {
 	return _maxQueuedStreams;
 }
 
-void IMuseDigital::adaptBufferCount() {
+void IMuse::adaptBufferCount() {
 	_maxQueuedStreams++;
 	_nominalBufferCount = _maxQueuedStreams;
 }
 
-void IMuseDigital::stopSound(int sound) {
-	diMUSEStopSound(sound);
+void IMuse::stopSound(int sound) {
+	imStopSound(sound);
 }
 
-void IMuseDigital::stopAllSounds() {
-	diMUSEStopAllSounds();
+void IMuse::stopAllSounds() {
+	imStopAllSounds();
 }
 
-int IMuseDigital::isSoundRunning(int soundId) {
-	return diMUSEGetParam(soundId, DIMUSE_P_SND_TRACK_NUM) > 0;
+int IMuse::isSoundRunning(int soundId) {
+	return imGetParam(soundId, IMUSE_P_SND_TRACK_NUM) > 0;
 }
 
-void IMuseDigital::diMUSEHeartbeat() {
+void IMuse::imHeartbeat() {
 	int soundId, musicTargetVolume, musicEffVol, musicVol, tempVol, tempEffVol;
 
 	if (_callbackInterruptFlag)
@@ -230,45 +230,45 @@ void IMuseDigital::diMUSEHeartbeat() {
 	//
 	// 	if (_curMixerMusicVolume != _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType)) {
 	// 		_curMixerMusicVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType);
-	// 		diMUSESetMusicGroupVol(CLIP(_mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType) / 2, 0, 127));
+	// 		setMusicGroupVol(CLIP(_mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType) / 2, 0, 127));
 	// 	}
 	//
 	// 	if (_curMixerSpeechVolume != _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType)) {
 	// 		_curMixerSpeechVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType);
-	// 		diMUSESetVoiceGroupVol(CLIP(_mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType) / 2, 0, 127));
+	// 		setVoiceGroupVol(CLIP(_mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType) / 2, 0, 127));
 	// 	}
 	//
 	// 	if (_curMixerSFXVolume != _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType)) {
 	// 		_curMixerSFXVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType);
-	// 		diMUSESetSFXGroupVol(CLIP(_mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType) / 2, 0, 127));
+	// 		setSFXGroupVol(CLIP(_mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType) / 2, 0, 127));
 	// 	}
 	// }
 
 	if (!_cmdsPauseCount) {
 		// Handle fades and triggers
 		_cmdsRunning50HzCount += _usecPerInt;
-		while (_cmdsRunning50HzCount >= DIMUSE_TIMER_FADES_RATE_USEC) {
-			_cmdsRunning50HzCount -= DIMUSE_TIMER_FADES_RATE_USEC;
+		while (_cmdsRunning50HzCount >= IMUSE_TIMER_FADES_RATE_USEC) {
+			_cmdsRunning50HzCount -= IMUSE_TIMER_FADES_RATE_USEC;
 			_fadesHandler->loop();
 			_triggersHandler->loop();
 		}
 
 		// Music gain reduction while speech is playing
 		_cmdsRunning5HzCount += _usecPerInt;
-		if (_cmdsRunning5HzCount >= DIMUSE_TIMER_GAIN_RED_RATE_USEC) {
+		if (_cmdsRunning5HzCount >= IMUSE_TIMER_GAIN_RED_RATE_USEC) {
 			while (1) {
-				_cmdsRunning5HzCount -= DIMUSE_TIMER_GAIN_RED_RATE_USEC;
+				_cmdsRunning5HzCount -= IMUSE_TIMER_GAIN_RED_RATE_USEC;
 
-				musicTargetVolume = _groupsHandler->setGroupVol(DIMUSE_GROUP_MUSIC, -1);
-				for (soundId = diMUSEGetNextSound(0); soundId; soundId = diMUSEGetNextSound(soundId)) {
-					if (diMUSEGetParam(soundId, DIMUSE_P_GROUP) == DIMUSE_GROUP_SPEECH) {
+				musicTargetVolume = _groupsHandler->setGroupVol(IMUSE_GROUP_MUSIC, -1);
+				for (soundId = imGetNextSound(0); soundId; soundId = imGetNextSound(soundId)) {
+					if (imGetParam(soundId, IMUSE_P_GROUP) == IMUSE_GROUP_SPEECH) {
 						musicTargetVolume = (77 * musicTargetVolume) >> 7;
 						break;
 					}
 				}
 
-				musicEffVol = _groupsHandler->setGroupVol(DIMUSE_GROUP_MUSICEFF, -1);
-				musicVol = _groupsHandler->setGroupVol(DIMUSE_GROUP_MUSIC, -1);
+				musicEffVol = _groupsHandler->setGroupVol(IMUSE_GROUP_MUSICEFF, -1);
+				musicVol = _groupsHandler->setGroupVol(IMUSE_GROUP_MUSIC, -1);
 
 				if (musicEffVol > musicTargetVolume) {
 					tempVol = musicEffVol - 36;
@@ -278,7 +278,7 @@ void IMuseDigital::diMUSEHeartbeat() {
 					} else if (tempVol < musicVol) {
 						musicVol = tempVol;
 					}
-					_groupsHandler->setGroupVol(DIMUSE_GROUP_MUSICEFF, musicVol);
+					_groupsHandler->setGroupVol(IMUSE_GROUP_MUSICEFF, musicVol);
 				} else if (musicEffVol < musicTargetVolume) {
 					tempEffVol = musicEffVol + 1;
 					if (tempEffVol < musicTargetVolume) {
@@ -287,10 +287,10 @@ void IMuseDigital::diMUSEHeartbeat() {
 					} else if (musicTargetVolume > musicVol) {
 						musicVol = musicTargetVolume;
 					}
-					_groupsHandler->setGroupVol(DIMUSE_GROUP_MUSICEFF, musicVol);
+					_groupsHandler->setGroupVol(IMUSE_GROUP_MUSICEFF, musicVol);
 				}
 
-				if (_cmdsRunning5HzCount < DIMUSE_TIMER_GAIN_RED_RATE_USEC)
+				if (_cmdsRunning5HzCount < IMUSE_TIMER_GAIN_RED_RATE_USEC)
 					break;
 			}
 		}
@@ -299,148 +299,148 @@ void IMuseDigital::diMUSEHeartbeat() {
 	_callbackInterruptFlag = false;
 }
 
-void IMuseDigital::setPriority(int soundId, int priority) {
-	diMUSESetParam(soundId, DIMUSE_P_PRIORITY, priority);
+void IMuse::setPriority(int soundId, int priority) {
+	imSetParam(soundId, IMUSE_P_PRIORITY, priority);
 }
 
-void IMuseDigital::setVolume(int soundId, int volume) {
-	diMUSESetParam(soundId, DIMUSE_P_VOLUME, volume);
+void IMuse::setVolume(int soundId, int volume) {
+	imSetParam(soundId, IMUSE_P_VOLUME, volume);
 	if (soundId == kTalkSoundID)
 		_currentSpeechVolume = volume;
 }
 
-void IMuseDigital::setPan(int soundId, int pan) {
-	diMUSESetParam(soundId, DIMUSE_P_PAN, pan);
+void IMuse::setPan(int soundId, int pan) {
+	imSetParam(soundId, IMUSE_P_PAN, pan);
 	if (soundId == kTalkSoundID)
 		_currentSpeechPan = pan;
 }
 
-void IMuseDigital::setFrequency(int soundId, int frequency) {
-	diMUSESetParam(soundId, DIMUSE_P_TRANSPOSE, frequency);
+void IMuse::setFrequency(int soundId, int frequency) {
+	imSetParam(soundId, IMUSE_P_TRANSPOSE, frequency);
 	if (soundId == kTalkSoundID)
 		_currentSpeechFrequency = frequency;
 }
 
-int IMuseDigital::getCurSpeechVolume() const {
+int IMuse::getCurSpeechVolume() const {
 	return _currentSpeechVolume;
 }
 
-int IMuseDigital::getCurSpeechPan() const {
+int IMuse::getCurSpeechPan() const {
 	return _currentSpeechPan;
 }
 
-int IMuseDigital::getCurSpeechFrequency() const {
+int IMuse::getCurSpeechFrequency() const {
 	return _currentSpeechFrequency;
 }
 
 // This is used in order to avoid crash everything
 // if a compressed audio resource file is found
-void IMuseDigital::disableEngine() {
+void IMuse::disableEngine() {
 	_isEngineDisabled = true;
 }
 
-bool IMuseDigital::isEngineDisabled() {
+bool IMuse::isEngineDisabled() {
 	return _isEngineDisabled;
 }
 
-int32 IMuseDigital::getCurMusicPosInMs() {
+int32 IMuse::getCurMusicPosInMs() {
 	int soundId, curSoundId;
 
 	curSoundId = 0;
 	soundId = 0;
 	while (1) {
-		curSoundId = diMUSEGetNextSound(curSoundId);
+		curSoundId = imGetNextSound(curSoundId);
 		if (!curSoundId)
 			break;
 
-		if (diMUSEGetParam(curSoundId, DIMUSE_P_SND_HAS_STREAM) && diMUSEGetParam(curSoundId, DIMUSE_P_STREAM_BUFID) == DIMUSE_BUFFER_MUSIC) {
+		if (imGetParam(curSoundId, IMUSE_P_SND_HAS_STREAM) && imGetParam(curSoundId, IMUSE_P_STREAM_BUFID) == IMUSE_BUFFER_MUSIC) {
 			soundId = curSoundId;
-			return diMUSEGetParam(soundId, DIMUSE_P_SND_POS_IN_MS);
+			return imGetParam(soundId, IMUSE_P_SND_POS_IN_MS);
 		}
 	}
 
-	return diMUSEGetParam(soundId, DIMUSE_P_SND_POS_IN_MS);
+	return imGetParam(soundId, IMUSE_P_SND_POS_IN_MS);
 }
 
-int32 IMuseDigital::getSoundElapsedTimeInMs(int soundId) {
-	if (diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM)) {
-		return diMUSEGetParam(soundId, DIMUSE_P_SND_POS_IN_MS);
+int32 IMuse::getSoundElapsedTimeInMs(int soundId) {
+	if (imGetParam(soundId, IMUSE_P_SND_HAS_STREAM)) {
+		return imGetParam(soundId, IMUSE_P_SND_POS_IN_MS);
 	}
 	return 0;
 }
 
-void IMuseDigital::pause(bool p) {
+void IMuse::pause(bool p) {
 	if (p) {
-		debug(5, "IMuseDigital::pause(): pausing...");
-		diMUSEPause();
+		debug(5, "IMuse::pause(): pausing...");
+		imPause();
 	} else {
-		debug(5, "IMuseDigital::pause(): resuming...");
-		diMUSEResume();
+		debug(5, "IMuse::pause(): resuming...");
+		imResume();
 	}
 }
 
-void IMuseDigital::floodMusicBuffer() {
-	while (!isMusicStreamIdle()) {
-		diMUSEProcessStreams();
+void IMuse::soundsFloodMusicBuffer() {
+	while (!soundsIsMusicStreamIdle()) {
+		imProcessStreams();
 	}
 }
 
-void IMuseDigital::fillStreamsWhileMusicCritical(int fillTimesAfter) {
-	while (isMusicCritical()) {
-		diMUSEProcessStreams();
+void IMuse::soundsFillStreamsWhileMusicCritical(int fillTimesAfter) {
+	while (soundsIsMusicCritical()) {
+		imProcessStreams();
 	}
 
 	for (int i = 0; i < fillTimesAfter; i++) {
-		diMUSEProcessStreams();
+		imProcessStreams();
 	}
 }
 
-bool IMuseDigital::isMusicStreamIdle() {
+bool IMuse::soundsIsMusicStreamIdle() {
 	int32 bufSize, criticalSize, freeSpace;
 	int paused;
-	IMuseDigiSndBuffer *bufInfo = filesGetBufInfo(DIMUSE_BUFFER_MUSIC);
+	IMuseSndBuffer *bufInfo = filesGetBufInfo(IMUSE_BUFFER_MUSIC);
 
-	if (!queryNextSoundFile(bufSize, criticalSize, freeSpace, paused))
+	if (!queryMusicStream(bufSize, criticalSize, freeSpace, paused))
 		return true;
 	return (paused > 0) || (bufSize - bufInfo->loadSize < freeSpace);
 }
 
-bool IMuseDigital::isMusicCritical() {
+bool IMuse::soundsIsMusicCritical() {
 	int32 bufSize, criticalSize, freeSpace;
 	int paused;
 
-	if (!queryNextSoundFile(bufSize, criticalSize, freeSpace, paused))
+	if (!queryMusicStream(bufSize, criticalSize, freeSpace, paused))
 		return false;
 	return (paused == 0) && freeSpace <= criticalSize;
 }
 
-bool IMuseDigital::queryNextSoundFile(int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
+bool IMuse::queryMusicStream(int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
 	int soundId;
-	soundId = diMUSEGetNextSound(0);
+	soundId = imGetNextSound(0);
 	while (soundId) {
-		if (diMUSEGetParam(soundId, DIMUSE_P_SND_HAS_STREAM) &&
-			(diMUSEGetParam(soundId, DIMUSE_P_GROUP) == DIMUSE_GROUP_MUSIC || diMUSEGetParam(soundId, DIMUSE_P_GROUP) == DIMUSE_GROUP_MUSICEFF)) {
-			diMUSEQueryStream(soundId, bufSize, criticalSize, freeSpace, paused);
+		if (imGetParam(soundId, IMUSE_P_SND_HAS_STREAM) &&
+			(imGetParam(soundId, IMUSE_P_GROUP) == IMUSE_GROUP_MUSIC || imGetParam(soundId, IMUSE_P_GROUP) == IMUSE_GROUP_MUSICEFF)) {
+			imQueryStream(soundId, bufSize, criticalSize, freeSpace, paused);
 			return true;
 		}
-		soundId = diMUSEGetNextSound(soundId);
+		soundId = imGetNextSound(soundId);
 	}
 	return false;
 }
 
-int IMuseDigital::getSampleRate() {
+int IMuse::getSampleRate() {
 	return _internalSampleRate;
 }
 
-int IMuseDigital::getFeedSize() {
+int IMuse::getFeedSize() {
 	return _internalFeedSize;
 }
 
-int IMuseDigital::diMUSETerminate() {
+int IMuse::imTerminate() {
 	return tracksDeinit();
 }
 
-int IMuseDigital::diMUSEInitialize() {
+int IMuse::imInitialize() {
 	if (_initialized)
 		return -1;
 
@@ -459,14 +459,14 @@ int IMuseDigital::diMUSEInitialize() {
 	return 49;
 }
 
-void IMuseDigital::diMUSEPause() {
+void IMuse::imPause() {
 	Common::StackLock lock(*_mutex);
 
 	if (_cmdsPauseCount++ == 0)
 		tracksPause();
 }
 
-void IMuseDigital::diMUSEResume() {
+void IMuse::imResume() {
 	Common::StackLock lock(*_mutex);
 
 	if (--_cmdsPauseCount) {
@@ -477,11 +477,11 @@ void IMuseDigital::diMUSEResume() {
 	}
 }
 
-int IMuseDigital::diMUSESaveLoad(Common::Serializer &ser) {
+int IMuse::imSaveLoad(Common::Serializer &ser) {
 	Common::StackLock lock(*_mutex);
 
 	if (ser.isLoading())
-		diMUSEStopAllSounds();
+		imStopAllSounds();
 
 	_fadesHandler->saveLoad(ser);
 	_triggersHandler->saveLoad(ser);
@@ -489,15 +489,15 @@ int IMuseDigital::diMUSESaveLoad(Common::Serializer &ser) {
 	return 0;
 }
 
-int IMuseDigital::diMUSESetGroupVol(int groupId, int volume) {
+int IMuse::imSetGroupVol(int groupId, int volume) {
 	return _groupsHandler->setGroupVol(groupId, volume);
 }
 
-int IMuseDigital::diMUSEStartSound(int soundId, int priority) {
+int IMuse::imStartSound(int soundId, int priority) {
 	uint8 *src = filesFetchMap(soundId);
 
 	if (src == nullptr) {
-		debug(5, "IMuseDigital::diMUSEStartSound(): ERROR: map address for sound %d is NULL", soundId);
+		debug(5, "IMuse::imStartSound(): ERROR: map address for sound %d is NULL", soundId);
 		return -1;
 	}
 
@@ -510,34 +510,34 @@ int IMuseDigital::diMUSEStartSound(int soundId, int priority) {
 	return -1;
 }
 
-int IMuseDigital::diMUSEStopSound(int soundId) {
-	debug(5, "IMuseDigital::diMUSEStopSound(): %d", soundId);
+int IMuse::imStopSound(int soundId) {
+	debug(5, "IMuse::imStopSound(): %d", soundId);
 	Common::StackLock lock(*_mutex);
 	return tracksStopSound(soundId);
 }
 
-int IMuseDigital::diMUSEStopAllSounds() {
-	debug(5, "IMuseDigital::diMUSEStopAllSounds()");
+int IMuse::imStopAllSounds() {
+	debug(5, "IMuse::imStopAllSounds()");
 	Common::StackLock lock(*_mutex);
 	return tracksStopAllSounds();
 }
 
-int IMuseDigital::diMUSEGetNextSound(int soundId) {
+int IMuse::imGetNextSound(int soundId) {
 	return tracksGetNextSound(soundId);
 }
 
-int IMuseDigital::diMUSESetParam(int soundId, int paramId, int value) {
+int IMuse::imSetParam(int soundId, int paramId, int value) {
 	Common::StackLock lock(*_mutex);
 	return tracksSetParam(soundId, paramId, value);
 }
 
-int IMuseDigital::diMUSEGetParam(int soundId, int paramId) {
+int IMuse::imGetParam(int soundId, int paramId) {
 	int param;
 
 	if (!paramId)
 		return 2;
 
-	if (paramId == DIMUSE_P_TRIGS_SNDS)
+	if (paramId == IMUSE_P_TRIGS_SNDS)
 		return _triggersHandler->countPendingSounds(soundId);
 
 	{
@@ -545,41 +545,41 @@ int IMuseDigital::diMUSEGetParam(int soundId, int paramId) {
 		param = tracksGetParam(soundId, paramId);
 	}
 
-	if (param < 0 && paramId == DIMUSE_P_SND_TRACK_NUM)
+	if (param < 0 && paramId == IMUSE_P_SND_TRACK_NUM)
 		return 0;
 
 	return param;
 }
 
-int IMuseDigital::diMUSEFadeParam(int soundId, int opcode, int destValue, int fadeLength) {
+int IMuse::imFadeParam(int soundId, int opcode, int destValue, int fadeLength) {
 	return _fadesHandler->fadeParam(soundId, opcode, destValue, fadeLength);
 }
 
-int IMuseDigital::diMUSESetHook(int soundId, int hookId) {
+int IMuse::imSetHook(int soundId, int hookId) {
 	return tracksSetHook(soundId, hookId);
 }
 
-int IMuseDigital::diMUSEGetHook(int soundId) {
+int IMuse::imGetHook(int soundId) {
 	return tracksGetHook(soundId);
 }
 
-int IMuseDigital::diMUSESetTrigger(int soundId, const char *marker, int opcode, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
+int IMuse::imSetTrigger(int soundId, const char *marker, int opcode, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
 	return _triggersHandler->setTrigger(soundId, (char *)marker, opcode, d, e, f, g, h, i, j, k, l, m, n);
 }
 
-int IMuseDigital::diMUSECheckTrigger(int soundId, const char *marker, int opcode) {
+int IMuse::imCheckTrigger(int soundId, const char *marker, int opcode) {
 	return _triggersHandler->checkTrigger(soundId, (char *)marker, opcode);
 }
 
-int IMuseDigital::diMUSEClearTrigger(int soundId, const char *marker, int opcode) {
+int IMuse::imClearTrigger(int soundId, const char *marker, int opcode) {
 	return _triggersHandler->clearTrigger(soundId, (char *)marker, opcode);
 }
 
-int IMuseDigital::diMUSEDeferCommand(int count, int opcode, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
+int IMuse::imDeferCommand(int count, int opcode, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
 	return _triggersHandler->deferCommand(count, opcode, c, d, e, f, g, h, i, j, k, l, m, n);
 }
 
-int IMuseDigital::diMUSEStartStream(int soundId, int priority, int bufferId) {
+int IMuse::imStartStream(int soundId, int priority, int bufferId) {
 	if (!filesCheckRange(soundId))
 		return -1;
 
@@ -587,111 +587,111 @@ int IMuseDigital::diMUSEStartStream(int soundId, int priority, int bufferId) {
 	return tracksStartSound(soundId, priority, bufferId);
 }
 
-int IMuseDigital::diMUSESwitchStream(int oldSoundId, int newSoundId, int fadeDelay, int fadeSyncFlag2, int fadeSyncFlag1) {
+int IMuse::imSwitchStream(int oldSoundId, int newSoundId, int fadeDelay, int fadeSyncFlag2, int fadeSyncFlag1) {
 	Common::StackLock lock(*_mutex);
 	return dispatchSwitchStream(oldSoundId, newSoundId, fadeDelay, fadeSyncFlag2, fadeSyncFlag1);
 }
 
-int IMuseDigital::diMUSEProcessStreams() {
+int IMuse::imProcessStreams() {
 	Common::StackLock lock(*_mutex);
 	return streamerProcessStreams();
 }
 
-int IMuseDigital::diMUSEQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
+int IMuse::imQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
 	Common::StackLock lock(*_mutex);
 	return tracksQueryStream(soundId, bufSize, criticalSize, freeSpace, paused);
 }
 
-int IMuseDigital::diMUSEFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused) {
+int IMuse::imFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused) {
 	Common::StackLock lock(*_mutex);
 	return tracksFeedStream(soundId, srcBuf, sizeToFeed, paused);
 }
 
-int IMuseDigital::diMUSEGetMusicGroupVol() {
+int IMuse::getMusicGroupVol() {
 	// TODO
 	// if (_vm->isUsingOriginalGUI()) {
-	// 	return diMUSESetGroupVol(DIMUSE_GROUP_MUSIC, -1);
+	// 	return imSetGroupVol(IMUSE_GROUP_MUSIC, -1);
 	// }
 	//
 	// return _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType) / 2;
-	return diMUSESetGroupVol(DIMUSE_GROUP_MUSIC, -1);
+	return imSetGroupVol(IMUSE_GROUP_MUSIC, -1);
 }
 
-int IMuseDigital::diMUSEGetSFXGroupVol() {
+int IMuse::getSFXGroupVol() {
 	// TODO
 	// if (_vm->isUsingOriginalGUI()) {
-	// 	return diMUSESetGroupVol(DIMUSE_GROUP_SFX, -1);
+	// 	return imSetGroupVol(IMUSE_GROUP_SFX, -1);
 	// }
 	//
 	// return _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType) / 2;
-	return diMUSESetGroupVol(DIMUSE_GROUP_SFX, -1);
+	return imSetGroupVol(IMUSE_GROUP_SFX, -1);
 }
 
-int IMuseDigital::diMUSEGetVoiceGroupVol() {
+int IMuse::getVoiceGroupVol() {
 	// TODO
 	// if (_vm->isUsingOriginalGUI()) {
-	// 	return diMUSESetGroupVol(DIMUSE_GROUP_SPEECH, -1);
+	// 	return imSetGroupVol(IMUSE_GROUP_SPEECH, -1);
 	// }
 	//
 	// return _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType) / 2;
-	return diMUSESetGroupVol(DIMUSE_GROUP_SPEECH, -1);
+	return imSetGroupVol(IMUSE_GROUP_SPEECH, -1);
 }
 
-int IMuseDigital::diMUSESetMusicGroupVol(int volume) {
-	debug(5, "IMuseDigital::diMUSESetMusicGroupVol(): %d", volume);
-	return diMUSESetGroupVol(DIMUSE_GROUP_MUSIC, volume);
+int IMuse::setMusicGroupVol(int volume) {
+	debug(5, "IMuse::setMusicGroupVol(): %d", volume);
+	return imSetGroupVol(IMUSE_GROUP_MUSIC, volume);
 }
 
-int IMuseDigital::diMUSESetSFXGroupVol(int volume) {
-	debug(5, "IMuseDigital::diMUSESetSFXGroupVol(): %d", volume);
-	return diMUSESetGroupVol(DIMUSE_GROUP_SFX, volume);
+int IMuse::setSFXGroupVol(int volume) {
+	debug(5, "IMuse::setSFXGroupVol(): %d", volume);
+	return imSetGroupVol(IMUSE_GROUP_SFX, volume);
 }
 
-int IMuseDigital::diMUSESetVoiceGroupVol(int volume) {
-	debug(5, "IMuseDigital::diMUSESetVoiceGroupVol(): %d", volume);
-	return diMUSESetGroupVol(DIMUSE_GROUP_SPEECH, volume);
+int IMuse::setVoiceGroupVol(int volume) {
+	debug(5, "IMuse::setVoiceGroupVol(): %d", volume);
+	return imSetGroupVol(IMUSE_GROUP_SPEECH, volume);
 }
 
-int IMuseDigital::diMUSEInitializeScript() {
-	return scriptParse(DIMUSE_C_SCRIPT_INIT, -1, -1);
+int IMuse::imInitializeScript() {
+	return scriptParse(IMUSE_C_SCRIPT_INIT, -1, -1);
 }
 
-int IMuseDigital::diMUSETerminateScript() {
-	return scriptParse(DIMUSE_C_SCRIPT_TERMINATE, -1, -1);
+int IMuse::imTerminateScript() {
+	return scriptParse(IMUSE_C_SCRIPT_TERMINATE, -1, -1);
 }
 
-void IMuseDigital::diMUSESaveLoadScript(Common::Serializer &ser) {
+void IMuse::imSaveLoadScript(Common::Serializer &ser) {
 	scriptSaveLoad(ser);
 }
 
-void IMuseDigital::diMUSERefreshScript() {
-	scriptParse(DIMUSE_C_SCRIPT_REFRESH, -1, -1);
+void IMuse::imRefreshScript() {
+	scriptParse(IMUSE_C_SCRIPT_REFRESH, -1, -1);
 }
 
-int IMuseDigital::diMUSESetState(int soundId) {
-	return scriptParse(DIMUSE_C_SCRIPT_SET_STATE, soundId, -1);
+int IMuse::imSetState(int soundId) {
+	return scriptParse(IMUSE_C_SCRIPT_SET_STATE, soundId, -1);
 }
 
-int IMuseDigital::diMUSESetSequence(int soundId) {
-	return scriptParse(DIMUSE_C_SCRIPT_SET_SEQUENCE, soundId, -1);
+int IMuse::imSetSequence(int soundId) {
+	return scriptParse(IMUSE_C_SCRIPT_SET_SEQUENCE, soundId, -1);
 }
 
-int IMuseDigital::diMUSESetCuePoint(int cueId) {
-	return scriptParse(DIMUSE_C_SCRIPT_CUE_POINT, cueId, -1);
+int IMuse::imSetCuePoint(int cueId) {
+	return scriptParse(IMUSE_C_SCRIPT_CUE_POINT, cueId, -1);
 }
 
-int IMuseDigital::diMUSESetAttribute(int attrIndex, int attrVal) {
-	return scriptParse(DIMUSE_C_SCRIPT_SET_ATTRIBUTE, attrIndex, attrVal);
+int IMuse::imSetAttribute(int attrIndex, int attrVal) {
+	return scriptParse(IMUSE_C_SCRIPT_SET_ATTRIBUTE, attrIndex, attrVal);
 }
 
-void IMuseDigital::diMUSEEnableSpooledMusic() {
+void IMuse::enableSpooledMusic() {
 	_spooledMusicEnabled = true;
 }
 
-void IMuseDigital::diMUSEDisableSpooledMusic() {
+void IMuse::disableSpooledMusic() {
 	_spooledMusicEnabled = true;
-	diMUSESetState(0);
-	diMUSESetSequence(0);
+	imSetState(0);
+	imSetSequence(0);
 	_spooledMusicEnabled = false;
 }
 
@@ -699,7 +699,7 @@ void IMuseDigital::diMUSEDisableSpooledMusic() {
 
 // TODO
 #if 0
-void IMuseDigital::listStates() {
+void IMuse::listStates() {
 	_vm->getDebugger()->debugPrintf("+---------------------------------+\n");
 	_vm->getDebugger()->debugPrintf("| stateId |         name          |\n");
 	_vm->getDebugger()->debugPrintf("+---------+-----------------------+\n");
@@ -725,7 +725,7 @@ void IMuseDigital::listStates() {
 	_vm->getDebugger()->debugPrintf("+---------+-----------------------+\n\n");
 }
 
-void IMuseDigital::listSeqs() {
+void IMuse::listSeqs() {
 	_vm->getDebugger()->debugPrintf("+--------------------------------+\n");
 	_vm->getDebugger()->debugPrintf("|  seqId  |         name         |\n");
 	_vm->getDebugger()->debugPrintf("+---------+----------------------+\n");
@@ -745,7 +745,7 @@ void IMuseDigital::listSeqs() {
 	_vm->getDebugger()->debugPrintf("+---------+----------------------+\n\n");
 }
 
-void IMuseDigital::listCues() {
+void IMuse::listCues() {
 	int curId = -1;
 	if (_curMusicSeq) {
 		_vm->getDebugger()->debugPrintf("Available cues for current sequence:\n");
@@ -763,17 +763,17 @@ void IMuseDigital::listCues() {
 	}
 }
 
-void IMuseDigital::listTracks() {
+void IMuse::listTracks() {
 	_vm->getDebugger()->debugPrintf("Virtual audio tracks currently playing:\n");
 	_vm->getDebugger()->debugPrintf("+-------------------------------------------------------------------------+\n");
 	_vm->getDebugger()->debugPrintf("| # | soundId | group | hasStream | vol/effVol/pan  | priority | jumpHook |\n");
 	_vm->getDebugger()->debugPrintf("+---+---------+-------+-----------+-----------------+----------+----------+\n");
 
 	for (int i = 0; i < _trackCount; i++) {
-		IMuseDigiTrack curTrack = _tracks[i];
+		IMuseTrack curTrack = _tracks[i];
 		if (curTrack.soundId != 0) {
 			_vm->getDebugger()->debugPrintf("| %1d |  %5d  |   %d   |     %d     |   %3d/%3d/%3d   |   %3d    |   %3d    |\n",
-				i, curTrack.soundId, curTrack.group, diMUSEGetParam(curTrack.soundId, DIMUSE_P_SND_HAS_STREAM),
+				i, curTrack.soundId, curTrack.group, imGetParam(curTrack.soundId, IMUSE_P_SND_HAS_STREAM),
 				curTrack.vol, curTrack.effVol, curTrack.pan, curTrack.priority, curTrack.jumpHook);
 		} else {
 			_vm->getDebugger()->debugPrintf("| %1d |   ---   |  ---  |    ---    |   ---/---/---   |   ---    |   ---    |\n", i);
@@ -782,12 +782,12 @@ void IMuseDigital::listTracks() {
 	_vm->getDebugger()->debugPrintf("+---+---------+-------+-----------+-----------------+----------+----------+\n\n");
 }
 
-void IMuseDigital::listGroups() {
+void IMuse::listGroups() {
 	_vm->getDebugger()->debugPrintf("Volume groups:\n");
-	_vm->getDebugger()->debugPrintf("\tSFX:      %3d\n", _groupsHandler->getGroupVol(DIMUSE_GROUP_SFX));
-	_vm->getDebugger()->debugPrintf("\tSPEECH:   %3d\n", _groupsHandler->getGroupVol(DIMUSE_GROUP_SPEECH));
-	_vm->getDebugger()->debugPrintf("\tMUSIC:    %3d\n", _groupsHandler->getGroupVol(DIMUSE_GROUP_MUSIC));
-	_vm->getDebugger()->debugPrintf("\tMUSICEFF: %3d\n\n", _groupsHandler->getGroupVol(DIMUSE_GROUP_MUSICEFF));
+	_vm->getDebugger()->debugPrintf("\tSFX:      %3d\n", _groupsHandler->getGroupVol(IMUSE_GROUP_SFX));
+	_vm->getDebugger()->debugPrintf("\tSPEECH:   %3d\n", _groupsHandler->getGroupVol(IMUSE_GROUP_SPEECH));
+	_vm->getDebugger()->debugPrintf("\tMUSIC:    %3d\n", _groupsHandler->getGroupVol(IMUSE_GROUP_MUSIC));
+	_vm->getDebugger()->debugPrintf("\tMUSICEFF: %3d\n\n", _groupsHandler->getGroupVol(IMUSE_GROUP_MUSICEFF));
 }
 #endif
 
diff --git a/engines/grim/imuse/dimuse_engine.h b/engines/grim/imuse/imuse_engine.h
similarity index 57%
rename from engines/grim/imuse/dimuse_engine.h
rename to engines/grim/imuse/imuse_engine.h
index 3a8048a4c0f..ab44525ee86 100644
--- a/engines/grim/imuse/dimuse_engine.h
+++ b/engines/grim/imuse/imuse_engine.h
@@ -29,12 +29,12 @@
 #include "common/textconsole.h"
 #include "common/util.h"
 
-#include "engines/grim/imuse/dimuse_defs.h"
-#include "engines/grim/imuse/dimuse_internalmixer.h"
-#include "engines/grim/imuse/dimuse_groups.h"
-#include "engines/grim/imuse/dimuse_fades.h"
-#include "engines/grim/imuse/dimuse_triggers.h"
-#include "engines/grim/imuse/dimuse_tables.h"
+#include "engines/grim/imuse/imuse_defs.h"
+#include "engines/grim/imuse/imuse_internalmixer.h"
+#include "engines/grim/imuse/imuse_groups.h"
+#include "engines/grim/imuse/imuse_fades.h"
+#include "engines/grim/imuse/imuse_triggers.h"
+#include "engines/grim/imuse/imuse_tables.h"
 
 #include "audio/mixer.h"
 #include "audio/decoders/raw.h"
@@ -49,20 +49,20 @@ class QueuingAudioStream;
 
 namespace Grim {
 
-struct IMuseDigiStateTable;
-struct IMuseDigiDispatch;
-struct IMuseDigiTrack;
-struct IMuseDigiStreamZone;
+struct IMuseStateTable;
+struct IMuseDispatch;
+struct IMuseTrack;
+struct IMuseStreamZone;
 
-class IMuseDigital {
+class IMuse {
 private:
 	Common::Mutex *_mutex;
 	Audio::Mixer *_mixer;
 
-	IMuseDigiInternalMixer *_internalMixer;
-	IMuseDigiGroupsHandler *_groupsHandler;
-	IMuseDigiFadesHandler *_fadesHandler;
-	IMuseDigiTriggersHandler *_triggersHandler;
+	IMuseInternalMixer *_internalMixer;
+	IMuseGroupsHandler *_groupsHandler;
+	IMuseFadesHandler *_fadesHandler;
+	IMuseTriggersHandler *_triggersHandler;
 
 	int _callbackFps;
 	static void timer_handler(void *refConf);
@@ -81,7 +81,7 @@ private:
 	int _outputSampleRate;
 
 	// Used in low latency mode only
-	uint8 *_outputLowLatencyAudioBuffers[DIMUSE_MAX_TRACKS];
+	uint8 *_outputLowLatencyAudioBuffers[IMUSE_MAX_TRACKS];
 
 	int _maxQueuedStreams; // maximum number of streams which can be queued before they are played
 	int _nominalBufferCount;
@@ -100,10 +100,10 @@ private:
 
 	int _usecPerInt; // Microseconds between each callback (will be set to 50 Hz)
 	bool _callbackInterruptFlag;
-	void diMUSEHeartbeat();
+	void imHeartbeat();
 
-	bool isMusicStreamIdle();
-	bool isMusicCritical();
+	bool soundsIsMusicStreamIdle();
+	bool soundsIsMusicCritical();
 
 	// Script
 	int scriptParse(int cmd, int a, int b);
@@ -114,7 +114,7 @@ private:
 	void scriptRefresh();
 	void scriptSetState(int soundId);
 	void scriptSetSequence(int soundId);
-	void scriptPlayMusic(const IMuseDigiStateTable *tableEntry, int curSongEntryId, int isSequence);
+	void scriptPlayMusic(const IMuseStateTable *tableEntry, int curSongEntryId, int isSequence);
 	void scriptSetCuePoint(int cueId);
 	int scriptSetAttribute(int attrIndex, int attrVal);
 
@@ -125,27 +125,27 @@ private:
 	int _cmdsRunning5HzCount;
 
 	// Streamer
-	IMuseDigiStream _streams[DIMUSE_MAX_STREAMS];
-	IMuseDigiStream *_lastStreamLoaded;
+	IMuseStream _streams[IMUSE_MAX_STREAMS];
+	IMuseStream *_lastStreamLoaded;
 	int _streamerBailFlag;
 
 	int streamerInit();
-	IMuseDigiStream *streamerAllocateSound(int soundId, int bufId, int32 maxRead);
-	int streamerClearSoundInStream(IMuseDigiStream *streamPtr);
+	IMuseStream *streamerAllocateSound(int soundId, int bufId, int32 maxRead);
+	int streamerClearSoundInStream(IMuseStream *streamPtr);
 	int streamerProcessStreams();
-	uint8 *streamerGetStreamBuffer(IMuseDigiStream *streamPtr, int size);
-	uint8 *streamerGetStreamBufferAtOffset(IMuseDigiStream *streamPtr, int32 offset, int size);
-	int streamerSetReadIndex(IMuseDigiStream *streamPtr, int offset);
-	int streamerSetLoadIndex(IMuseDigiStream *streamPtr, int offset);
-	int streamerGetFreeBufferAmount(IMuseDigiStream *streamPtr);
-	int streamerSetSoundToStreamFromOffset(IMuseDigiStream *streamPtr, int soundId, int32 offset);
-	void streamerQueryStream(IMuseDigiStream *streamPtr, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
-	int streamerFeedStream(IMuseDigiStream *streamPtr, uint8 *srcBuf, int32 sizeToFeed, int paused);
-	int streamerFetchData(IMuseDigiStream *streamPtr);
+	uint8 *streamerGetStreamBuffer(IMuseStream *streamPtr, int size);
+	uint8 *streamerGetStreamBufferAtOffset(IMuseStream *streamPtr, int32 offset, int size);
+	int streamerSetReadIndex(IMuseStream *streamPtr, int offset);
+	int streamerSetLoadIndex(IMuseStream *streamPtr, int offset);
+	int streamerGetFreeBufferAmount(IMuseStream *streamPtr);
+	int streamerSetSoundToStreamFromOffset(IMuseStream *streamPtr, int soundId, int32 offset);
+	void streamerQueryStream(IMuseStream *streamPtr, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
+	int streamerFeedStream(IMuseStream *streamPtr, uint8 *srcBuf, int32 sizeToFeed, int paused);
+	int streamerFetchData(IMuseStream *streamPtr);
 
 	// Tracks
-	IMuseDigiTrack _tracks[DIMUSE_MAX_TRACKS];
-	IMuseDigiTrack *_trackList;
+	IMuseTrack _tracks[IMUSE_MAX_TRACKS];
+	IMuseTrack *_trackList;
 
 	int _trackCount;
 	int _tracksPauseTimer;
@@ -163,24 +163,24 @@ private:
 	int tracksGetNextSound(int soundId);
 	int tracksQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
 	int tracksFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused);
-	void tracksClear(IMuseDigiTrack *trackPtr);
+	void tracksClear(IMuseTrack *trackPtr);
 	int tracksSetParam(int soundId, int opcode, int value);
 	int tracksGetParam(int soundId, int opcode);
 	int tracksSetHook(int soundId, int hookId);
 	int tracksGetHook(int soundId);
-	IMuseDigiTrack *tracksReserveTrack(int priority);
+	IMuseTrack *tracksReserveTrack(int priority);
 	int tracksDeinit();
 
 	// Dispatch
-	IMuseDigiDispatch _dispatches[DIMUSE_MAX_DISPATCHES];
-	IMuseDigiStreamZone _streamZones[DIMUSE_MAX_STREAMZONES];
+	IMuseDispatch _dispatches[IMUSE_MAX_DISPATCHES];
+	IMuseStreamZone _streamZones[IMUSE_MAX_STREAMZONES];
 	uint8 *_dispatchBuffer;
 	int32 _dispatchSize;
 	uint8 *_dispatchSmallFadeBufs;
 	uint8 *_dispatchLargeFadeBufs;
 	int32 _dispatchFadeSize;
-	int _dispatchLargeFadeFlags[DIMUSE_LARGE_FADES];
-	int _dispatchSmallFadeFlags[DIMUSE_SMALL_FADES];
+	int _dispatchLargeFadeFlags[IMUSE_LARGE_FADES];
+	int _dispatchSmallFadeFlags[IMUSE_SMALL_FADES];
 	int _dispatchFadeStartedFlag;
 	int _dispatchBufferedHookId;
 	int32 _dispatchJumpFadeSize;
@@ -191,58 +191,58 @@ private:
 
 	int dispatchInit();
 	int dispatchTerminate();
-	IMuseDigiDispatch *dispatchGetDispatchByTrackId(int trackId);
+	IMuseDispatch *dispatchGetDispatchByTrackId(int trackId);
 	void dispatchSaveLoad(Common::Serializer &ser);
 	int dispatchRestoreStreamZones();
-	int dispatchAllocateSound(IMuseDigiTrack *trackPtr, int groupId);
-	int dispatchRelease(IMuseDigiTrack *trackPtr);
+	int dispatchAllocateSound(IMuseTrack *trackPtr, int groupId);
+	int dispatchRelease(IMuseTrack *trackPtr);
 	int dispatchSwitchStream(int oldSoundId, int newSoundId, int fadeLength, int exitTriggerSyncFlag, int offsetFadeSyncFlag);
-	void dispatchProcessDispatches(IMuseDigiTrack *trackPtr, int feedSize, int sampleRate);
+	void dispatchProcessDispatches(IMuseTrack *trackPtr, int feedSize, int sampleRate);
 	void dispatchPredictFirstStream();
-	int dispatchNavigateMap(IMuseDigiDispatch *dispatchPtr);
-	int dispatchGetMap(IMuseDigiDispatch *dispatchPtr);
+	int dispatchNavigateMap(IMuseDispatch *dispatchPtr);
+	int dispatchGetMap(IMuseDispatch *dispatchPtr);
 	int dispatchConvertMap(uint8 *rawMap, int32 *destMap);
 	uint8 *dispatchGetNextMapEvent(int32 *mapPtr, int32 soundOffset, uint8 *mapEvent);
-	void dispatchPredictStream(IMuseDigiDispatch *dispatchPtr);
-	uint8 *dispatchCheckForJump(int32 *mapPtr, IMuseDigiStreamZone *strZnPtr, int &candidateHookId);
-	void dispatchPrepareToJump(IMuseDigiDispatch *dispatchPtr, IMuseDigiStreamZone *strZnPtr, uint8 *jumpParamsFromMap, int calledFromGetNextMapEvent);
-	void dispatchStreamNextZone(IMuseDigiDispatch *dispatchPtr, IMuseDigiStreamZone *strZnPtr);
-	IMuseDigiStreamZone *dispatchAllocateStreamZone();
+	void dispatchPredictStream(IMuseDispatch *dispatchPtr);
+	uint8 *dispatchCheckForJump(int32 *mapPtr, IMuseStreamZone *strZnPtr, int &candidateHookId);
+	void dispatchPrepareToJump(IMuseDispatch *dispatchPtr, IMuseStreamZone *strZnPtr, uint8 *jumpParamsFromMap, int calledFromGetNextMapEvent);
+	void dispatchStreamNextZone(IMuseDispatch *dispatchPtr, IMuseStreamZone *strZnPtr);
+	IMuseStreamZone *dispatchAllocateStreamZone();
 	uint8 *dispatchAllocateFade(int32 &fadeSize, const char *functionName);
-	void dispatchDeallocateFade(IMuseDigiDispatch *dispatchPtr, const char *functionName);
-	int dispatchGetFadeSize(IMuseDigiDispatch *dispatchPtr, int fadeLength);
-	void dispatchValidateFadeSize(IMuseDigiDispatch *dispatchPtr, int32 &dispatchSize);
-	int dispatchUpdateFadeMixVolume(IMuseDigiDispatch *dispatchPtr, int32 remainingFade);
-	int dispatchUpdateFadeSlope(IMuseDigiDispatch *dispatchPtr);
+	void dispatchDeallocateFade(IMuseDispatch *dispatchPtr, const char *functionName);
+	int dispatchGetFadeSize(IMuseDispatch *dispatchPtr, int fadeLength);
+	void dispatchValidateFadeSize(IMuseDispatch *dispatchPtr, int32 &dispatchSize);
+	int dispatchUpdateFadeMixVolume(IMuseDispatch *dispatchPtr, int32 remainingFade);
+	int dispatchUpdateFadeSlope(IMuseDispatch *dispatchPtr);
 
 	// Files
-	IMuseDigiSoundList _mainSoundList[DIMUSE_MAX_SOUND_LIST];
-	IMuseDigiSoundList *_loadedSoundList;
-	IMuseDigiSoundList *_openedSoundsList;
+	IMuseSoundList _mainSoundList[IMUSE_MAX_SOUND_LIST];
+	IMuseSoundList *_loadedSoundList;
+	IMuseSoundList *_openedSoundsList;
 	bool _fileListInitialized;
 	uint16 _imuseDestTable[5786];
-	IMuseDigiOpenAudioFile _openAudioFiles[DIMUSE_MAX_OPEN_FILES];
-	IMuseDigiSndBuffer _soundBuffers[4];
-
-	int diMUSEInitFilelist();
-	void diMUSESaveLoadFilelist(Common::Serializer &ser);
-	int diMUSELoadSound(const char *soundName, int requestedSoundId);
-	void diMUSEUnloadSound(int soundId);
-	void diMUSEUnloadAll();
-	int diMUSEOpenSound(const char *filename, int requestedSoundId);
-	void diMUSECloseSound(int soundId);
-	void diMUSECloseAll();
-	int diMUSEFindSound(const char *soundName);
-	void diMUSEFlushSounds();
-	int diMUSEAddSoundToList(IMuseDigiSoundList **listPtr, IMuseDigiSoundList *item);
-	int diMUSERemoveSoundFromList(IMuseDigiSoundList **listPtr, IMuseDigiSoundList *item);
+	IMuseOpenAudioFile _openAudioFiles[IMUSE_MAX_OPEN_FILES];
+	IMuseSndBuffer _soundBuffers[4];
+
+	int imInitFilelist();
+	void imSaveLoadFilelist(Common::Serializer &ser);
+	int imLoadSound(const char *soundName, int requestedSoundId);
+	void imUnloadSound(int soundId);
+	void imUnloadAll();
+	int imOpenSound(const char *filename, int requestedSoundId);
+	void imCloseSound(int soundId);
+	void imCloseAll();
+	int imFindSound(const char *soundName);
+	void imFlushSounds();
+	int imAddSoundToList(IMuseSoundList **listPtr, IMuseSoundList *item);
+	int imRemoveSoundFromList(IMuseSoundList **listPtr, IMuseSoundList *item);
 
 	bool filesCheckRange(int soundId);
 	uint8 *filesGetSoundAddrData(int soundId);
 	uint8 *filesFetchMap(int soundId);
 	int filesSeek(int soundId, int32 offset, int mode);
 	int filesRead(int soundId, uint8 *buf, int32 size);
-	IMuseDigiSndBuffer *filesGetBufInfo(int bufId);
+	IMuseSndBuffer *filesGetBufInfo(int bufId);
 
 	int ihostLoadSound(const char *soundName, int requestedSoundId);
 	int ihostUnloadSound(int soundId);
@@ -250,11 +250,11 @@ private:
 	int ihostCloseSound(int soundId);
 	uint8 *ihostGetMapAddr(int soundId);
 	uint8 *ihostGetSoundAddr(int soundId);
-	IMuseDigiSndBuffer *ihostGetBufferInfo(int bufId);
+	IMuseSndBuffer *ihostGetBufferInfo(int bufId);
 	int ihostFseek(int soundId, int32 offset, int mode);
 	int ihostRead(int soundId, uint8 *destBuf, int32 size);
 
-	IMuseDigiCachedSound _soundCache[DIMUSE_MAX_CACHED_SOUNDS];
+	IMuseCachedSound _soundCache[IMUSE_MAX_CACHED_SOUNDS];
 	int _currentSoundSlot;
 
 	int cacheGetSoundId(const char *soundName);
@@ -265,18 +265,18 @@ private:
 
 	void soundsAllocateBuffer(int bufferId, int32 bufSize, int32 loadSize, int32 criticalSize);
 	void soundsDeallocateBuffer(int bufferId);
-	IMuseDigiResource *soundsOpenFile(const char *filename);
-	void soundsCloseFile(IMuseDigiResource *res);
-	void soundsFileSeek(IMuseDigiResource *res, int32 offset, int mode);
-	int32 soundsFileTell(IMuseDigiResource *res);
-	int soundsGetCompBlockId(IMuseDigiResource *res, int32 offset);
-	int32 copyDataFromResource(IMuseDigiResource *res, uint8 *dest, int32 size);
+	IMuseResource *soundsOpenFile(const char *filename);
+	void soundsCloseFile(IMuseResource *res);
+	void soundsFileSeek(IMuseResource *res, int32 offset, int mode);
+	int32 soundsFileTell(IMuseResource *res);
+	int soundsGetCompBlockId(IMuseResource *res, int32 offset);
+	int32 copyDataFromResource(IMuseResource *res, uint8 *dest, int32 size);
 
 	// Voice and lipsync
 	char _curSpeechFile[32];
 	int32 _millisecsInCurSpeechFile;
-	int _lipsyncSoundIds[DIMUSE_MAX_LIPSYNCS];
-	uint8 _lipsyncBufs[DIMUSE_MAX_LIPSYNCS][DIMUSE_LIPSYNC_MAX_SIZE + 48];
+	int _lipsyncSoundIds[IMUSE_MAX_LIPSYNCS];
+	uint8 _lipsyncBufs[IMUSE_MAX_LIPSYNCS][IMUSE_LIPSYNC_MAX_SIZE + 48];
 	int _globalVolume;
 
 	int soundsRegisterVoice(const char *filename);
@@ -339,8 +339,8 @@ private:
 	uint8 *_waveOutLowLatencyOutputBuffer;
 
 public:
-	IMuseDigital(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode = false);
-	~IMuseDigital();
+	IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode = false);
+	~IMuse();
 
 	// Wrapper functions used by the main engine
 
@@ -357,9 +357,9 @@ public:
 	void pause(bool pause);
 	void disableEngine();
 	bool isEngineDisabled();
-	void floodMusicBuffer();
-	void fillStreamsWhileMusicCritical(int fillTimesAfter);
-	bool queryNextSoundFile(int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
+	void soundsFloodMusicBuffer();
+	void soundsFillStreamsWhileMusicCritical(int fillTimesAfter);
+	bool queryMusicStream(int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
 	int getSampleRate();
 	int getFeedSize();
 
@@ -392,64 +392,64 @@ public:
 	void tracksSetGroupVol();
 
 	// General engine functions
-	int diMUSETerminate();
-	int diMUSEInitialize();
-	void diMUSEPause();
-	void diMUSEResume();
-	int diMUSESaveLoad(Common::Serializer &ser);
-	int diMUSESetGroupVol(int groupId, int volume);
-	int diMUSEStartSound(int soundId, int priority);
-	int diMUSEStopSound(int soundId);
-	int diMUSEStopAllSounds();
-	int diMUSEGetNextSound(int soundId);
-	int diMUSESetParam(int soundId, int paramId, int value);
-	int diMUSEGetParam(int soundId, int paramId);
-	int diMUSEFadeParam(int soundId, int opcode, int destValue, int fadeLength);
-	int diMUSESetHook(int soundId, int hookId);
-	int diMUSEGetHook(int soundId);
-
-	int diMUSESetTrigger(int soundId, const char *marker, int opcode,
+	int imTerminate();
+	int imInitialize();
+	void imPause();
+	void imResume();
+	int imSaveLoad(Common::Serializer &ser);
+	int imSetGroupVol(int groupId, int volume);
+	int imStartSound(int soundId, int priority);
+	int imStopSound(int soundId);
+	int imStopAllSounds();
+	int imGetNextSound(int soundId);
+	int imSetParam(int soundId, int paramId, int value);
+	int imGetParam(int soundId, int paramId);
+	int imFadeParam(int soundId, int opcode, int destValue, int fadeLength);
+	int imSetHook(int soundId, int hookId);
+	int imGetHook(int soundId);
+
+	int imSetTrigger(int soundId, const char *marker, int opcode,
 		int d = -1, int e = -1, int f = -1, int g = -1,
 		int h = -1, int i = -1, int j = -1, int k = -1,
 		int l = -1, int m = -1, int n = -1);
-	int diMUSECheckTrigger(int soundId, const char *marker, int opcode);
-	int diMUSEClearTrigger(int soundId, const char *marker, int opcode);
-	int diMUSEDeferCommand(int count, int opcode, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n);
-
-	int diMUSEStartStream(int soundId, int priority, int bufferId);
-	int diMUSESwitchStream(int oldSoundId, int newSoundId, int fadeDelay, int fadeSyncFlag2, int fadeSyncFlag1);
-	int diMUSEProcessStreams();
-	int diMUSEQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
-	int diMUSEFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused);
-	int diMUSEGetMusicGroupVol();
-	int diMUSEGetSFXGroupVol();
-	int diMUSEGetVoiceGroupVol();
-	int diMUSESetMusicGroupVol(int volume);
-	int diMUSESetSFXGroupVol(int volume);
-	int diMUSESetVoiceGroupVol(int volume);
-	int diMUSEInitializeScript();
-	int diMUSETerminateScript();
-	void diMUSESaveLoadScript(Common::Serializer &ser);
-	void diMUSERefreshScript();
-	int diMUSESetState(int soundId);
-	int diMUSESetSequence(int soundId);
-	int diMUSESetCuePoint(int cueId);
-	int diMUSESetAttribute(int attrIndex, int attrVal);
-	void diMUSEEnableSpooledMusic();
-	void diMUSEDisableSpooledMusic();
+	int imCheckTrigger(int soundId, const char *marker, int opcode);
+	int imClearTrigger(int soundId, const char *marker, int opcode);
+	int imDeferCommand(int count, int opcode, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n);
+
+	int imStartStream(int soundId, int priority, int bufferId);
+	int imSwitchStream(int oldSoundId, int newSoundId, int fadeDelay, int fadeSyncFlag2, int fadeSyncFlag1);
+	int imProcessStreams();
+	int imQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
+	int imFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused);
+	int getMusicGroupVol();
+	int getSFXGroupVol();
+	int getVoiceGroupVol();
+	int setMusicGroupVol(int volume);
+	int setSFXGroupVol(int volume);
+	int setVoiceGroupVol(int volume);
+	int imInitializeScript();
+	int imTerminateScript();
+	void imSaveLoadScript(Common::Serializer &ser);
+	void imRefreshScript();
+	int imSetState(int soundId);
+	int imSetSequence(int soundId);
+	int imSetCuePoint(int cueId);
+	int imSetAttribute(int attrIndex, int attrVal);
+	void enableSpooledMusic();
+	void disableSpooledMusic();
 
 	// Utils
-	int addTrackToList(IMuseDigiTrack **listPtr, IMuseDigiTrack *listPtr_Item);
-	int removeTrackFromList(IMuseDigiTrack **listPtr, IMuseDigiTrack *itemPtr);
-	int addStreamZoneToList(IMuseDigiStreamZone **listPtr, IMuseDigiStreamZone *listPtr_Item);
-	int removeStreamZoneFromList(IMuseDigiStreamZone **listPtr, IMuseDigiStreamZone *itemPtr);
+	int addTrackToList(IMuseTrack **listPtr, IMuseTrack *listPtr_Item);
+	int removeTrackFromList(IMuseTrack **listPtr, IMuseTrack *itemPtr);
+	int addStreamZoneToList(IMuseStreamZone **listPtr, IMuseStreamZone *listPtr_Item);
+	int removeStreamZoneFromList(IMuseStreamZone **listPtr, IMuseStreamZone *itemPtr);
 	int clampNumber(int value, int minValue, int maxValue);
 	int checkHookId(int &trackHookId, int sampleHookId);
 	int roundRobinSetBufferCount();
 	void adaptBufferCount();
 
 	// CMDs
-	int cmdsHandleCmd(int cmd, uint8 *ptr = nullptr,
+	int imSoundCall(int cmd, uint8 *ptr = nullptr,
 		int a = -1, int b = -1, int c = -1, int d = -1, int e = -1,
 		int f = -1, int g = -1, int h = -1, int i = -1, int j = -1,
 		int k = -1, int l = -1, int m = -1, int n = -1);
@@ -465,7 +465,7 @@ public:
 	void listGroups();
 };
 
-extern IMuseDigital *g_imuse;
+extern IMuse *g_imuse;
 
 } // End of namespace Grim
 
diff --git a/engines/grim/imuse/dimuse_fades.cpp b/engines/grim/imuse/imuse_fades.cpp
similarity index 67%
rename from engines/grim/imuse/dimuse_fades.cpp
rename to engines/grim/imuse/imuse_fades.cpp
index c41b26a0477..ee8d53e4411 100644
--- a/engines/grim/imuse/dimuse_fades.cpp
+++ b/engines/grim/imuse/imuse_fades.cpp
@@ -19,30 +19,30 @@
  *
  */
 
-#include "engines/grim/imuse/dimuse_engine.h"
-#include "engines/grim/imuse/dimuse_fades.h"
+#include "engines/grim/imuse/imuse_engine.h"
+#include "engines/grim/imuse/imuse_fades.h"
 
 namespace Grim {
 
-IMuseDigiFadesHandler::IMuseDigiFadesHandler(IMuseDigital *engine, Common::Mutex *mutex) {
+IMuseFadesHandler::IMuseFadesHandler(IMuse *engine, Common::Mutex *mutex) {
 	_engine = engine;
 	_mutex = mutex;
 }
 
-IMuseDigiFadesHandler::~IMuseDigiFadesHandler() {}
+IMuseFadesHandler::~IMuseFadesHandler() {}
 
-int IMuseDigiFadesHandler::init() {
+int IMuseFadesHandler::init() {
 	clearAllFades();
 	return 0;
 }
 
-int IMuseDigiFadesHandler::fadeParam(int soundId, int opcode, int destinationValue, int fadeLength) {
+int IMuseFadesHandler::fadeParam(int soundId, int opcode, int destinationValue, int fadeLength) {
 	Common::StackLock lock(*_mutex);
 
 	if (!soundId || fadeLength < 0)
 		return -5;
 
-	if (opcode != DIMUSE_P_PRIORITY && opcode != DIMUSE_P_VOLUME && opcode != DIMUSE_P_PAN && opcode != DIMUSE_P_DETUNE)
+	if (opcode != IMUSE_P_PRIORITY && opcode != IMUSE_P_VOLUME && opcode != IMUSE_P_PAN && opcode != IMUSE_P_DETUNE)
 		return -5;
 
 	clearFadeStatus(soundId, opcode);
@@ -50,21 +50,21 @@ int IMuseDigiFadesHandler::fadeParam(int soundId, int opcode, int destinationVal
 	int len50HzTicks = 5 * fadeLength / 6;
 
 	if (!len50HzTicks) {
-		debug(5, "IMuseDigiFadesHandler::fadeParam(): WARNING: allocated fade with zero length for sound %d", soundId);
-		if (opcode != DIMUSE_P_VOLUME || destinationValue) {
-			_engine->diMUSESetParam(soundId, opcode, destinationValue);
+		debug(5, "IMuseFadesHandler::fadeParam(): WARNING: allocated fade with zero length for sound %d", soundId);
+		if (opcode != IMUSE_P_VOLUME || destinationValue) {
+			_engine->imSetParam(soundId, opcode, destinationValue);
 		} else {
-			_engine->diMUSEStopSound(soundId);
+			_engine->imStopSound(soundId);
 		}
 
 		return 0;
 	}
 
-	for (int l = 0; l < DIMUSE_MAX_FADES; l++) {
+	for (int l = 0; l < IMUSE_MAX_FADES; l++) {
 		if (!_fades[l].status) {
 			_fades[l].sound = soundId;
 			_fades[l].param = opcode;
-			_fades[l].currentVal = _engine->diMUSEGetParam(soundId, opcode);
+			_fades[l].currentVal = _engine->imGetParam(soundId, opcode);
 			_fades[l].length = len50HzTicks;
 			_fades[l].counter = len50HzTicks;
 			_fades[l].slope = (destinationValue - _fades[l].currentVal) / len50HzTicks;
@@ -84,12 +84,12 @@ int IMuseDigiFadesHandler::fadeParam(int soundId, int opcode, int destinationVal
 		}
 	}
 
-	debug(5, "IMuseDigiFadesHandler::fadeParam(): unable to allocate fade for sound %d", soundId);
+	debug(5, "IMuseFadesHandler::fadeParam(): unable to allocate fade for sound %d", soundId);
 	return -6;
 }
 
-void IMuseDigiFadesHandler::clearFadeStatus(int soundId, int opcode) {
-	for (int l = 0; l < DIMUSE_MAX_FADES; l++) {
+void IMuseFadesHandler::clearFadeStatus(int soundId, int opcode) {
+	for (int l = 0; l < IMUSE_MAX_FADES; l++) {
 		if (_fades[l].status
 			&& _fades[l].sound == soundId
 			&& (_fades[l].param == opcode || opcode == -1)) {
@@ -98,13 +98,13 @@ void IMuseDigiFadesHandler::clearFadeStatus(int soundId, int opcode) {
 	}
 }
 
-void IMuseDigiFadesHandler::loop() {
+void IMuseFadesHandler::loop() {
 	if (!_fadesOn)
 		return;
 
 	_fadesOn = 0;
 
-	for (int l = 0; l < DIMUSE_MAX_FADES; l++) {
+	for (int l = 0; l < IMUSE_MAX_FADES; l++) {
 		if (_fades[l].status) {
 			_fadesOn = 1;
 			if (--_fades[l].counter == 0) {
@@ -124,11 +124,11 @@ void IMuseDigiFadesHandler::loop() {
 				_fades[l].currentVal = currentVolume;
 
 				if (!(_fades[l].counter % 5)) {
-					debug(5, "IMuseDigiFadesHandler::loop(): running fade for sound %d with id %d, currently at volume %d", _fades[l].sound, l, currentVolume);
-					if ((_fades[l].param != DIMUSE_P_VOLUME) || currentVolume) {
-						_engine->diMUSESetParam(_fades[l].sound, _fades[l].param, currentVolume);
+					debug(5, "IMuseFadesHandler::loop(): running fade for sound %d with id %d, currently at volume %d", _fades[l].sound, l, currentVolume);
+					if ((_fades[l].param != IMUSE_P_VOLUME) || currentVolume) {
+						_engine->imSetParam(_fades[l].sound, _fades[l].param, currentVolume);
 					} else {
-						_engine->diMUSEStopSound(_fades[l].sound);
+						_engine->imStopSound(_fades[l].sound);
 					}
 				}
 			}
@@ -136,8 +136,8 @@ void IMuseDigiFadesHandler::loop() {
 	}
 }
 
-void IMuseDigiFadesHandler::saveLoad(Common::Serializer &ser) {
-	for (int l = 0; l < DIMUSE_MAX_FADES; l++) {
+void IMuseFadesHandler::saveLoad(Common::Serializer &ser) {
+	for (int l = 0; l < IMUSE_MAX_FADES; l++) {
 		ser.syncAsSint32LE(_fades[l].status, VER(30));
 		ser.syncAsSint32LE(_fades[l].sound, VER(30));
 		ser.syncAsSint32LE(_fades[l].param, VER(30));
@@ -154,10 +154,10 @@ void IMuseDigiFadesHandler::saveLoad(Common::Serializer &ser) {
 		_fadesOn = 1;
 }
 
-void IMuseDigiFadesHandler::clearAllFades() {
+void IMuseFadesHandler::clearAllFades() {
 	Common::StackLock lock(*_mutex);
 
-	for (int l = 0; l < DIMUSE_MAX_FADES; l++) {
+	for (int l = 0; l < IMUSE_MAX_FADES; l++) {
 		_fades[l].status = 0;
 		_fades[l].sound = 0;
 		_fades[l].param = 0;
diff --git a/engines/grim/imuse/dimuse_fades.h b/engines/grim/imuse/imuse_fades.h
similarity index 87%
rename from engines/grim/imuse/dimuse_fades.h
rename to engines/grim/imuse/imuse_fades.h
index f8997edfeea..8cf1eb49610 100644
--- a/engines/grim/imuse/dimuse_fades.h
+++ b/engines/grim/imuse/imuse_fades.h
@@ -28,18 +28,18 @@
 
 namespace Grim {
 
-class IMuseDigiFadesHandler {
+class IMuseFadesHandler {
 
 private:
-	IMuseDigital *_engine;
+	IMuse *_engine;
 	Common::Mutex *_mutex;
-	IMuseDigiFade _fades[DIMUSE_MAX_FADES] = {};
+	IMuseFade _fades[IMUSE_MAX_FADES] = {};
 	int _fadesOn = 0;
 
 	void clearAllFades();
 public:
-	IMuseDigiFadesHandler(IMuseDigital *engine, Common::Mutex *mutex);
-	~IMuseDigiFadesHandler();
+	IMuseFadesHandler(IMuse *engine, Common::Mutex *mutex);
+	~IMuseFadesHandler();
 
 	int init();
 	void saveLoad(Common::Serializer &ser);
diff --git a/engines/grim/imuse/dimuse_files.cpp b/engines/grim/imuse/imuse_files.cpp
similarity index 75%
rename from engines/grim/imuse/dimuse_files.cpp
rename to engines/grim/imuse/imuse_files.cpp
index 791d77aa35a..df9162a8d4c 100644
--- a/engines/grim/imuse/dimuse_files.cpp
+++ b/engines/grim/imuse/imuse_files.cpp
@@ -24,12 +24,12 @@
 
 #include "engines/grim/resource.h"
 #include "engines/grim/movie/codecs/vima.h"
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 
 namespace Grim {
 
-int IMuseDigital::diMUSEInitFilelist() {
-	for (int i = 0; i < DIMUSE_MAX_SOUND_LIST; i++) {
+int IMuse::imInitFilelist() {
+	for (int i = 0; i < IMUSE_MAX_SOUND_LIST; i++) {
 		_mainSoundList[i].prev = nullptr;
 		_mainSoundList[i].next = nullptr;
 		_mainSoundList[i].soundId = 0;
@@ -39,8 +39,8 @@ int IMuseDigital::diMUSEInitFilelist() {
 	return 0;
 }
 
-void IMuseDigital::diMUSESaveLoadFilelist(Common::Serializer &ser) {
-	IMuseDigiSoundList *sound;
+void IMuse::imSaveLoadFilelist(Common::Serializer &ser) {
+	IMuseSoundList *sound;
 	int loadedCount = 0;
 	int openedCount = 0;
 	int soundId = 0;
@@ -54,7 +54,7 @@ void IMuseDigital::diMUSESaveLoadFilelist(Common::Serializer &ser) {
 		for (sound = _openedSoundsList; sound; sound = sound->next)
 			openedCount++;
 	} else {
-		for (int i = 0; i < DIMUSE_MAX_SOUND_LIST; i++) {
+		for (int i = 0; i < IMUSE_MAX_SOUND_LIST; i++) {
 			_mainSoundList[i].prev = nullptr;
 			_mainSoundList[i].next = nullptr;
 			_mainSoundList[i].soundId = 0;
@@ -78,13 +78,13 @@ void IMuseDigital::diMUSESaveLoadFilelist(Common::Serializer &ser) {
 		ser.syncAsSint32LE(refCount, VER(30));
 
 		if (ser.isLoading()) {
-			if (!diMUSELoadSound(filename, soundId)) {
-				debug(5, "IMuseDigital::diMUSESaveLoadFilelist(): ERROR: couldn't load file %s", filename);
+			if (!imLoadSound(filename, soundId)) {
+				debug(5, "IMuse::imSaveLoadFilelist(): ERROR: couldn't load file %s", filename);
 				return;
 			}
 
 			if (soundId != _loadedSoundList->soundId) {
-				debug(5, "IMuseDigital::diMUSESaveLoadFilelist(): ERROR: detected modified sound number");
+				debug(5, "IMuse::imSaveLoadFilelist(): ERROR: detected modified sound number");
 				return;
 			}
 
@@ -106,12 +106,12 @@ void IMuseDigital::diMUSESaveLoadFilelist(Common::Serializer &ser) {
 		ser.syncAsSint32LE(refCount, VER(30));
 
 		if (ser.isLoading()) {
-			if (!diMUSEOpenSound(filename, soundId)) {
-				debug(5, "IMuseDigital::diMUSESaveLoadFilelist(): ERROR: couldn't open file %s", filename);
+			if (!imOpenSound(filename, soundId)) {
+				debug(5, "IMuse::imSaveLoadFilelist(): ERROR: couldn't open file %s", filename);
 			}
 
 			if (soundId != _openedSoundsList->soundId) {
-				debug(5, "IMuseDigital::diMUSESaveLoadFilelist(): ERROR: detected modified sound number");
+				debug(5, "IMuse::imSaveLoadFilelist(): ERROR: detected modified sound number");
 				return;
 			}
 
@@ -120,15 +120,15 @@ void IMuseDigital::diMUSESaveLoadFilelist(Common::Serializer &ser) {
 	}
 }
 
-int IMuseDigital::diMUSELoadSound(const char *soundName, int requestedSoundId) {
-	IMuseDigiSoundList *sound;
+int IMuse::imLoadSound(const char *soundName, int requestedSoundId) {
+	IMuseSoundList *sound;
 	int soundId;
 	int nameIndex;
 
 	if (!_fileListInitialized || !*soundName)
 		return 0;
 
-	soundId = diMUSEFindSound(soundName);
+	soundId = imFindSound(soundName);
 	if (soundId && _loadedSoundList) {
 		sound = _loadedSoundList;
 		while (soundId != sound->soundId) {
@@ -146,8 +146,8 @@ int IMuseDigital::diMUSELoadSound(const char *soundName, int requestedSoundId) {
 
 	sound = _mainSoundList;
 	while (sound->soundId) {
-		if (++sound >= &_mainSoundList[DIMUSE_MAX_SOUND_LIST]) {
-			debug(5, "IMuseDigital::diMUSELoadSound(): Sound List FULL!");
+		if (++sound >= &_mainSoundList[IMUSE_MAX_SOUND_LIST]) {
+			debug(5, "IMuse::imLoadSound(): Sound List FULL!");
 			return 0;
 		}
 	}
@@ -164,20 +164,20 @@ int IMuseDigital::diMUSELoadSound(const char *soundName, int requestedSoundId) {
 			sound->filename[nameIndex] = 0;
 			sound->soundId = soundId;
 			sound->refCount = 1;
-			diMUSEAddSoundToList(&_loadedSoundList, sound);
+			imAddSoundToList(&_loadedSoundList, sound);
 			return soundId;
 		}
 
-		debug(5, "IMuseDigital::diMUSELoadSound(): Name too long: %s", soundName);
+		debug(5, "IMuse::imLoadSound(): Name too long: %s", soundName);
 	} else {
-		debug(5, "IMuseDigital::diMUSELoadSound(): Host couldn't load sound %s", soundName);
+		debug(5, "IMuse::imLoadSound(): Host couldn't load sound %s", soundName);
 	}
 
 	return 0;
 }
 
-void IMuseDigital::diMUSEUnloadSound(int soundId) {
-	IMuseDigiSoundList *sound;
+void IMuse::imUnloadSound(int soundId) {
+	IMuseSoundList *sound;
 
 	if (_fileListInitialized) {
 		sound = _loadedSoundList;
@@ -192,30 +192,30 @@ void IMuseDigital::diMUSEUnloadSound(int soundId) {
 			sound = sound->next;
 		}
 
-		diMUSEFlushSounds();
+		imFlushSounds();
 	}
 }
 
-void IMuseDigital::diMUSEUnloadAll() {
-	IMuseDigiSoundList *sound;
+void IMuse::imUnloadAll() {
+	IMuseSoundList *sound;
 
 	if (_fileListInitialized) {
 		for (sound = _loadedSoundList; sound; sound = sound->next)
 			sound->refCount = 0;
 
-		diMUSEFlushSounds();
+		imFlushSounds();
 	}
 }
 
-int IMuseDigital::diMUSEOpenSound(const char *filename, int requestedSoundId) {
-	IMuseDigiSoundList *sound;
+int IMuse::imOpenSound(const char *filename, int requestedSoundId) {
+	IMuseSoundList *sound;
 	int soundId;
 	int nameIndex;
 
 	if (!_fileListInitialized || !*filename)
 		return 0;
 
-	soundId = diMUSEFindSound(filename);
+	soundId = imFindSound(filename);
 	if (soundId && _openedSoundsList) {
 		sound = _openedSoundsList;
 		while (soundId != sound->soundId) {
@@ -232,8 +232,8 @@ int IMuseDigital::diMUSEOpenSound(const char *filename, int requestedSoundId) {
 
 	sound = _mainSoundList;
 	while (sound->soundId) {
-		if (++sound >= &_mainSoundList[DIMUSE_MAX_SOUND_LIST]) {
-			debug(5, "IMuseDigital::diMUSEOpenSound(): Sound List FULL!");
+		if (++sound >= &_mainSoundList[IMUSE_MAX_SOUND_LIST]) {
+			debug(5, "IMuse::imOpenSound(): Sound List FULL!");
 			return 0;
 		}
 	}
@@ -251,20 +251,20 @@ int IMuseDigital::diMUSEOpenSound(const char *filename, int requestedSoundId) {
 			sound->filename[nameIndex] = 0;
 			sound->soundId = soundId;
 			sound->refCount = 1;
-			diMUSEAddSoundToList(&_openedSoundsList, sound);
+			imAddSoundToList(&_openedSoundsList, sound);
 			return soundId;
 		}
 
-		debug(5, "IMuseDigital::diMUSEOpenSound(): Name too long: %s", filename);
+		debug(5, "IMuse::imOpenSound(): Name too long: %s", filename);
 	} else {
-		debug(5, "IMuseDigital::diMUSEOpenSound(): Host couldn't open sound %s", filename);
+		debug(5, "IMuse::imOpenSound(): Host couldn't open sound %s", filename);
 	}
 
 	return 0;
 }
 
-void IMuseDigital::diMUSECloseSound(int soundId) {
-	IMuseDigiSoundList *sound;
+void IMuse::imCloseSound(int soundId) {
+	IMuseSoundList *sound;
 
 	if (_fileListInitialized) {
 		sound = _openedSoundsList;
@@ -277,23 +277,23 @@ void IMuseDigital::diMUSECloseSound(int soundId) {
 			sound = sound->next;
 		}
 
-		diMUSEFlushSounds();
+		imFlushSounds();
 	}
 }
 
-void IMuseDigital::diMUSECloseAll() {
-	IMuseDigiSoundList *sound;
+void IMuse::imCloseAll() {
+	IMuseSoundList *sound;
 
 	if (_fileListInitialized) {
 		for (sound = _openedSoundsList; sound; sound = sound->next)
 			sound->refCount = 0;
 
-		diMUSEFlushSounds();
+		imFlushSounds();
 	}
 }
 
-int IMuseDigital::diMUSEFindSound(const char *soundName) {
-	IMuseDigiSoundList *sound;
+int IMuse::imFindSound(const char *soundName) {
+	IMuseSoundList *sound;
 
 	for (sound = _loadedSoundList; sound; sound = sound->next) {
 		if (*soundName && !strcmp(sound->filename, soundName))
@@ -308,31 +308,31 @@ int IMuseDigital::diMUSEFindSound(const char *soundName) {
 	return 0;
 }
 
-void IMuseDigital::diMUSEFlushSounds() {
-	IMuseDigiSoundList *sound, *next;
+void IMuse::imFlushSounds() {
+	IMuseSoundList *sound, *next;
 
 	for (sound = _loadedSoundList; sound; sound = next) {
 		next = sound->next;
-		if (!sound->refCount && !diMUSEGetParam(sound->soundId, DIMUSE_P_SND_TRACK_NUM) && !diMUSEGetParam(sound->soundId, DIMUSE_P_TRIGS_SNDS)) {
+		if (!sound->refCount && !imGetParam(sound->soundId, IMUSE_P_SND_TRACK_NUM) && !imGetParam(sound->soundId, IMUSE_P_TRIGS_SNDS)) {
 			ihostUnloadSound(sound->soundId);
 			sound->soundId = 0;
-			diMUSERemoveSoundFromList(&_loadedSoundList, sound);
+			imRemoveSoundFromList(&_loadedSoundList, sound);
 		}
 	}
 
 	for (sound = _openedSoundsList; sound; sound = next) {
 		next = sound->next;
-		if (!sound->refCount && !diMUSEGetParam(sound->soundId, DIMUSE_P_SND_TRACK_NUM) && !diMUSEGetParam(sound->soundId, DIMUSE_P_TRIGS_SNDS)) {
+		if (!sound->refCount && !imGetParam(sound->soundId, IMUSE_P_SND_TRACK_NUM) && !imGetParam(sound->soundId, IMUSE_P_TRIGS_SNDS)) {
 			ihostCloseSound(sound->soundId);
 			sound->soundId = 0;
-			diMUSERemoveSoundFromList(&_openedSoundsList, sound);
+			imRemoveSoundFromList(&_openedSoundsList, sound);
 		}
 	}
 }
 
-int IMuseDigital::diMUSEAddSoundToList(IMuseDigiSoundList **listPtr, IMuseDigiSoundList *item) {
+int IMuse::imAddSoundToList(IMuseSoundList **listPtr, IMuseSoundList *item) {
 	if (!item || item->prev || item->next) {
-		debug(5, "IMuseDigital::diMUSEAddSoundToList(): ERROR: list arg err when adding");
+		debug(5, "IMuse::imAddSoundToList(): ERROR: list arg err when adding");
 		return -5;
 	}
 
@@ -347,8 +347,8 @@ int IMuseDigital::diMUSEAddSoundToList(IMuseDigiSoundList **listPtr, IMuseDigiSo
 	return 0;
 }
 
-int IMuseDigital::diMUSERemoveSoundFromList(IMuseDigiSoundList **listPtr, IMuseDigiSoundList *item) {
-	IMuseDigiSoundList *curItem = *listPtr;
+int IMuse::imRemoveSoundFromList(IMuseSoundList **listPtr, IMuseSoundList *item) {
+	IMuseSoundList *curItem = *listPtr;
 
 	if (item && curItem) {
 		while (curItem) {
@@ -371,65 +371,65 @@ int IMuseDigital::diMUSERemoveSoundFromList(IMuseDigiSoundList **listPtr, IMuseD
 
 			return 0;
 		} else {
-			debug(5, "IMuseDigital::diMUSERemoveSoundFromList(): ERROR: item not on list");
+			debug(5, "IMuse::imRemoveSoundFromList(): ERROR: item not on list");
 			return -3;
 		}
 	} else {
-		debug(5, "IMuseDigital::diMUSERemoveSoundFromList(): ERROR: list arg err when removing");
+		debug(5, "IMuse::imRemoveSoundFromList(): ERROR: list arg err when removing");
 		return -5;
 	}
 }
 
-bool IMuseDigital::filesCheckRange(int soundId) {
+bool IMuse::filesCheckRange(int soundId) {
 	return soundId > 0;
 }
 
-uint8 *IMuseDigital::filesGetSoundAddrData(int soundId) {
+uint8 *IMuse::filesGetSoundAddrData(int soundId) {
 	if (filesCheckRange(soundId))
 		return ihostGetSoundAddr(soundId);
 
 	return nullptr;
 }
 
-uint8 *IMuseDigital::filesFetchMap(int soundId) {
+uint8 *IMuse::filesFetchMap(int soundId) {
 	if (filesCheckRange(soundId))
 		return ihostGetMapAddr(soundId);
 
 	return nullptr;
 }
 
-int IMuseDigital::filesSeek(int soundId, int32 offset, int mode) {
+int IMuse::filesSeek(int soundId, int32 offset, int mode) {
 	if (filesCheckRange(soundId))
 		return ihostFseek(soundId, offset, mode);
 
 	return 0;
 }
 
-int IMuseDigital::filesRead(int soundId, uint8 *buf, int32 size) {
+int IMuse::filesRead(int soundId, uint8 *buf, int32 size) {
 	if (filesCheckRange(soundId))
 		return ihostRead(soundId, buf, size);
 
 	return 0;
 }
 
-IMuseDigiSndBuffer *IMuseDigital::filesGetBufInfo(int bufId) {
+IMuseSndBuffer *IMuse::filesGetBufInfo(int bufId) {
 	if (bufId)
 		return ihostGetBufferInfo(bufId);
 
 	return nullptr;
 }
 
-int IMuseDigital::ihostLoadSound(const char *soundName, int requestedSoundId) {
+int IMuse::ihostLoadSound(const char *soundName, int requestedSoundId) {
 	return 0;
 }
 
-int IMuseDigital::ihostUnloadSound(int soundId) {
+int IMuse::ihostUnloadSound(int soundId) {
 	return 0;
 }
 
-int IMuseDigital::ihostOpenSound(const char *filename, int requestedSoundId) {
+int IMuse::ihostOpenSound(const char *filename, int requestedSoundId) {
 	Common::StackLock lock(*_mutex);
-	IMuseDigiResource *res;
+	IMuseResource *res;
 	int index;
 
 	if (requestedSoundId) {
@@ -440,7 +440,7 @@ int IMuseDigital::ihostOpenSound(const char *filename, int requestedSoundId) {
 		return requestedSoundId;
 	}
 
-	for (index = 1; index < DIMUSE_MAX_OPEN_FILES; index++) {
+	for (index = 1; index < IMUSE_MAX_OPEN_FILES; index++) {
 		if (!_openAudioFiles[index].resourcePtr)
 			break;
 
@@ -450,7 +450,7 @@ int IMuseDigital::ihostOpenSound(const char *filename, int requestedSoundId) {
 		}
 	}
 
-	if (index >= DIMUSE_MAX_OPEN_FILES)
+	if (index >= IMUSE_MAX_OPEN_FILES)
 		return 0;
 
 	res = soundsOpenFile(filename);
@@ -464,7 +464,7 @@ int IMuseDigital::ihostOpenSound(const char *filename, int requestedSoundId) {
 	return 0;
 }
 
-int IMuseDigital::ihostCloseSound(int soundId) {
+int IMuse::ihostCloseSound(int soundId) {
 	Common::StackLock lock(*_mutex);
 	int index = soundId - 10000;
 
@@ -483,34 +483,34 @@ int IMuseDigital::ihostCloseSound(int soundId) {
 	return 0;
 }
 
-uint8 *IMuseDigital::ihostGetMapAddr(int soundId) {
-	if (soundId < 100 || soundId >= 100 + DIMUSE_MAX_CACHED_SOUNDS)
+uint8 *IMuse::ihostGetMapAddr(int soundId) {
+	if (soundId < 100 || soundId >= 100 + IMUSE_MAX_CACHED_SOUNDS)
 		return nullptr;
 
 	return _soundCache[soundId - 100].soundMap;
 }
 
-uint8 *IMuseDigital::ihostGetSoundAddr(int soundId) {
-	if (soundId < 100 || soundId >= 100 + DIMUSE_MAX_CACHED_SOUNDS)
+uint8 *IMuse::ihostGetSoundAddr(int soundId) {
+	if (soundId < 100 || soundId >= 100 + IMUSE_MAX_CACHED_SOUNDS)
 		return nullptr;
 
 	return _soundCache[soundId - 100].soundAddrData;
 }
 
-IMuseDigiSndBuffer *IMuseDigital::ihostGetBufferInfo(int bufId) {
+IMuseSndBuffer *IMuse::ihostGetBufferInfo(int bufId) {
 	return &_soundBuffers[bufId];
 }
 
-int IMuseDigital::ihostFseek(int soundId, int32 offset, int mode) {
+int IMuse::ihostFseek(int soundId, int32 offset, int mode) {
 	Common::StackLock lock(*_mutex);
 
-	if (soundId >= 10000 && soundId < 10000 + DIMUSE_MAX_OPEN_FILES) {
-		IMuseDigiResource *res = _openAudioFiles[soundId - 10000].resourcePtr;
+	if (soundId >= 10000 && soundId < 10000 + IMUSE_MAX_OPEN_FILES) {
+		IMuseResource *res = _openAudioFiles[soundId - 10000].resourcePtr;
 		if (res) {
 			soundsFileSeek(res, offset, mode);
 
 			if (soundId == kTalkSoundID && _curEffectId && mode == SEEK_END)
-				return _curEffectId * (soundsFileTell(res) + DIMUSE_HMI_TAIL_SIZE - 44) + 44;
+				return _curEffectId * (soundsFileTell(res) + IMUSE_HMI_TAIL_SIZE - 44) + 44;
 
 			if (soundId != kTalkSoundID || !_curEffectId || mode != SEEK_SET)
 				return soundsFileTell(res);
@@ -527,10 +527,10 @@ int IMuseDigital::ihostFseek(int soundId, int32 offset, int mode) {
 	return 0;
 }
 
-int IMuseDigital::ihostRead(int soundId, uint8 *destBuf, int32 size) {
+int IMuse::ihostRead(int soundId, uint8 *destBuf, int32 size) {
 	Common::StackLock lock(*_mutex);
 
-	IMuseDigiResource *res = _openAudioFiles[soundId - 10000].resourcePtr;
+	IMuseResource *res = _openAudioFiles[soundId - 10000].resourcePtr;
 	if (!res)
 		return 0;
 
@@ -577,7 +577,7 @@ int IMuseDigital::ihostRead(int soundId, uint8 *destBuf, int32 size) {
 			isLastChunk = true;
 
 		memcpy(destBuf, _voiceSrcBuf, 44);
-		WRITE_LE_UINT32(destBuf + 40, (DIMUSE_HMI_TAIL_SIZE + READ_LE_UINT32(destBuf + 40)) * _curEffectId);
+		WRITE_LE_UINT32(destBuf + 40, (IMUSE_HMI_TAIL_SIZE + READ_LE_UINT32(destBuf + 40)) * _curEffectId);
 		WRITE_LE_UINT32(destBuf + 28, READ_LE_UINT32(destBuf + 28) * _curEffectId);
 
 		if (_curEffectId > 1) {
@@ -645,8 +645,8 @@ int IMuseDigital::ihostRead(int soundId, uint8 *destBuf, int32 size) {
 	return size;
 }
 
-void IMuseDigital::soundsAllocateBuffer(int bufferId, int32 bufSize, int32 loadSize, int32 criticalSize) {
-	IMuseDigiSndBuffer *soundBuf = &_soundBuffers[bufferId];
+void IMuse::soundsAllocateBuffer(int bufferId, int32 bufSize, int32 loadSize, int32 criticalSize) {
+	IMuseSndBuffer *soundBuf = &_soundBuffers[bufferId];
 
 	soundBuf->buffer = (uint8 *)malloc(bufSize);
 	soundBuf->bufSize = bufSize;
@@ -654,14 +654,14 @@ void IMuseDigital::soundsAllocateBuffer(int bufferId, int32 bufSize, int32 loadS
 	soundBuf->criticalSize = criticalSize;
 }
 
-void IMuseDigital::soundsDeallocateBuffer(int bufferId) {
-	IMuseDigiSndBuffer *soundBuf = &_soundBuffers[bufferId];
+void IMuse::soundsDeallocateBuffer(int bufferId) {
+	IMuseSndBuffer *soundBuf = &_soundBuffers[bufferId];
 
 	free(soundBuf->buffer);
 	soundBuf->buffer = nullptr;
 }
 
-IMuseDigiResource *IMuseDigital::soundsOpenFile(const char *filename) {
+IMuseResource *IMuse::soundsOpenFile(const char *filename) {
 	Common::String lowerName(filename);
 	lowerName.toLowercase();
 
@@ -669,8 +669,8 @@ IMuseDigiResource *IMuseDigital::soundsOpenFile(const char *filename) {
 	if (!stream)
 		return nullptr;
 
-	IMuseDigiResource *res = new IMuseDigiResource();
-	memset(res, 0, sizeof(IMuseDigiResource));
+	IMuseResource *res = new IMuseResource();
+	memset(res, 0, sizeof(IMuseResource));
 	res->resId = stream;
 	res->curProcessedCompBlock = -1;
 	Common::strlcpy(res->filename, filename, sizeof(res->filename));
@@ -739,7 +739,7 @@ IMuseDigiResource *IMuseDigital::soundsOpenFile(const char *filename) {
 	return res;
 }
 
-void IMuseDigital::soundsCloseFile(IMuseDigiResource *res) {
+void IMuse::soundsCloseFile(IMuseResource *res) {
 	if (res->hasMcmp) {
 		free(res->mcmpBlockPtr);
 		delete[] res->compBlockPtr;
@@ -754,7 +754,7 @@ void IMuseDigital::soundsCloseFile(IMuseDigiResource *res) {
 	delete res;
 }
 
-void IMuseDigital::soundsFileSeek(IMuseDigiResource *res, int32 offset, int mode) {
+void IMuse::soundsFileSeek(IMuseResource *res, int32 offset, int mode) {
 	if (!res->hasMcmp) {
 		res->resId->seek(offset, mode);
 	} else if (mode == SEEK_SET) {
@@ -766,14 +766,14 @@ void IMuseDigital::soundsFileSeek(IMuseDigiResource *res, int32 offset, int mode
 	}
 }
 
-int32 IMuseDigital::soundsFileTell(IMuseDigiResource *res) {
+int32 IMuse::soundsFileTell(IMuseResource *res) {
 	if (!res->hasMcmp)
 		return res->resId->pos();
 
 	return res->fileCurOffset;
 }
 
-int IMuseDigital::soundsGetCompBlockId(IMuseDigiResource *res, int32 offset) {
+int IMuse::soundsGetCompBlockId(IMuseResource *res, int32 offset) {
 	if (offset >= 0 && offset < res->resSize) {
 		for (int i = 0; i < res->compBlocksNum; i++) {
 			if (offset >= res->compBlockOffset[i] && offset < res->compBlockOffset[i + 1])
@@ -784,7 +784,7 @@ int IMuseDigital::soundsGetCompBlockId(IMuseDigiResource *res, int32 offset) {
 	return -1;
 }
 
-int32 IMuseDigital::copyDataFromResource(IMuseDigiResource *res, uint8 *dest, int32 size) {
+int32 IMuse::copyDataFromResource(IMuseResource *res, uint8 *dest, int32 size) {
 	uint8 *cmpDataTmpBuf = nullptr;
 	uint32 curCompBlockSize = 0;
 	uint8 *curDest = dest;
@@ -881,9 +881,9 @@ int32 IMuseDigital::copyDataFromResource(IMuseDigiResource *res, uint8 *dest, in
 	return resSize;
 }
 
-int IMuseDigital::cacheGetSoundId(const char *soundName) {
+int IMuse::cacheGetSoundId(const char *soundName) {
 	uintptr soundKey = (uintptr)soundName;
-	IMuseDigiCachedSound *sound;
+	IMuseCachedSound *sound;
 	int slot, soundId, loadSlot = -1;
 	bool isLuaSoundId;
 	bool allocated = false;
@@ -911,8 +911,8 @@ int IMuseDigital::cacheGetSoundId(const char *soundName) {
 		isLuaSoundId = false;
 	}
 
-	sound = &_soundCache[DIMUSE_MAX_CACHED_SOUNDS - 1];
-	slot = DIMUSE_MAX_CACHED_SOUNDS - 1;
+	sound = &_soundCache[IMUSE_MAX_CACHED_SOUNDS - 1];
+	slot = IMUSE_MAX_CACHED_SOUNDS - 1;
 
 	if (isLuaSoundId) {
 		while ((uintptr)sound->luaSoundId != soundKey) {
@@ -947,7 +947,7 @@ int IMuseDigital::cacheGetSoundId(const char *soundName) {
 				do {
 					collision = false;
 					int candidateId = abs(slotCounter) % 256 + 1111;
-					for (int i = 0; i < DIMUSE_MAX_CACHED_SOUNDS; i++) {
+					for (int i = 0; i < IMUSE_MAX_CACHED_SOUNDS; i++) {
 						if (_soundCache[i].soundFilename[0] && _soundCache[i].luaSoundId == candidateId) {
 							collision = true;
 							slotCounter++;
@@ -976,9 +976,9 @@ int IMuseDigital::cacheGetSoundId(const char *soundName) {
 	// Load the sound in the cache
 	sound->flag = 0;
 
-	IMuseDigiResource *res = soundsOpenFile(sound->soundFilename);
+	IMuseResource *res = soundsOpenFile(sound->soundFilename);
 	if (!res) {
-		memset(sound, 0, sizeof(IMuseDigiCachedSound));
+		memset(sound, 0, sizeof(IMuseCachedSound));
 		return 0;
 	}
 
@@ -1046,21 +1046,21 @@ int IMuseDigital::cacheGetSoundId(const char *soundName) {
 
 	free(sound->soundUncompData);
 	soundsResetLipsyncState(sound->luaSoundId);
-	memset(sound, 0, sizeof(IMuseDigiCachedSound));
+	memset(sound, 0, sizeof(IMuseCachedSound));
 	return 0;
 }
 
-int IMuseDigital::cachePurgeOldestStoppedSound() {
+int IMuse::cachePurgeOldestStoppedSound() {
 	int foundSlot = -1;
 	int emptySlot = -1;
 	uint32 oldestTimestamp = g_system->getMillis();
 
-	for (int slot = DIMUSE_MAX_CACHED_SOUNDS - 1; slot >= 0; slot--) {
-		IMuseDigiCachedSound *sound = &_soundCache[slot];
+	for (int slot = IMUSE_MAX_CACHED_SOUNDS - 1; slot >= 0; slot--) {
+		IMuseCachedSound *sound = &_soundCache[slot];
 
 		if (sound->soundFilename[0] && sound->soundUncompData) {
-			if (!diMUSEGetParam(slot + 100, DIMUSE_P_SND_TRACK_NUM) &&
-				!diMUSEGetParam(slot + 100, DIMUSE_P_TRIGS_SNDS) &&
+			if (!imGetParam(slot + 100, IMUSE_P_SND_TRACK_NUM) &&
+				!imGetParam(slot + 100, IMUSE_P_TRIGS_SNDS) &&
 				(foundSlot < 0 || oldestTimestamp > sound->tsOfAllocation)) {
 				foundSlot = slot;
 				oldestTimestamp = sound->tsOfAllocation;
@@ -1071,20 +1071,20 @@ int IMuseDigital::cachePurgeOldestStoppedSound() {
 	}
 
 	if (foundSlot >= 0) {
-		IMuseDigiCachedSound *sound = &_soundCache[foundSlot];
+		IMuseCachedSound *sound = &_soundCache[foundSlot];
 		sound->soundFilename[0] = 0;
 		soundsResetLipsyncState(sound->luaSoundId);
 
 		free(sound->soundUncompData);
-		memset(sound, 0, sizeof(IMuseDigiCachedSound));
+		memset(sound, 0, sizeof(IMuseCachedSound));
 		return foundSlot;
 	}
 
 	return emptySlot;
 }
 
-void IMuseDigital::cacheReset() {
-	for (int slot = DIMUSE_MAX_CACHED_SOUNDS - 1; slot >= 0; slot--) {
+void IMuse::cacheReset() {
+	for (int slot = IMUSE_MAX_CACHED_SOUNDS - 1; slot >= 0; slot--) {
 		if (_soundCache[slot].soundUncompData) {
 			soundsResetLipsyncState(_soundCache[slot].luaSoundId);
 			free(_soundCache[slot].soundUncompData);
@@ -1095,7 +1095,7 @@ void IMuseDigital::cacheReset() {
 	memset(_soundCache, 0, sizeof(_soundCache));
 }
 
-uint8 *IMuseDigital::soundsGetExtFormatBuffer(uint8 *streamHeader, int *formatId, int *targetSampleRate, int *targetWordSize, int *targetNumChannels, int *swapEndianFlag, int *regionLength) {
+uint8 *IMuse::soundsGetExtFormatBuffer(uint8 *streamHeader, int *formatId, int *targetSampleRate, int *targetWordSize, int *targetNumChannels, int *swapEndianFlag, int *regionLength) {
 	bool isMCMP = false;
 	uint8 *header = streamHeader;
 
@@ -1242,7 +1242,7 @@ uint8 *IMuseDigital::soundsGetExtFormatBuffer(uint8 *streamHeader, int *formatId
 	return nullptr;
 }
 
-int IMuseDigital::createSoundHeader(uint8 *buffer, int mode, int sampleRate, int wordSize, int numChannels, int regionLength) {
+int IMuse::createSoundHeader(uint8 *buffer, int mode, int sampleRate, int wordSize, int numChannels, int regionLength) {
 	if (mode == 3) {
 		memcpy(buffer, "iMUS", 4);
 		WRITE_BE_UINT32(buffer + 4, regionLength + 80);
@@ -1270,7 +1270,7 @@ int IMuseDigital::createSoundHeader(uint8 *buffer, int mode, int sampleRate, int
 	return 0;
 }
 
-int IMuseDigital::soundsLoadStartSound(const char *soundName, int priority, int group) {
+int IMuse::soundsLoadStartSound(const char *soundName, int priority, int group) {
 	int soundId = cacheGetSoundId(soundName);
 	if (!soundId)
 		return 0;
@@ -1278,13 +1278,13 @@ int IMuseDigital::soundsLoadStartSound(const char *soundName, int priority, int
 	if (priority > 124)
 		priority = 124;
 
-	diMUSEStartSound(soundId, priority);
-	diMUSESetParam(soundId, DIMUSE_P_GROUP, group);
+	imStartSound(soundId, priority);
+	imSetParam(soundId, IMUSE_P_GROUP, group);
 	_soundCache[soundId - 100].priority = priority;
 	return _soundCache[soundId - 100].luaSoundId;
 }
 
-int IMuseDigital::soundsLoadProcessStartSound(const char *soundName, int priority, int group) {
+int IMuse::soundsLoadProcessStartSound(const char *soundName, int priority, int group) {
 	int soundId = cacheGetSoundId(soundName);
 	if (!soundId)
 		return 0;
@@ -1293,76 +1293,76 @@ int IMuseDigital::soundsLoadProcessStartSound(const char *soundName, int priorit
 		priority = 124;
 
 	if (_curEffectId) {
-		IMuseDigiCachedSound *sound = &_soundCache[soundId - 100];
+		IMuseCachedSound *sound = &_soundCache[soundId - 100];
 		if (sound->luaSoundId && !sound->flag)
 			allocateProcessedSound(sound->luaSoundId);
 	}
 
-	diMUSEStartSound(soundId, priority);
-	diMUSESetParam(soundId, DIMUSE_P_GROUP, group);
+	imStartSound(soundId, priority);
+	imSetParam(soundId, IMUSE_P_GROUP, group);
 	_soundCache[soundId - 100].priority = priority;
 	return _soundCache[soundId - 100].luaSoundId;
 }
 
-void IMuseDigital::soundsStopSound(const char *soundName) {
+void IMuse::soundsStopSound(const char *soundName) {
 	int soundId = cacheGetSoundId(soundName);
 	if (soundId)
-		diMUSEStopSound(soundId);
+		imStopSound(soundId);
 }
 
-int IMuseDigital::soundsGetParam(const char *soundName, int paramId) {
+int IMuse::soundsGetParam(const char *soundName, int paramId) {
 	int soundId = cacheGetSoundId(soundName);
 	if (soundId)
-		return diMUSEGetParam(soundId, paramId);
+		return imGetParam(soundId, paramId);
 
 	return 1;
 }
 
-void IMuseDigital::soundsSetParam(const char *soundName, int paramId, int value) {
+void IMuse::soundsSetParam(const char *soundName, int paramId, int value) {
 	int soundId = cacheGetSoundId(soundName);
 	if (soundId)
-		diMUSESetParam(soundId, paramId, value);
+		imSetParam(soundId, paramId, value);
 }
 
-int IMuseDigital::soundsFadeParam(const char *soundName, int paramId, int value, int length) {
+int IMuse::soundsFadeParam(const char *soundName, int paramId, int value, int length) {
 	int soundId = cacheGetSoundId(soundName);
 	if (soundId)
-		return diMUSEFadeParam(soundId, paramId, value, 60 * length / 1000);
+		return imFadeParam(soundId, paramId, value, 60 * length / 1000);
 
 	return 1;
 }
 
-bool IMuseDigital::soundsIsSoundInUse(const char *soundName) {
+bool IMuse::soundsIsSoundInUse(const char *soundName) {
 	uint32 soundIndex = cacheGetSoundId(soundName) - 100;
-	if (soundIndex >= DIMUSE_MAX_CACHED_SOUNDS || !_soundCache[soundIndex].soundFilename[0] || !_soundCache[soundIndex].soundUncompData)
+	if (soundIndex >= IMUSE_MAX_CACHED_SOUNDS || !_soundCache[soundIndex].soundFilename[0] || !_soundCache[soundIndex].soundUncompData)
 		return false;
 
 	int soundId = soundIndex + 100;
-	return diMUSEGetParam(soundId, DIMUSE_P_SND_TRACK_NUM) > 0 || diMUSEGetParam(soundId, DIMUSE_P_TRIGS_SNDS) > 0;
+	return imGetParam(soundId, IMUSE_P_SND_TRACK_NUM) > 0 || imGetParam(soundId, IMUSE_P_TRIGS_SNDS) > 0;
 }
 
-bool IMuseDigital::soundsIsSoundPlaying(const char *soundName) {
+bool IMuse::soundsIsSoundPlaying(const char *soundName) {
 	int soundId = cacheGetSoundId(soundName);
-	return diMUSEGetParam(soundId, DIMUSE_P_SND_TRACK_NUM) > 0;
+	return imGetParam(soundId, IMUSE_P_SND_TRACK_NUM) > 0;
 }
 
-int IMuseDigital::iMUSESetHook(const char *soundName, int hookId) {
+int IMuse::iMUSESetHook(const char *soundName, int hookId) {
 	int soundId = cacheGetSoundId(soundName);
 	if (soundId)
-		return diMUSESetHook(soundId, hookId);
+		return imSetHook(soundId, hookId);
 
 	return -1;
 }
 
-int IMuseDigital::iMUSEGetHook(const char *soundName) {
+int IMuse::iMUSEGetHook(const char *soundName) {
 	int soundId = cacheGetSoundId(soundName);
 	if (soundId)
-		return diMUSEGetHook(soundId);
+		return imGetHook(soundId);
 
 	return -1;
 }
 
-void IMuseDigital::iMUSESetVoiceEffect(const char *effectName) {
+void IMuse::iMUSESetVoiceEffect(const char *effectName) {
 	Common::strlcpy(_curEffectName, effectName, sizeof(_curEffectName));
 
 	if (!_hmiFxInitialized || !scumm_stricmp(effectName, "OFF"))
@@ -1371,17 +1371,17 @@ void IMuseDigital::iMUSESetVoiceEffect(const char *effectName) {
 		_curEffectId = registerHMIEffect(effectName);
 }
 
-void IMuseDigital::allocateProcessedSound(int luaSoundId) {
+void IMuse::allocateProcessedSound(int luaSoundId) {
 	if (luaSoundId < 1111 || luaSoundId >= 1367)
 		return;
 
-	int slot = DIMUSE_MAX_CACHED_SOUNDS - 1;
+	int slot = IMUSE_MAX_CACHED_SOUNDS - 1;
 	while (_soundCache[slot].luaSoundId != luaSoundId) {
 		if (!slot--)
 			return;
 	}
 
-	IMuseDigiCachedSound *sound = &_soundCache[slot];
+	IMuseCachedSound *sound = &_soundCache[slot];
 	if (!sound->soundUncompData || !sound->soundAddrData)
 		return;
 
@@ -1413,37 +1413,37 @@ void IMuseDigital::allocateProcessedSound(int luaSoundId) {
 	}
 }
 
-void IMuseDigital::soundsPeriodic() {
+void IMuse::soundsPeriodic() {
 	int32 cachedSize = 0;
 
-	diMUSEProcessStreams();
-	diMUSERefreshScript();
+	imProcessStreams();
+	imRefreshScript();
 
-	for (int slot = DIMUSE_MAX_CACHED_SOUNDS - 1; slot >= 0; slot--) {
+	for (int slot = IMUSE_MAX_CACHED_SOUNDS - 1; slot >= 0; slot--) {
 		if (_soundCache[slot].soundFilename[0] && _soundCache[slot].soundUncompData)
 			cachedSize += _soundCache[slot].uncompResourceSize;
 	}
 
-	if (cachedSize > DIMUSE_SOUNDS_MEMORY_LIMIT)
+	if (cachedSize > IMUSE_SOUNDS_MEMORY_LIMIT)
 		cachePurgeOldestStoppedSound();
 }
 
-int IMuseDigital::soundsPause() {
-	diMUSEPause();
-	_globalVolume = diMUSESetGroupVol(0, -1);
-	diMUSESetGroupVol(0, 0);
-	diMUSESetAttribute(-1, 0);
+int IMuse::soundsPause() {
+	imPause();
+	_globalVolume = imSetGroupVol(0, -1);
+	imSetGroupVol(0, 0);
+	imSetAttribute(-1, 0);
 	return 0;
 }
 
-int IMuseDigital::soundsResume() {
-	diMUSESetGroupVol(0, _globalVolume);
-	diMUSEResume();
-	diMUSESetAttribute(-1, 1);
+int IMuse::soundsResume() {
+	imSetGroupVol(0, _globalVolume);
+	imResume();
+	imSetAttribute(-1, 1);
 	return 0;
 }
 
-int IMuseDigital::soundsRegisterVoice(const char *filename) {
+int IMuse::soundsRegisterVoice(const char *filename) {
 	char lipsyncFilename[32];
 
 	Common::strlcpy(_curSpeechFile, filename, sizeof(_curSpeechFile));
@@ -1455,7 +1455,7 @@ int IMuseDigital::soundsRegisterVoice(const char *filename) {
 		loadLip(lipsyncFilename, kTalkSoundID);
 	}
 
-	IMuseDigiResource *res = soundsOpenFile(filename);
+	IMuseResource *res = soundsOpenFile(filename);
 	_openAudioFiles[0].resourcePtr = res;
 	if (!res) {
 		_millisecsInCurSpeechFile = 0;
@@ -1469,7 +1469,7 @@ int IMuseDigital::soundsRegisterVoice(const char *filename) {
 	return 1;
 }
 
-void IMuseDigital::soundsCloseVoiceFile() {
+void IMuse::soundsCloseVoiceFile() {
 	if (_openAudioFiles[0].resourcePtr) {
 		soundsCloseFile(_openAudioFiles[0].resourcePtr);
 		soundsResetLipsyncState(kTalkSoundID);
@@ -1477,38 +1477,38 @@ void IMuseDigital::soundsCloseVoiceFile() {
 	}
 }
 
-void IMuseDigital::soundsReOpenVoiceFile() {
+void IMuse::soundsReOpenVoiceFile() {
 	soundsCloseVoiceFile();
 	if (_curSpeechFile[0])
 		soundsRegisterVoice(_curSpeechFile);
 }
 
-int IMuseDigital::soundStartVoiceStream(const char *filename, int volume, int pan) {
-	diMUSEStopSound(kTalkSoundID);
+int IMuse::soundStartVoiceStream(const char *filename, int volume, int pan) {
+	imStopSound(kTalkSoundID);
 	soundsCloseVoiceFile();
 	if (!soundsRegisterVoice(filename))
 		return 1;
 
-	fillStreamsWhileMusicCritical(5);
-	diMUSEStartStream(kTalkSoundID, 127, DIMUSE_BUFFER_SPEECH);
-	diMUSESetParam(kTalkSoundID, DIMUSE_P_GROUP, DIMUSE_GROUP_SPEECH);
-	diMUSESetParam(kTalkSoundID, DIMUSE_P_VOLUME, volume);
-	diMUSESetParam(kTalkSoundID, DIMUSE_P_PAN, pan);
-	diMUSEProcessStreams();
-	diMUSEProcessStreams();
+	soundsFillStreamsWhileMusicCritical(5);
+	imStartStream(kTalkSoundID, 127, IMUSE_BUFFER_SPEECH);
+	imSetParam(kTalkSoundID, IMUSE_P_GROUP, IMUSE_GROUP_SPEECH);
+	imSetParam(kTalkSoundID, IMUSE_P_VOLUME, volume);
+	imSetParam(kTalkSoundID, IMUSE_P_PAN, pan);
+	imProcessStreams();
+	imProcessStreams();
 	return 0;
 }
 
-int IMuseDigital::soundStopVoiceStream() {
-	diMUSEStopSound(kTalkSoundID);
+int IMuse::soundStopVoiceStream() {
+	imStopSound(kTalkSoundID);
 	return ihostCloseSound(kTalkSoundID);
 }
 
-int IMuseDigital::soundGetVoiceTime() {
-	return diMUSEGetParam(kTalkSoundID, DIMUSE_P_SND_POS_IN_MS);
+int IMuse::soundGetVoiceTime() {
+	return imGetParam(kTalkSoundID, IMUSE_P_SND_POS_IN_MS);
 }
 
-int IMuseDigital::loadLip(const char *lipsyncFilename, int soundId) {
+int IMuse::loadLip(const char *lipsyncFilename, int soundId) {
 	Common::String lowerName(lipsyncFilename);
 	lowerName.toLowercase();
 
@@ -1523,7 +1523,7 @@ int IMuseDigital::loadLip(const char *lipsyncFilename, int soundId) {
 		return 0;
 	}
 
-	for (int i = 1; i < DIMUSE_MAX_LIPSYNCS; i++) {
+	for (int i = 1; i < IMUSE_MAX_LIPSYNCS; i++) {
 		if (soundId == _lipsyncSoundIds[i]) {
 			delete lipsyncFile;
 			return 1;
@@ -1534,7 +1534,7 @@ int IMuseDigital::loadLip(const char *lipsyncFilename, int soundId) {
 	if (soundId == kTalkSoundID) {
 		slot = 0;
 	} else {
-		for (int i = 1; i < DIMUSE_MAX_LIPSYNCS; i++) {
+		for (int i = 1; i < IMUSE_MAX_LIPSYNCS; i++) {
 			if (!_lipsyncSoundIds[i]) {
 				slot = i;
 				break;
@@ -1546,7 +1546,7 @@ int IMuseDigital::loadLip(const char *lipsyncFilename, int soundId) {
 		_lipsyncSoundIds[slot] = soundId;
 
 		int fileSize = lipsyncFile->size();
-		if (fileSize <= DIMUSE_LIPSYNC_MAX_SIZE) {
+		if (fileSize <= IMUSE_LIPSYNC_MAX_SIZE) {
 			lipsyncFile->read(_lipsyncBufs[slot], fileSize);
 
 			if (memcmp(_lipsyncBufs[slot], "LIP!", 4))
@@ -1558,14 +1558,14 @@ int IMuseDigital::loadLip(const char *lipsyncFilename, int soundId) {
 	return 0;
 }
 
-void IMuseDigital::soundsResetLipsyncState(int soundId) {
-	for (int i = 0; i < DIMUSE_MAX_LIPSYNCS; i++) {
+void IMuse::soundsResetLipsyncState(int soundId) {
+	for (int i = 0; i < IMUSE_MAX_LIPSYNCS; i++) {
 		if (soundId == _lipsyncSoundIds[i])
 			_lipsyncSoundIds[i] = 0;
 	}
 }
 
-int IMuseDigital::soundsGetPhoneme(int soundId, int offset) {
+int IMuse::soundsGetPhoneme(int soundId, int offset) {
 	uint8 *lipsyncBuffer;
 
 	if (soundId == kTalkSoundID) {
@@ -1597,10 +1597,10 @@ int IMuseDigital::soundsGetPhoneme(int soundId, int offset) {
 		entry += 4;
 	}
 
-	return DIMUSE_PHONEME_NONE;
+	return IMUSE_PHONEME_NONE;
 }
 
-void IMuseDigital::soundsSaveLoad(Common::Serializer &ser) {
+void IMuse::soundsSaveLoad(Common::Serializer &ser) {
 	Common::StackLock lock(*_mutex);
 
 	char effectName[sizeof(_curEffectName)];
@@ -1613,43 +1613,43 @@ void IMuseDigital::soundsSaveLoad(Common::Serializer &ser) {
 	ser.syncArray(effectName, sizeof(effectName), Common::Serializer::SByte, VER(30));
 
 	if (ser.isLoading()) {
-		diMUSEStopAllSounds();
-		diMUSEFlushSounds();
+		imStopAllSounds();
+		imFlushSounds();
 		soundsCloseVoiceFile();
 		cacheReset();
 		iMUSESetVoiceEffect(effectName);
 		_curSpeechFile[0] = '\0';
 	}
 
-	diMUSESaveLoad(ser);
-	diMUSESaveLoadScript(ser);
+	imSaveLoad(ser);
+	imSaveLoadScript(ser);
 
 	if (ser.isLoading()) {
-		for (int soundId = diMUSEGetNextSound(0); soundId; soundId = diMUSEGetNextSound(soundId)) {
+		for (int soundId = imGetNextSound(0); soundId; soundId = imGetNextSound(soundId)) {
 			if (soundId <= kTalkSoundID)
-				diMUSEStopSound(soundId);
+				imStopSound(soundId);
 		}
 
 		soundsCloseVoiceFile();
 	}
 
 	int32 numSounds = 0;
-	int savedSlots[DIMUSE_MAX_CACHED_SOUNDS];
+	int savedSlots[IMUSE_MAX_CACHED_SOUNDS];
 
 	if (ser.isSaving()) {
 		// Only active sounds with a native iMUS map are saved...
-		for (int slot = 0; slot < DIMUSE_MAX_CACHED_SOUNDS; slot++) {
-			IMuseDigiCachedSound *sound = &_soundCache[slot];
+		for (int slot = 0; slot < IMUSE_MAX_CACHED_SOUNDS; slot++) {
+			IMuseCachedSound *sound = &_soundCache[slot];
 
 			if (sound->soundFilename[0] && sound->soundUncompData &&
-				diMUSEGetParam(slot + 100, DIMUSE_P_SND_TRACK_NUM) > 0 &&
+				imGetParam(slot + 100, IMUSE_P_SND_TRACK_NUM) > 0 &&
 				!memcmp(sound->soundMap, "iMUS", 4) && READ_BE_UINT16(sound->soundMap + 14) != 56)
 				savedSlots[numSounds++] = slot;
 		}
 	}
 
 	ser.syncAsSint32LE(numSounds, VER(30));
-	if (numSounds < 0 || numSounds > DIMUSE_MAX_CACHED_SOUNDS)
+	if (numSounds < 0 || numSounds > IMUSE_MAX_CACHED_SOUNDS)
 		return;
 
 	// The cached sounds are restarted with the same ids, volume, pan and hook
@@ -1669,7 +1669,7 @@ void IMuseDigital::soundsSaveLoad(Common::Serializer &ser) {
 
 		if (ser.isLoading()) {
 			_currentSoundSlot = luaSoundId - 1111;
-			soundsLoadStartSound(soundName, priority, DIMUSE_GROUP_SFX);
+			soundsLoadStartSound(soundName, priority, IMUSE_GROUP_SFX);
 		}
 	}
 
@@ -1678,8 +1678,8 @@ void IMuseDigital::soundsSaveLoad(Common::Serializer &ser) {
 
 		if (ser.isSaving()) {
 			luaSoundId = _soundCache[savedSlots[i]].luaSoundId;
-			volume = diMUSEGetParam(savedSlots[i] + 100, DIMUSE_P_VOLUME);
-			pan = diMUSEGetParam(savedSlots[i] + 100, DIMUSE_P_PAN);
+			volume = imGetParam(savedSlots[i] + 100, IMUSE_P_VOLUME);
+			pan = imGetParam(savedSlots[i] + 100, IMUSE_P_PAN);
 		}
 
 		ser.syncAsSint32LE(luaSoundId, VER(30));
@@ -1687,8 +1687,8 @@ void IMuseDigital::soundsSaveLoad(Common::Serializer &ser) {
 		ser.syncAsSint32LE(pan, VER(30));
 
 		if (ser.isLoading()) {
-			soundsSetParam((const char *)(intptr)luaSoundId, DIMUSE_P_VOLUME, volume);
-			soundsSetParam((const char *)(intptr)luaSoundId, DIMUSE_P_PAN, pan);
+			soundsSetParam((const char *)(intptr)luaSoundId, IMUSE_P_VOLUME, volume);
+			soundsSetParam((const char *)(intptr)luaSoundId, IMUSE_P_PAN, pan);
 		}
 	}
 
@@ -1697,7 +1697,7 @@ void IMuseDigital::soundsSaveLoad(Common::Serializer &ser) {
 
 		if (ser.isSaving()) {
 			luaSoundId = _soundCache[savedSlots[i]].luaSoundId;
-			hookId = diMUSEGetHook(savedSlots[i] + 100);
+			hookId = imGetHook(savedSlots[i] + 100);
 		}
 
 		ser.syncAsSint32LE(luaSoundId, VER(30));
@@ -1708,13 +1708,13 @@ void IMuseDigital::soundsSaveLoad(Common::Serializer &ser) {
 	}
 }
 
-void IMuseDigital::soundsRestoreLegacy(int32 stateIndex, int32 seqIndex) {
+void IMuse::soundsRestoreLegacy(int32 stateIndex, int32 seqIndex) {
 	Common::StackLock lock(*_mutex);
 
 	// The savegames of the old iMUSE only stored the music state and sequence, so
 	// the rest is reset and the music is started again as it was
-	diMUSEStopAllSounds();
-	diMUSEFlushSounds();
+	imStopAllSounds();
+	imFlushSounds();
 	soundsCloseVoiceFile();
 	cacheReset();
 	_curSpeechFile[0] = '\0';
@@ -1731,13 +1731,13 @@ void IMuseDigital::soundsRestoreLegacy(int32 stateIndex, int32 seqIndex) {
 	scriptSetState(stateId);
 }
 
-int IMuseDigital::iMUSEGetPhoneme(int lipsyncId, int offset) {
+int IMuse::iMUSEGetPhoneme(int lipsyncId, int offset) {
 	if (lipsyncId == _lipsyncSoundIds[0])
 		return soundsGetPhoneme(lipsyncId, offset + soundGetVoiceTime());
 
 	if (lipsyncId == _lipsyncSoundIds[1] || lipsyncId == _lipsyncSoundIds[2] || lipsyncId == _lipsyncSoundIds[3]) {
 		int soundId = 0;
-		for (int slot = 0; slot < DIMUSE_MAX_CACHED_SOUNDS && !soundId; slot++) {
+		for (int slot = 0; slot < IMUSE_MAX_CACHED_SOUNDS && !soundId; slot++) {
 			if (_soundCache[slot].luaSoundId == lipsyncId)
 				soundId = slot + 100;
 		}
@@ -1745,7 +1745,7 @@ int IMuseDigital::iMUSEGetPhoneme(int lipsyncId, int offset) {
 		if (!soundId)
 			return 0;
 
-		return soundsGetPhoneme(lipsyncId, offset + diMUSEGetParam(soundId, DIMUSE_P_SND_POS_IN_MS));
+		return soundsGetPhoneme(lipsyncId, offset + imGetParam(soundId, IMUSE_P_SND_POS_IN_MS));
 	}
 
 	return 0;
diff --git a/engines/grim/imuse/dimuse_groups.cpp b/engines/grim/imuse/imuse_groups.cpp
similarity index 73%
rename from engines/grim/imuse/dimuse_groups.cpp
rename to engines/grim/imuse/imuse_groups.cpp
index 6f7de12b1b9..3fa2f18eea6 100644
--- a/engines/grim/imuse/dimuse_groups.cpp
+++ b/engines/grim/imuse/imuse_groups.cpp
@@ -19,32 +19,32 @@
  *
  */
 
-#include "engines/grim/imuse/dimuse_engine.h"
-#include "engines/grim/imuse/dimuse_groups.h"
+#include "engines/grim/imuse/imuse_engine.h"
+#include "engines/grim/imuse/imuse_groups.h"
 
 namespace Grim {
 
-IMuseDigiGroupsHandler::IMuseDigiGroupsHandler(IMuseDigital *engine, Common::Mutex *mutex) {
+IMuseGroupsHandler::IMuseGroupsHandler(IMuse *engine, Common::Mutex *mutex) {
 	_engine = engine;
 	_mutex = mutex;
 }
 
-IMuseDigiGroupsHandler::~IMuseDigiGroupsHandler() {}
+IMuseGroupsHandler::~IMuseGroupsHandler() {}
 
-int IMuseDigiGroupsHandler::init() {
-	for (int i = 0; i < DIMUSE_MAX_GROUPS; i++) {
+int IMuseGroupsHandler::init() {
+	for (int i = 0; i < IMUSE_MAX_GROUPS; i++) {
 		_effVols[i] = 127;
 		_vols[i] = 127;
 	}
 	return 0;
 }
 
-int IMuseDigiGroupsHandler::setGroupVol(uint32 id, int volume) {
+int IMuseGroupsHandler::setGroupVol(uint32 id, int volume) {
 	Common::StackLock lock(*_mutex);
 
 	int l;
 
-	if (id >= DIMUSE_MAX_GROUPS) {
+	if (id >= IMUSE_MAX_GROUPS) {
 		return -5;
 	}
 
@@ -64,7 +64,7 @@ int IMuseDigiGroupsHandler::setGroupVol(uint32 id, int volume) {
 		_effVols[0] = volume;
 		_vols[0] = volume;
 
-		for (l = 1; l < DIMUSE_MAX_GROUPS; l++) {
+		for (l = 1; l < IMUSE_MAX_GROUPS; l++) {
 			_effVols[l] = (volume * (_vols[l] + 1)) / 128;
 		}
 	}
@@ -73,10 +73,10 @@ int IMuseDigiGroupsHandler::setGroupVol(uint32 id, int volume) {
 	return oldVolume;
 }
 
-int IMuseDigiGroupsHandler::getGroupVol(uint32 id) {
+int IMuseGroupsHandler::getGroupVol(uint32 id) {
 	Common::StackLock lock(*_mutex);
 
-	if (id >= DIMUSE_MAX_GROUPS) {
+	if (id >= IMUSE_MAX_GROUPS) {
 		return -5;
 	}
 
diff --git a/engines/grim/imuse/dimuse_groups.h b/engines/grim/imuse/imuse_groups.h
similarity index 82%
rename from engines/grim/imuse/dimuse_groups.h
rename to engines/grim/imuse/imuse_groups.h
index cd16fe7d3ae..c88de313e0e 100644
--- a/engines/grim/imuse/dimuse_groups.h
+++ b/engines/grim/imuse/imuse_groups.h
@@ -27,20 +27,20 @@
 #include "common/serializer.h"
 #include "common/textconsole.h"
 #include "common/util.h"
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 
 namespace Grim {
 
-class IMuseDigiGroupsHandler {
+class IMuseGroupsHandler {
 
 private:
-	IMuseDigital *_engine;
+	IMuse *_engine;
 	Common::Mutex *_mutex;
-	int _effVols[DIMUSE_MAX_GROUPS] = {};
-	int _vols[DIMUSE_MAX_GROUPS] = {};
+	int _effVols[IMUSE_MAX_GROUPS] = {};
+	int _vols[IMUSE_MAX_GROUPS] = {};
 public:
-	IMuseDigiGroupsHandler(IMuseDigital *engine, Common::Mutex *mutex);
-	~IMuseDigiGroupsHandler();
+	IMuseGroupsHandler(IMuse *engine, Common::Mutex *mutex);
+	~IMuseGroupsHandler();
 	int init();
 	int setGroupVol(uint32 id, int volume);
 	int getGroupVol(uint32 id);
diff --git a/engines/grim/imuse/dimuse_hmi.cpp b/engines/grim/imuse/imuse_hmi.cpp
similarity index 93%
rename from engines/grim/imuse/dimuse_hmi.cpp
rename to engines/grim/imuse/imuse_hmi.cpp
index 9aac9c156bf..cff6f0acd4e 100644
--- a/engines/grim/imuse/dimuse_hmi.cpp
+++ b/engines/grim/imuse/imuse_hmi.cpp
@@ -24,11 +24,11 @@
 #include "audio/effects/hmi/hmifxlib.h"
 
 #include "engines/grim/resource.h"
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 
 namespace Grim {
 
-int IMuseDigital::setupHMI(int heapSize) {
+int IMuse::setupHMI(int heapSize) {
 	if (_hmiFxInitialized)
 		return 1;
 
@@ -67,7 +67,7 @@ int IMuseDigital::setupHMI(int heapSize) {
 	return 1;
 }
 
-int IMuseDigital::registerHMIEffect(const char *effectName) {
+int IMuse::registerHMIEffect(const char *effectName) {
 	if (_loadedPreset)
 		_hmiFxLib->hmiFXPresetRelease(_loadedPreset);
 
@@ -93,7 +93,7 @@ int IMuseDigital::registerHMIEffect(const char *effectName) {
 	return _curHMIEffectIdInternal;
 }
 
-int IMuseDigital::processSound(uint8 *srcBuf, uint32 soundLength, uint8 *destBuf, uint8 **outBuf, int32 *outLength, bool isLastChunk) {
+int IMuse::processSound(uint8 *srcBuf, uint32 soundLength, uint8 *destBuf, uint8 **outBuf, int32 *outLength, bool isLastChunk) {
 	if (_loadedPreset) {
 		_hmiRequest.flags = HMI_PROCESS_USE_PRESET | HMI_PROCESS_OVERRIDE_INPUT_FORMAT | HMI_PROCESS_OVERRIDE_OUTPUT_FORMAT;
 		if (isLastChunk)
@@ -148,7 +148,7 @@ int IMuseDigital::processSound(uint8 *srcBuf, uint32 soundLength, uint8 *destBuf
 	return _curHMIEffectIdInternal;
 }
 
-void IMuseDigital::soundsTerminateProcessing() {
+void IMuse::soundsTerminateProcessing() {
 	if (!_hmiFxInitialized)
 		return;
 
diff --git a/engines/grim/imuse/dimuse_internalmixer.cpp b/engines/grim/imuse/imuse_internalmixer.cpp
similarity index 88%
rename from engines/grim/imuse/dimuse_internalmixer.cpp
rename to engines/grim/imuse/imuse_internalmixer.cpp
index a1d2f3566be..6ba3fb122c5 100644
--- a/engines/grim/imuse/dimuse_internalmixer.cpp
+++ b/engines/grim/imuse/imuse_internalmixer.cpp
@@ -25,12 +25,12 @@
 #include "common/textconsole.h"
 #include "common/util.h"
 
-#include "engines/grim/imuse/dimuse_engine.h"
-#include "engines/grim/imuse/dimuse_internalmixer.h"
+#include "engines/grim/imuse/imuse_engine.h"
+#include "engines/grim/imuse/imuse_internalmixer.h"
 
 namespace Grim {
 
-IMuseDigiInternalMixer::IMuseDigiInternalMixer(Audio::Mixer *mixer, int sampleRate, bool lowLatencyMode) {
+IMuseInternalMixer::IMuseInternalMixer(Audio::Mixer *mixer, int sampleRate, bool lowLatencyMode) {
 	_mixer = mixer;
 	_sampleRate = sampleRate;
 	_lowLatencyMode = lowLatencyMode;
@@ -46,11 +46,11 @@ IMuseDigiInternalMixer::IMuseDigiInternalMixer(Audio::Mixer *mixer, int sampleRa
 		_stream = nullptr;
 }
 
-IMuseDigiInternalMixer::~IMuseDigiInternalMixer() {
+IMuseInternalMixer::~IMuseInternalMixer() {
 	terminate();
 }
 
-int IMuseDigiInternalMixer::terminate() {
+int IMuseInternalMixer::terminate() {
 	free(_softLTable);
 	free(_mixBuf);
 	_softLTable = nullptr;
@@ -58,7 +58,7 @@ int IMuseDigiInternalMixer::terminate() {
 	return 0;
 }
 
-int IMuseDigiInternalMixer::init(int numChannels, int mixBufSize, int mixChannelsNum) {
+int IMuseInternalMixer::init(int numChannels, int mixBufSize, int mixChannelsNum) {
 	// Pan table: 17 volume levels x 17 pan positions
 	for (int i = 0; i < 17; i++) {
 		for (int j = 0; j < 17; j++) {
@@ -72,7 +72,7 @@ int IMuseDigiInternalMixer::init(int numChannels, int mixBufSize, int mixChannel
 
 	_softLTable = (int16 *)malloc(mixChannelsNum << 16);
 	if (!_softLTable) {
-		debug(5, "IMuseDigiInternalMixer::init(): ERROR: couldn't allocate mixer tables");
+		debug(5, "IMuseInternalMixer::init(): ERROR: couldn't allocate mixer tables");
 		return -1;
 	}
 
@@ -92,7 +92,7 @@ int IMuseDigiInternalMixer::init(int numChannels, int mixBufSize, int mixChannel
 	return 0;
 }
 
-int IMuseDigiInternalMixer::clearMixerBuffer() {
+int IMuseInternalMixer::clearMixerBuffer() {
 	if (!_mixBuf)
 		return -1;
 
@@ -101,7 +101,7 @@ int IMuseDigiInternalMixer::clearMixerBuffer() {
 	return 0;
 }
 
-void IMuseDigiInternalMixer::mix16ToStereo(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int leftAmp, int rightAmp) {
+void IMuseInternalMixer::mix16ToStereo(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int leftAmp, int rightAmp) {
 	int32 *mixBufCurCell = &_mixBuf[2 * mixBufStartIndex];
 	uint32 ratio = ((uint32)inFrameCount << 16) / feedSize;
 	uint32 position = 0;
@@ -158,7 +158,7 @@ void IMuseDigiInternalMixer::mix16ToStereo(const int16 *srcBuf, int32 inFrameCou
 	}
 }
 
-void IMuseDigiInternalMixer::mix16ToStereoSwap(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int leftAmp, int rightAmp) {
+void IMuseInternalMixer::mix16ToStereoSwap(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int leftAmp, int rightAmp) {
 	int32 *mixBufCurCell = &_mixBuf[2 * mixBufStartIndex];
 	uint32 ratio = ((uint32)inFrameCount << 16) / feedSize;
 	uint32 position = 0;
@@ -220,7 +220,7 @@ void IMuseDigiInternalMixer::mix16ToStereoSwap(const int16 *srcBuf, int32 inFram
 	}
 }
 
-void IMuseDigiInternalMixer::mix16(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int volume) {
+void IMuseInternalMixer::mix16(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int volume) {
 	int32 *mixBufCurCell = &_mixBuf[2 * mixBufStartIndex];
 	uint32 ratio = ((uint32)inFrameCount << 16) / feedSize;
 	uint32 position = 0;
@@ -270,7 +270,7 @@ void IMuseDigiInternalMixer::mix16(const int16 *srcBuf, int32 inFrameCount, uint
 	}
 }
 
-void IMuseDigiInternalMixer::mix16Swap(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int volume) {
+void IMuseInternalMixer::mix16Swap(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int volume) {
 	int32 *mixBufCurCell = &_mixBuf[2 * mixBufStartIndex];
 	uint32 ratio = ((uint32)inFrameCount << 16) / feedSize;
 	uint32 position = 0;
@@ -326,7 +326,7 @@ void IMuseDigiInternalMixer::mix16Swap(const int16 *srcBuf, int32 inFrameCount,
 	}
 }
 
-void IMuseDigiInternalMixer::mix(uint8 *srcBuf, int32 inFrameCount, int wordSize, int channelCount, int swapEndiannessFlag, int feedSize, int32 mixBufStartIndex, int volume, int pan) {
+void IMuseInternalMixer::mix(uint8 *srcBuf, int32 inFrameCount, int wordSize, int channelCount, int swapEndiannessFlag, int feedSize, int32 mixBufStartIndex, int volume, int pan) {
 	int channelVolume, channelPan, leftAmp, rightAmp;
 
 	// The original could divide by zero here, let's avoid that...
@@ -356,7 +356,7 @@ void IMuseDigiInternalMixer::mix(uint8 *srcBuf, int32 inFrameCount, int wordSize
 	}
 }
 
-int IMuseDigiInternalMixer::loop(uint8 **destBuffer, int len) {
+int IMuseInternalMixer::loop(uint8 **destBuffer, int len) {
 	if (!_mixBuf || !destBuffer || !len)
 		return -1;
 
@@ -377,7 +377,7 @@ int IMuseDigiInternalMixer::loop(uint8 **destBuffer, int len) {
 	return 0;
 }
 
-void IMuseDigiInternalMixer::endStream(int idx) {
+void IMuseInternalMixer::endStream(int idx) {
 	// We mark the stream as finished and then remove
 	// the reference: in this way, the stream will have time
 	// to flush the remaining sound data and will be disposed
@@ -388,7 +388,7 @@ void IMuseDigiInternalMixer::endStream(int idx) {
 	}
 }
 
-Audio::QueuingAudioStream *IMuseDigiInternalMixer::getStream(int idx) {
+Audio::QueuingAudioStream *IMuseInternalMixer::getStream(int idx) {
 	if (!_lowLatencyMode || idx == -1) {
 		// Stream for the original mode
 		return _stream;
diff --git a/engines/grim/imuse/dimuse_internalmixer.h b/engines/grim/imuse/imuse_internalmixer.h
similarity index 86%
rename from engines/grim/imuse/dimuse_internalmixer.h
rename to engines/grim/imuse/imuse_internalmixer.h
index c4852c3be04..97145baaca8 100644
--- a/engines/grim/imuse/dimuse_internalmixer.h
+++ b/engines/grim/imuse/imuse_internalmixer.h
@@ -19,8 +19,8 @@
  *
  */
 
-#ifndef GRIM_IMUSE_MIXER_H
-#define GRIM_IMUSE_MIXER_H
+#ifndef GRIM_IMUSE_INTERNALMIXER_H
+#define GRIM_IMUSE_INTERNALMIXER_H
 
 #include "common/scummsys.h"
 #include "common/mutex.h"
@@ -28,7 +28,7 @@
 #include "common/textconsole.h"
 #include "common/util.h"
 
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 #include "audio/mixer.h"
 #include "audio/audiostream.h"
 
@@ -40,7 +40,7 @@ class QueuingAudioStream;
 
 namespace Grim {
 
-class IMuseDigiInternalMixer {
+class IMuseInternalMixer {
 
 private:
 	uint8 _mixerTable[17 * 17];
@@ -61,8 +61,8 @@ private:
 	void mix16ToStereoSwap(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int leftAmp, int rightAmp);
 
 public:
-	IMuseDigiInternalMixer(Audio::Mixer *mixer, int sampleRate, bool lowLatencyMode = false);
-	~IMuseDigiInternalMixer();
+	IMuseInternalMixer(Audio::Mixer *mixer, int sampleRate, bool lowLatencyMode = false);
+	~IMuseInternalMixer();
 	int  init(int numChannels, int mixBufSize, int mixChannelsNum);
 	int  terminate();
 	int  clearMixerBuffer();
@@ -75,8 +75,8 @@ public:
 	void endStream(int idx);
 	Audio::QueuingAudioStream *getStream(int idx);
 
-	Audio::QueuingAudioStream *_separateStreams[DIMUSE_MAX_TRACKS];
-	Audio::SoundHandle _separateChannelHandles[DIMUSE_MAX_TRACKS];
+	Audio::QueuingAudioStream *_separateStreams[IMUSE_MAX_TRACKS];
+	Audio::SoundHandle _separateChannelHandles[IMUSE_MAX_TRACKS];
 };
 
 } // End of namespace Grim
diff --git a/engines/grim/imuse/imuse_scripts.cpp b/engines/grim/imuse/imuse_scripts.cpp
new file mode 100644
index 00000000000..fda13a93133
--- /dev/null
+++ b/engines/grim/imuse/imuse_scripts.cpp
@@ -0,0 +1,434 @@
+/* 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 3 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, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "engines/grim/imuse/imuse_engine.h"
+
+namespace Grim {
+
+#define GRIM_STATE_OFFSET   3
+#define GRIM_SEQ_OFFSET     185
+#define GRIM_STOP_SEQ_ATTR  227
+
+int IMuse::scriptParse(int cmd, int a, int b) {
+	if (_scriptInitializedFlag || !cmd) {
+		switch (cmd) {
+		case IMUSE_C_SCRIPT_INIT:
+			if (_scriptInitializedFlag) {
+				debug(5, "IMuse::scriptParse(): script module already initialized");
+				return -1;
+			} else {
+				_scriptInitializedFlag = true;
+				return scriptInit();
+			}
+		case IMUSE_C_SCRIPT_TERMINATE:
+			_scriptInitializedFlag = false;
+			return scriptTerminate();
+		case IMUSE_C_SCRIPT_SAVE:
+		case IMUSE_C_SCRIPT_RESTORE:
+			break;
+		case IMUSE_C_SCRIPT_REFRESH:
+			scriptRefresh();
+			return 0;
+		case IMUSE_C_SCRIPT_SET_STATE:
+			scriptSetState(a);
+			return 0;
+		case IMUSE_C_SCRIPT_SET_SEQUENCE:
+			scriptSetSequence(a);
+			return 0;
+		case IMUSE_C_SCRIPT_CUE_POINT:
+			scriptSetCuePoint(a);
+			return 0;
+		case IMUSE_C_SCRIPT_SET_ATTRIBUTE:
+			return scriptSetAttribute(a, b);
+		default:
+			debug(5, "IMuse::scriptParse(): unrecognized opcode (%d)", cmd);
+			return -1;
+		}
+	} else {
+		debug(5, "IMuse::scriptParse(): script module not initialized");
+		return -1;
+	}
+
+	return -1;
+}
+
+int IMuse::scriptInit() {
+	imInitFilelist();
+
+	_curMusicState = 0;
+	_curMusicSeq = 0;
+	_nextSeqToPlay = 0;
+	memset(_attributes, 0, sizeof(_attributes));
+	return 0;
+}
+
+int IMuse::scriptTerminate() {
+	scriptDeinit();
+
+	_curMusicState = 0;
+	_curMusicSeq = 0;
+	_nextSeqToPlay = 0;
+	memset(_attributes, 0, sizeof(_attributes));
+	return 0;
+}
+
+void IMuse::scriptRefresh() {
+	int soundId;
+
+	if (_attributes[GRIM_STOP_SEQ_ATTR]) {
+		scriptSetSequence(0);
+		_attributes[GRIM_STOP_SEQ_ATTR] = 0;
+	}
+
+	soundId = imGetNextSound(0);
+	while (soundId) {
+		if (imGetParam(soundId, IMUSE_P_SND_HAS_STREAM) && imGetParam(soundId, IMUSE_P_STREAM_BUFID) == IMUSE_BUFFER_MUSIC)
+			break;
+
+		soundId = imGetNextSound(soundId);
+	}
+
+	if (!soundId) {
+		if (_curMusicSeq)
+			scriptSetSequence(0);
+	}
+
+	imFlushSounds();
+}
+
+void IMuse::scriptSetState(int stateId) {
+	int num;
+
+	if (stateId == -1)
+		return;
+
+	for (num = 0; num < ARRAYSIZE(_grimStateMusicTable); num++) {
+		if (_grimStateMusicTable[num].soundId == stateId)
+			break;
+	}
+
+	if (num == ARRAYSIZE(_grimStateMusicTable))
+		return;
+
+	debug(5, "IMuse::scriptSetState(): Set music state: %s", _grimStateMusicTable[num].internalName);
+
+	if (num != _curMusicState) {
+		if (!_curMusicSeq)
+			scriptPlayMusic(num ? &_grimStateMusicTable[num] : nullptr, num, false);
+
+		_curMusicState = num;
+	}
+}
+
+void IMuse::scriptSetSequence(int seqId) {
+	int num;
+
+	if (seqId == -1)
+		return;
+
+	if (seqId == 0)
+		seqId = 2000;
+
+	for (num = 0; num < ARRAYSIZE(_grimSeqMusicTable); num++) {
+		if (_grimSeqMusicTable[num].soundId == seqId)
+			break;
+	}
+
+	if (num == ARRAYSIZE(_grimSeqMusicTable)) {
+		debug(5, "IMuse::scriptSetSequence(): bogus sequence");
+		return;
+	}
+
+	debug(5, "IMuse::scriptSetSequence(): Set music sequence: %s", _grimSeqMusicTable[num].internalName);
+
+	if (num == _curMusicSeq)
+		return;
+
+	if (num) {
+		if (_curMusicSeq && (_grimSeqMusicTable[_curMusicSeq].transitionId == 4 || _grimSeqMusicTable[_curMusicSeq].transitionId == 6)) {
+			_nextSeqToPlay = num;
+			return;
+		}
+
+		scriptPlayMusic(&_grimSeqMusicTable[num], 0, true);
+		_nextSeqToPlay = 0;
+		_attributes[GRIM_SEQ_OFFSET + num] = 1;
+		_curMusicSeq = num;
+	} else {
+		if (_nextSeqToPlay) {
+			scriptPlayMusic(&_grimSeqMusicTable[_nextSeqToPlay], 0, true);
+			_curMusicSeq = _nextSeqToPlay;
+			_nextSeqToPlay = 0;
+			_attributes[GRIM_SEQ_OFFSET + _curMusicSeq] = 1;
+			return;
+		}
+
+		scriptPlayMusic(_curMusicState ? &_grimStateMusicTable[_curMusicState] : nullptr, _curMusicState, true);
+		_curMusicSeq = 0;
+	}
+}
+
+void IMuse::scriptSetCuePoint(int cueId) {
+}
+
+int IMuse::scriptSetAttribute(int attrIndex, int attrVal) {
+	if (attrIndex == -1) {
+		if (attrVal == 0) {
+			imPause();
+		} else if (attrVal == 1) {
+			imResume();
+		} else if (attrVal == -1) {
+			memset(_attributes, 0, sizeof(_attributes));
+		}
+	} else if (attrIndex == 10000) {
+		char *dest = (char *)(intptr)attrVal;
+
+		for (int i = 0; i < ARRAYSIZE(_grimStateMusicTable); i++) {
+			memcpy(dest, _grimStateMusicTable[i].name, strlen(_grimStateMusicTable[i].name) + 1);
+			dest += strlen(_grimStateMusicTable[i].name) + 1;
+		}
+
+		for (int i = 0; i < ARRAYSIZE(_grimSeqMusicTable); i++) {
+			memcpy(dest, _grimSeqMusicTable[i].name, strlen(_grimSeqMusicTable[i].name) + 1);
+			dest += strlen(_grimSeqMusicTable[i].name) + 1;
+		}
+	} else if ((uint32)attrIndex >= ARRAYSIZE(_attributes)) {
+		debug(5, "IMuse::scriptSetAttribute(): bogus attribute");
+	} else if (attrVal != -1) {
+		debug(5, "IMuse::scriptSetAttribute(): Set attr %u to %u", attrIndex, attrVal);
+		_attributes[attrIndex] = attrVal;
+	}
+
+	return 0;
+}
+
+void IMuse::scriptSaveLoad(Common::Serializer &ser) {
+	if (ser.isLoading()) {
+		imUnloadAll();
+		imCloseAll();
+	}
+
+	ser.syncAsSint32LE(_curMusicState, VER(30));
+	ser.syncAsSint32LE(_curMusicSeq, VER(30));
+	ser.syncAsSint32LE(_nextSeqToPlay, VER(30));
+	ser.syncArray(_attributes, ARRAYSIZE(_attributes), Common::Serializer::Sint32LE, VER(30));
+	imSaveLoadFilelist(ser);
+}
+
+void IMuse::scriptDeinit() {
+	imStopAllSounds();
+	imUnloadAll();
+	imCloseAll();
+}
+
+int IMuse::scriptTriggerCallback(char *marker) {
+	if (marker[0] != '_') {
+		debug(5, "IMuse::scriptTriggerCallback(): got marker != '_end', callback ignored");
+		return -1;
+	}
+	_attributes[GRIM_STOP_SEQ_ATTR] = 1;
+	return 0;
+}
+
+void IMuse::scriptPlayMusic(const IMuseStateTable *tableEntry, int curSongEntryId, int isSequence) {
+	int hookId = 0;
+	int attribPos, oldSoundId, newSoundId, soundId;
+	int fadeTime, fadeDelay, fadeLength;
+	char fileName[64];
+
+	Common::StackLock lock(*_mutex);
+
+	if (tableEntry) {
+		attribPos = curSongEntryId;
+		if (curSongEntryId) {
+			if (tableEntry->attribPos)
+				attribPos = tableEntry->attribPos;
+
+			hookId = _attributes[GRIM_STATE_OFFSET + attribPos];
+
+			if (tableEntry->hookId) {
+				if (hookId || tableEntry->hookId <= 1) {
+					_attributes[GRIM_STATE_OFFSET + attribPos] = hookId + 1;
+					if (hookId + 1 > tableEntry->hookId)
+						_attributes[GRIM_STATE_OFFSET + attribPos] = 1;
+				} else {
+					_attributes[GRIM_STATE_OFFSET + attribPos] = 2;
+				}
+			}
+		}
+	}
+
+	if (!hookId)
+		hookId = 100;
+
+	// Fade out any music track which is not streamed
+	for (soundId = imGetNextSound(0); soundId; soundId = imGetNextSound(soundId)) {
+		if (imGetParam(soundId, IMUSE_P_GROUP) == IMUSE_GROUP_MUSICEFF && !imGetParam(soundId, IMUSE_P_SND_HAS_STREAM))
+			imFadeParam(soundId, IMUSE_P_VOLUME, 0, 120);
+	}
+
+	oldSoundId = 0;
+	for (soundId = imGetNextSound(0); soundId; soundId = imGetNextSound(soundId)) {
+		if (imGetParam(soundId, IMUSE_P_SND_HAS_STREAM) && imGetParam(soundId, IMUSE_P_STREAM_BUFID) == IMUSE_BUFFER_MUSIC) {
+			oldSoundId = soundId;
+			break;
+		}
+	}
+
+	if (!tableEntry) {
+		if (oldSoundId)
+			imFadeParam(oldSoundId, IMUSE_P_VOLUME, 0, 120);
+		return;
+	}
+
+	fadeTime = tableEntry->fadeTime;
+	if (!fadeTime)
+		fadeTime = 1000;
+
+	fadeDelay = fadeTime;
+	fadeLength = (3 * fadeTime) / 50;
+
+	switch (tableEntry->transitionId) {
+	case 0:
+		debug(5, "IMuse::scriptPlayMusic(): NULL transition, ignored");
+		break;
+	case 2:
+	case 3:
+	case 4:
+	case 10:
+	case 11:
+	case 12:
+		// TODO
+		// The original remaps the name through a table which always appends ".IMC"
+		Common::strlcpy(fileName, tableEntry->name, sizeof(fileName));
+		Common::strlcat(fileName, ".IMC", sizeof(fileName));
+
+		debug(5, "IMuse::scriptPlayMusic(): opening %s", fileName);
+		newSoundId = imOpenSound(fileName, 0);
+
+		if (!newSoundId) {
+			debug(5, "IMuse::scriptPlayMusic(): unable to open %s", fileName);
+			if (oldSoundId)
+				imFadeParam(oldSoundId, IMUSE_P_VOLUME, 0, 60);
+			return;
+		}
+
+		if (tableEntry->transitionId == 4) {
+			_attributes[GRIM_STOP_SEQ_ATTR] = 0;
+			imSetTrigger(newSoundId, "_end", IMUSE_C_SCRIPT_CALLBACK);
+		}
+
+		debug(5, "IMuse::scriptPlayMusic(): HOOK=%d", hookId);
+
+		if (!oldSoundId) {
+			debug(5, "IMuse::scriptPlayMusic(): no stream sound");
+			if (imStartStream(newSoundId, 126, IMUSE_BUFFER_MUSIC))
+				debug(5, "IMuse::scriptPlayMusic(): failed to start the stream for sound %d", newSoundId);
+
+			imSetParam(newSoundId, IMUSE_P_VOLUME, 0);
+			imFadeParam(newSoundId, IMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			imSetParam(newSoundId, IMUSE_P_PAN, tableEntry->pan);
+			imSetParam(newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+			imSetHook(newSoundId, hookId);
+		} else if (tableEntry->transitionId == 2) {
+			imSwitchStream(oldSoundId, newSoundId, fadeDelay, 0, 0);
+			debug(5, "IMuse::scriptPlayMusic(): FADE=%d, vol=%d", fadeDelay, tableEntry->volume);
+			imFadeParam(newSoundId, IMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			imFadeParam(newSoundId, IMUSE_P_PAN, tableEntry->pan, fadeLength);
+			imSetParam(newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+			imSetHook(newSoundId, hookId);
+			imProcessStreams();
+		} else if (oldSoundId == newSoundId) {
+			imFadeParam(newSoundId, IMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			debug(5, "IMuse::scriptPlayMusic(): fading VOL=%d", tableEntry->volume);
+			if (tableEntry->pan) {
+				imFadeParam(newSoundId, IMUSE_P_PAN, tableEntry->pan, fadeLength);
+				debug(5, "IMuse::scriptPlayMusic(): and PAN=%d", tableEntry->pan);
+			}
+		} else if (!isSequence && tableEntry->attribPos && tableEntry->attribPos == _grimStateMusicTable[_curMusicState].attribPos) {
+			imSwitchStream(oldSoundId, newSoundId, fadeDelay, 0, 1);
+			imFadeParam(newSoundId, IMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			imFadeParam(newSoundId, IMUSE_P_PAN, tableEntry->pan, fadeLength);
+			imSetParam(newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+			if (hookId == 100)
+				imSetHook(newSoundId, 100);
+			imProcessStreams();
+		} else if (tableEntry->transitionId == 10 || tableEntry->transitionId == 12) {
+			if (tableEntry->transitionId == 12) {
+				imSetHook(oldSoundId, 99);
+				imSetTrigger(oldSoundId, "clear", IMUSE_C_SET_HOOK, oldSoundId, 128);
+			}
+
+			imSetTrigger(oldSoundId, "exit", IMUSE_C_SWITCH_STREAM, oldSoundId, newSoundId, fadeDelay, 1, 0);
+			imSetTrigger(oldSoundId, "exit", IMUSE_C_FADE_PARAM, newSoundId, IMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			imSetTrigger(oldSoundId, "exit", IMUSE_C_FADE_PARAM, newSoundId, IMUSE_P_PAN, tableEntry->pan, fadeLength);
+			imSetTrigger(oldSoundId, "exit", IMUSE_C_SET_PARAM, newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+			imSetTrigger(oldSoundId, "exit", IMUSE_C_SET_HOOK, newSoundId, hookId);
+			imProcessStreams();
+		} else if (tableEntry->transitionId == 11) {
+			imSetTrigger(oldSoundId, "exit2", IMUSE_C_SWITCH_STREAM, oldSoundId, newSoundId, fadeDelay, 1, 0);
+			imSetTrigger(oldSoundId, "exit2", IMUSE_C_FADE_PARAM, newSoundId, IMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			imSetTrigger(oldSoundId, "exit2", IMUSE_C_FADE_PARAM, newSoundId, IMUSE_P_PAN, tableEntry->pan, fadeLength);
+			imSetTrigger(oldSoundId, "exit2", IMUSE_C_SET_PARAM, newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+			imSetTrigger(oldSoundId, "exit2", IMUSE_C_SET_HOOK, newSoundId, hookId);
+			imProcessStreams();
+		} else {
+			imSwitchStream(oldSoundId, newSoundId, fadeDelay, 0, 0);
+			debug(5, "IMuse::scriptPlayMusic(): FADE=%d, vol=%d", fadeDelay, tableEntry->volume);
+			imFadeParam(newSoundId, IMUSE_P_VOLUME, tableEntry->volume, fadeLength);
+			imFadeParam(newSoundId, IMUSE_P_PAN, tableEntry->pan, fadeLength);
+			debug(5, "IMuse::scriptPlayMusic(): set pan=%d", tableEntry->pan);
+			imSetParam(newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+			imSetHook(newSoundId, hookId);
+			imProcessStreams();
+		}
+
+		imCloseSound(newSoundId);
+		imSetParam(newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+		break;
+	case 5:
+		break;
+	case 6:
+		_attributes[GRIM_STOP_SEQ_ATTR] = 0;
+		imSetTrigger(IMUSE_SMUSH_SOUNDID + IMUSE_BUFFER_MUSIC, "_end", IMUSE_C_SCRIPT_CALLBACK);
+		break;
+	case 7:
+		if (oldSoundId)
+			imFadeParam(oldSoundId, IMUSE_P_VOLUME, 0, 60);
+		break;
+	case 8:
+		if (oldSoundId)
+			imSetHook(oldSoundId, 100);
+		break;
+	case 9:
+		if (oldSoundId)
+			imSetHook(oldSoundId, 99);
+
+		_attributes[GRIM_STOP_SEQ_ATTR] = 0;
+		imSetTrigger(oldSoundId, "_end", IMUSE_C_SCRIPT_CALLBACK);
+		break;
+	default:
+		debug(5, "IMuse::scriptPlayMusic(): bogus transition type, ignored");
+		break;
+	}
+}
+
+} // End of namespace Grim
diff --git a/engines/grim/imuse/dimuse_streamer.cpp b/engines/grim/imuse/imuse_streamer.cpp
similarity index 77%
rename from engines/grim/imuse/dimuse_streamer.cpp
rename to engines/grim/imuse/imuse_streamer.cpp
index f56d7007738..b6ccd8cfa01 100644
--- a/engines/grim/imuse/dimuse_streamer.cpp
+++ b/engines/grim/imuse/imuse_streamer.cpp
@@ -19,38 +19,38 @@
  *
  */
 
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 
 namespace Grim {
 
-int IMuseDigital::streamerInit() {
-	for (int l = 0; l < DIMUSE_MAX_STREAMS; l++) {
+int IMuse::streamerInit() {
+	for (int l = 0; l < IMUSE_MAX_STREAMS; l++) {
 		_streams[l].soundId = 0;
 	}
 	_lastStreamLoaded = nullptr;
 	return 0;
 }
 
-IMuseDigiStream *IMuseDigital::streamerAllocateSound(int soundId, int bufId, int32 maxRead) {
-	IMuseDigiSndBuffer *bufInfoPtr = filesGetBufInfo(bufId);
+IMuseStream *IMuse::streamerAllocateSound(int soundId, int bufId, int32 maxRead) {
+	IMuseSndBuffer *bufInfoPtr = filesGetBufInfo(bufId);
 	if (!bufInfoPtr) {
-		debug(5, "IMuseDigital::streamerAlloc(): ERROR: couldn't get buffer info");
+		debug(5, "IMuse::streamerAlloc(): ERROR: couldn't get buffer info");
 		return nullptr;
 	}
 
 	if ((bufInfoPtr->bufSize / 4) <= maxRead) {
-		debug(5, "IMuseDigital::streamerAlloc(): ERROR: maxRead too big for buffer");
+		debug(5, "IMuse::streamerAlloc(): ERROR: maxRead too big for buffer");
 		return nullptr;
 	}
 
-	for (int l = 0; l < DIMUSE_MAX_STREAMS; l++) {
+	for (int l = 0; l < IMUSE_MAX_STREAMS; l++) {
 		if (_streams[l].soundId && _streams[l].bufId == bufId) {
-			debug(5, "IMuseDigital::streamerAlloc(): ERROR: stream bufId %d already in use", bufId);
+			debug(5, "IMuse::streamerAlloc(): ERROR: stream bufId %d already in use", bufId);
 			return nullptr;
 		}
 	}
 
-	for (int l = 0; l < DIMUSE_MAX_STREAMS; l++) {
+	for (int l = 0; l < IMUSE_MAX_STREAMS; l++) {
 		if (!_streams[l].soundId) {
 			_streams[l].endOffset = filesSeek(soundId, 0, SEEK_END);
 			_streams[l].curOffset = 0;
@@ -67,11 +67,11 @@ IMuseDigiStream *IMuseDigital::streamerAllocateSound(int soundId, int bufId, int
 			return &_streams[l];
 		}
 	}
-	debug(5, "IMuseDigital::streamerAlloc(): ERROR: no spare streams");
+	debug(5, "IMuse::streamerAlloc(): ERROR: no spare streams");
 	return nullptr;
 }
 
-int IMuseDigital::streamerClearSoundInStream(IMuseDigiStream *streamPtr) {
+int IMuse::streamerClearSoundInStream(IMuseStream *streamPtr) {
 	streamPtr->soundId = 0;
 	if (_lastStreamLoaded == streamPtr) {
 		_lastStreamLoaded = 0;
@@ -79,13 +79,13 @@ int IMuseDigital::streamerClearSoundInStream(IMuseDigiStream *streamPtr) {
 	return 0;
 }
 
-int IMuseDigital::streamerProcessStreams() {
+int IMuse::streamerProcessStreams() {
 	dispatchPredictFirstStream();
 
-	IMuseDigiStream *stream1 = nullptr;
-	IMuseDigiStream *stream2 = nullptr;
+	IMuseStream *stream1 = nullptr;
+	IMuseStream *stream2 = nullptr;
 
-	for (int l = 0; l < DIMUSE_MAX_STREAMS; l++) {
+	for (int l = 0; l < IMUSE_MAX_STREAMS; l++) {
 		if ((_streams[l].soundId) && (!_streams[l].paused)) {
 			if (stream1) {
 				if (!stream2) {
@@ -143,7 +143,7 @@ int IMuseDigital::streamerProcessStreams() {
 	}
 }
 
-uint8 *IMuseDigital::streamerGetStreamBuffer(IMuseDigiStream *streamPtr, int size) {
+uint8 *IMuse::streamerGetStreamBuffer(IMuseStream *streamPtr, int size) {
 	if (size > streamerGetFreeBufferAmount(streamPtr) || streamPtr->maxRead < size)
 		return 0;
 
@@ -162,7 +162,7 @@ uint8 *IMuseDigital::streamerGetStreamBuffer(IMuseDigiStream *streamPtr, int siz
 	return ptr;
 }
 
-uint8 *IMuseDigital::streamerGetStreamBufferAtOffset(IMuseDigiStream *streamPtr, int32 offset, int size) {
+uint8 *IMuse::streamerGetStreamBufferAtOffset(IMuseStream *streamPtr, int32 offset, int size) {
 	if (offset + size > streamerGetFreeBufferAmount(streamPtr) || streamPtr->maxRead < size)
 		return 0;
 
@@ -178,7 +178,7 @@ uint8 *IMuseDigital::streamerGetStreamBufferAtOffset(IMuseDigiStream *streamPtr,
 	return &streamPtr->buf[offsetReadIndex];
 }
 
-int IMuseDigital::streamerSetReadIndex(IMuseDigiStream *streamPtr, int offset) {
+int IMuse::streamerSetReadIndex(IMuseStream *streamPtr, int offset) {
 	_streamerBailFlag = 1;
 	if (offset > streamerGetFreeBufferAmount(streamPtr))
 		return -1;
@@ -190,7 +190,7 @@ int IMuseDigital::streamerSetReadIndex(IMuseDigiStream *streamPtr, int offset) {
 	return 0;
 }
 
-int IMuseDigital::streamerSetLoadIndex(IMuseDigiStream *streamPtr, int offset) {
+int IMuse::streamerSetLoadIndex(IMuseStream *streamPtr, int offset) {
 	_streamerBailFlag = 1;
 	if (offset > streamerGetFreeBufferAmount(streamPtr))
 		return -1;
@@ -202,14 +202,14 @@ int IMuseDigital::streamerSetLoadIndex(IMuseDigiStream *streamPtr, int offset) {
 	return 0;
 }
 
-int IMuseDigital::streamerGetFreeBufferAmount(IMuseDigiStream *streamPtr) {
+int IMuse::streamerGetFreeBufferAmount(IMuseStream *streamPtr) {
 	int32 freeBufferSize = streamPtr->loadIndex - streamPtr->readIndex;
 	if (freeBufferSize < 0)
 		freeBufferSize += streamPtr->bufFreeSize;
 	return freeBufferSize;
 }
 
-int IMuseDigital::streamerSetSoundToStreamFromOffset(IMuseDigiStream *streamPtr, int soundId, int32 offset) {
+int IMuse::streamerSetSoundToStreamFromOffset(IMuseStream *streamPtr, int soundId, int32 offset) {
 	_streamerBailFlag = 1;
 	streamPtr->soundId = soundId;
 	streamPtr->curOffset = offset;
@@ -221,7 +221,7 @@ int IMuseDigital::streamerSetSoundToStreamFromOffset(IMuseDigiStream *streamPtr,
 	return 0;
 }
 
-void IMuseDigital::streamerQueryStream(IMuseDigiStream *streamPtr, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
+void IMuse::streamerQueryStream(IMuseStream *streamPtr, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
 	dispatchPredictFirstStream();
 
 	bufSize = streamPtr->bufFreeSize;
@@ -230,12 +230,12 @@ void IMuseDigital::streamerQueryStream(IMuseDigiStream *streamPtr, int32 &bufSiz
 	paused = streamPtr->paused;
 }
 
-int IMuseDigital::streamerFeedStream(IMuseDigiStream *streamPtr, uint8 *srcBuf, int32 sizeToFeed, int paused) {
+int IMuse::streamerFeedStream(IMuseStream *streamPtr, uint8 *srcBuf, int32 sizeToFeed, int paused) {
 	int32 size = streamPtr->readIndex - streamPtr->loadIndex;
 	if (size <= 0)
 		size += streamPtr->bufFreeSize;
 	if (sizeToFeed > (size - 4)) {
-		debug(5, "IMuseDigital::streamerFeedStream(): WARNING: buffer overflow");
+		debug(5, "IMuse::streamerFeedStream(): WARNING: buffer overflow");
 		streamerSetReadIndex(streamPtr, sizeToFeed - (size - 4) - (sizeToFeed - (size - 4)) % 12 + 12);
 	}
 
@@ -262,7 +262,7 @@ int IMuseDigital::streamerFeedStream(IMuseDigiStream *streamPtr, uint8 *srcBuf,
 	return 0;
 }
 
-int IMuseDigital::streamerFetchData(IMuseDigiStream *streamPtr) {
+int IMuse::streamerFetchData(IMuseStream *streamPtr) {
 	if (streamPtr->endOffset == 0) {
 		streamPtr->endOffset = filesSeek(streamPtr->soundId, 0, SEEK_END);
 	}
@@ -297,7 +297,7 @@ int IMuseDigital::streamerFetchData(IMuseDigiStream *streamPtr) {
 			}
 
 			if (filesSeek(streamPtr->soundId, streamPtr->curOffset, SEEK_SET) != streamPtr->curOffset) {
-				debug(5, "IMuseDigital::streamerFetchData(): ERROR: invalid seek in streamer (%d), pausing stream...", streamPtr->curOffset);
+				debug(5, "IMuse::streamerFetchData(): ERROR: invalid seek in streamer (%d), pausing stream...", streamPtr->curOffset);
 				streamPtr->paused = 1;
 				return 0;
 			}
@@ -328,7 +328,7 @@ int IMuseDigital::streamerFetchData(IMuseDigiStream *streamPtr) {
 				return 0;
 		}
 
-		debug(5, "IMuseDigital::streamerFetchData(): ERROR: unable to load the correct amount of data (req=%d, act=%d)", requestedAmount, actualAmount);
+		debug(5, "IMuse::streamerFetchData(): ERROR: unable to load the correct amount of data (req=%d, act=%d)", requestedAmount, actualAmount);
 		_lastStreamLoaded = nullptr;
 	}
 
diff --git a/engines/grim/imuse/dimuse_tables.cpp b/engines/grim/imuse/imuse_tables.cpp
similarity index 99%
rename from engines/grim/imuse/dimuse_tables.cpp
rename to engines/grim/imuse/imuse_tables.cpp
index 3b7bc0cd6dd..8b5db93056e 100644
--- a/engines/grim/imuse/dimuse_tables.cpp
+++ b/engines/grim/imuse/imuse_tables.cpp
@@ -21,11 +21,11 @@
 
 #include "common/util.h"
 
-#include "engines/grim/imuse/dimuse_tables.h"
+#include "engines/grim/imuse/imuse_tables.h"
 
 namespace Grim {
 
-const IMuseDigiStateTable _grimStateMusicTable[181] = {
+const IMuseStateTable _grimStateMusicTable[181] = {
 	{"",                        0, 1000, "STATE_NULL",           0,  0,   0, 127, 0}, /* 000 */
 	{"",                        0, 1999, "stateNoChange",        0,  0,   0, 127, 0}, /* 001 */
 	{"1001 - Manny's Office",   3, 1001, "stateMO",              0,  0,   0, 127, 0}, /* 002 */
@@ -209,7 +209,7 @@ const IMuseDigiStateTable _grimStateMusicTable[181] = {
 	{"",                        0, 1500, "stateMenu",            0,  0,   0, 127, 0}, /* 180 */
 };
 
-const IMuseDigiStateTable _grimSeqMusicTable[41] = {
+const IMuseStateTable _grimSeqMusicTable[41] = {
 	{"",                        0, 2000, "SEQ_NULL",             0,  0, 300, 127, 0}, /* 000 */
 	{"2001 - Climb Rope",       2, 2001, "seqClimbRope",         0,  0, 300, 127, 0}, /* 001 */
 	{"2010 - Glottis OK",       2, 2010, "seqGlottisOK",         0,  0, 300, 127, 0}, /* 002 */
diff --git a/engines/grim/imuse/dimuse_tables.h b/engines/grim/imuse/imuse_tables.h
similarity index 89%
rename from engines/grim/imuse/dimuse_tables.h
rename to engines/grim/imuse/imuse_tables.h
index a18c0d7d3eb..94401d243e8 100644
--- a/engines/grim/imuse/dimuse_tables.h
+++ b/engines/grim/imuse/imuse_tables.h
@@ -26,7 +26,7 @@
 
 namespace Grim {
 
-struct IMuseDigiStateTable {
+struct IMuseStateTable {
 	char name[32];
 	int transitionId;
 	int soundId;
@@ -38,8 +38,8 @@ struct IMuseDigiStateTable {
 	int pan;
 };
 
-extern const IMuseDigiStateTable _grimStateMusicTable[181];
-extern const IMuseDigiStateTable _grimSeqMusicTable[41];
+extern const IMuseStateTable _grimStateMusicTable[181];
+extern const IMuseStateTable _grimSeqMusicTable[41];
 
 // Sound id of a state, given its position in the table of the old iMUSE
 int grimLegacyStateSoundId(int tableIndex);
diff --git a/engines/grim/imuse/dimuse_tracks.cpp b/engines/grim/imuse/imuse_tracks.cpp
similarity index 78%
rename from engines/grim/imuse/dimuse_tracks.cpp
rename to engines/grim/imuse/imuse_tracks.cpp
index 8c36f781c2d..66397f6725a 100644
--- a/engines/grim/imuse/dimuse_tracks.cpp
+++ b/engines/grim/imuse/imuse_tracks.cpp
@@ -19,12 +19,12 @@
  *
  */
 
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 
 namespace Grim {
 
-int IMuseDigital::tracksInit() {
-	_trackCount = DIMUSE_MAX_TRACKS;
+int IMuse::tracksInit() {
+	_trackCount = IMUSE_MAX_TRACKS;
 	_tracksPauseTimer = 0;
 	_trackList = nullptr;
 
@@ -62,15 +62,15 @@ int IMuseDigital::tracksInit() {
 	return 0;
 }
 
-void IMuseDigital::tracksPause() {
+void IMuse::tracksPause() {
 	_tracksPauseTimer = 1;
 }
 
-void IMuseDigital::tracksResume() {
+void IMuse::tracksResume() {
 	_tracksPauseTimer = 0;
 }
 
-void IMuseDigital::tracksSaveLoad(Common::Serializer &ser) {
+void IMuse::tracksSaveLoad(Common::Serializer &ser) {
 	Common::StackLock lock(*_mutex);
 	dispatchSaveLoad(ser);
 
@@ -104,15 +104,15 @@ void IMuseDigital::tracksSaveLoad(Common::Serializer &ser) {
 	}
 }
 
-void IMuseDigital::tracksSetGroupVol() {
-	IMuseDigiTrack* curTrack = _trackList;
+void IMuse::tracksSetGroupVol() {
+	IMuseTrack* curTrack = _trackList;
 	while (curTrack) {
 		curTrack->effVol = ((curTrack->vol + 1) * _groupsHandler->getGroupVol(curTrack->group)) / 128;
 		curTrack = curTrack->next;
 	}
 }
 
-void IMuseDigital::tracksCallback() {
+void IMuse::tracksCallback() {
 	if (_tracksPauseTimer) {
 		if (++_tracksPauseTimer < 3)
 			return;
@@ -126,7 +126,7 @@ void IMuseDigital::tracksCallback() {
 	// This is not part of the original implementation, but it's used to yield
 	// smooth audio hopefully on every device.
 	if (_internalMixer->_stream->endOfData() && _checkForUnderrun) {
-		debug(5, "IMuseDigital::tracksCallback(): WARNING: audio buffer underrun, adapting the buffer queue count...");
+		debug(5, "IMuse::tracksCallback(): WARNING: audio buffer underrun, adapting the buffer queue count...");
 
 		adaptBufferCount();
 
@@ -156,10 +156,10 @@ void IMuseDigital::tracksCallback() {
 			_internalMixer->clearMixerBuffer();
 
 			if (!_tracksPauseTimer) {
-				IMuseDigiTrack *track = _trackList;
+				IMuseTrack *track = _trackList;
 
 				while (track) {
-					IMuseDigiTrack *next = track->next;
+					IMuseTrack *next = track->next;
 					dispatchProcessDispatches(track, _outputFeedSize, _outputSampleRate);
 					track = next;
 				};
@@ -170,7 +170,7 @@ void IMuseDigital::tracksCallback() {
 	}
 }
 
-void IMuseDigital::tracksLowLatencyCallback() {
+void IMuse::tracksLowLatencyCallback() {
 	// Why do we need a low latency mode?
 	//
 	// For every audio callback, this engine works by collecting all the sound
@@ -201,11 +201,11 @@ void IMuseDigital::tracksLowLatencyCallback() {
 
 	dispatchPredictFirstStream();
 
-	IMuseDigiTrack *track = _trackList;
+	IMuseTrack *track = _trackList;
 
 	while (track) {
 
-		IMuseDigiTrack *next = track->next;
+		IMuseTrack *next = track->next;
 		int idx = track->index;
 
 		bool canQueueBufs = (int)_internalMixer->getStream(idx)->numQueuedStreams() < (_maxQueuedStreams + 1);
@@ -235,14 +235,14 @@ void IMuseDigital::tracksLowLatencyCallback() {
 	}
 }
 
-int IMuseDigital::tracksStartSound(int soundId, int tryPriority, int group) {
+int IMuse::tracksStartSound(int soundId, int tryPriority, int group) {
 	int priority = clampNumber(tryPriority, 0, 127);
 
-	debug(5, "IMuseDigital::tracksStartSound(): sound %d with priority %d and group %d", soundId, priority, group);
-	IMuseDigiTrack *allocatedTrack = tracksReserveTrack(priority);
+	debug(5, "IMuse::tracksStartSound(): sound %d with priority %d and group %d", soundId, priority, group);
+	IMuseTrack *allocatedTrack = tracksReserveTrack(priority);
 
 	if (!allocatedTrack) {
-		debug(5, "IMuseDigital::tracksStartSound(): ERROR: couldn't find a spare track to allocate sound %d", soundId);
+		debug(5, "IMuse::tracksStartSound(): ERROR: couldn't find a spare track to allocate sound %d", soundId);
 		return -6;
 	}
 
@@ -260,7 +260,7 @@ int IMuseDigital::tracksStartSound(int soundId, int tryPriority, int group) {
 	allocatedTrack->jumpHook = 0;
 
 	if (dispatchAllocateSound(allocatedTrack, group)) {
-		debug(5, "IMuseDigital::tracksStartSound(): ERROR: dispatch couldn't start sound %d", soundId);
+		debug(5, "IMuse::tracksStartSound(): ERROR: dispatch couldn't start sound %d", soundId);
 		allocatedTrack->soundId = 0;
 		return -1;
 	}
@@ -272,12 +272,12 @@ int IMuseDigital::tracksStartSound(int soundId, int tryPriority, int group) {
 	return 0;
 }
 
-int IMuseDigital::tracksStopSound(int soundId) {
+int IMuse::tracksStopSound(int soundId) {
 	if (!_trackList)
 		return -1;
 
-	IMuseDigiTrack *nextTrack = _trackList;
-	IMuseDigiTrack *curTrack;
+	IMuseTrack *nextTrack = _trackList;
+	IMuseTrack *curTrack;
 	int result = -1;
 
 	while (nextTrack) {
@@ -292,10 +292,10 @@ int IMuseDigital::tracksStopSound(int soundId) {
 	return result;
 }
 
-int IMuseDigital::tracksStopAllSounds() {
+int IMuse::tracksStopAllSounds() {
 	Common::StackLock lock(*_mutex);
-	IMuseDigiTrack *nextTrack = _trackList;
-	IMuseDigiTrack *curTrack;
+	IMuseTrack *nextTrack = _trackList;
+	IMuseTrack *curTrack;
 
 	while (nextTrack) {
 		curTrack = nextTrack;
@@ -306,9 +306,9 @@ int IMuseDigital::tracksStopAllSounds() {
 	return 0;
 }
 
-int IMuseDigital::tracksGetNextSound(int soundId) {
+int IMuse::tracksGetNextSound(int soundId) {
 	int foundSoundId = 0;
-	IMuseDigiTrack *track = _trackList;
+	IMuseTrack *track = _trackList;
 	while (track) {
 		if (track->soundId > soundId) {
 			if (!foundSoundId || track->soundId < foundSoundId) {
@@ -321,13 +321,13 @@ int IMuseDigital::tracksGetNextSound(int soundId) {
 	return foundSoundId;
 }
 
-int IMuseDigital::tracksQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
+int IMuse::tracksQueryStream(int soundId, int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused) {
 	if (!_trackList) {
-		debug(5, "IMuseDigital::tracksQueryStream(): WARNING: empty trackList, ignoring call...");
+		debug(5, "IMuse::tracksQueryStream(): WARNING: empty trackList, ignoring call...");
 		return -1;
 	}
 
-	IMuseDigiTrack *track = _trackList;
+	IMuseTrack *track = _trackList;
 	do {
 		if (track->soundId) {
 			if (soundId == track->soundId && track->dispatchPtr->streamPtr) {
@@ -338,15 +338,15 @@ int IMuseDigital::tracksQueryStream(int soundId, int32 &bufSize, int32 &critical
 		track = track->next;
 	} while (track);
 
-	debug(5, "IMuseDigital::tracksQueryStream(): WARNING: couldn't find sound %d in trackList, ignoring call...", soundId);
+	debug(5, "IMuse::tracksQueryStream(): WARNING: couldn't find sound %d in trackList, ignoring call...", soundId);
 	return -1;
 }
 
-int IMuseDigital::tracksFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused) {
+int IMuse::tracksFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused) {
 	if (!_trackList)
 		return -1;
 
-	IMuseDigiTrack *track = _trackList;
+	IMuseTrack *track = _trackList;
 	do {
 		if (track->soundId != 0) {
 			if (track->soundId == soundId && track->dispatchPtr->streamPtr) {
@@ -360,7 +360,7 @@ int IMuseDigital::tracksFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed,
 	return -1;
 }
 
-void IMuseDigital::tracksClear(IMuseDigiTrack *trackPtr) {
+void IMuse::tracksClear(IMuseTrack *trackPtr) {
 	Common::StackLock lock(*_mutex);
 
 	removeTrackFromList(&_trackList, trackPtr);
@@ -380,53 +380,53 @@ void IMuseDigital::tracksClear(IMuseDigiTrack *trackPtr) {
 	trackPtr->soundId = 0;
 }
 
-int IMuseDigital::tracksSetParam(int soundId, int opcode, int value) {
+int IMuse::tracksSetParam(int soundId, int opcode, int value) {
 	if (!_trackList)
 		return -4;
 
-	IMuseDigiTrack *track = _trackList;
+	IMuseTrack *track = _trackList;
 	while (track) {
 		if (track->soundId == soundId) {
 			switch (opcode) {
-			case DIMUSE_P_GROUP:
+			case IMUSE_P_GROUP:
 				if (value >= 16)
 					return -5;
 				track->group = value;
 				track->effVol = ((track->vol + 1) * _groupsHandler->getGroupVol(value)) / 128;
 				return 0;
-			case DIMUSE_P_PRIORITY:
+			case IMUSE_P_PRIORITY:
 				if (value > 127)
 					return -5;
 				track->priority = value;
 				return 0;
-			case DIMUSE_P_VOLUME:
+			case IMUSE_P_VOLUME:
 				if (value > 127)
 					return -5;
 				track->vol = value;
 				track->effVol = ((value + 1) * _groupsHandler->getGroupVol(track->group)) / 128;
 				return 0;
-			case DIMUSE_P_PAN:
+			case IMUSE_P_PAN:
 				if (value > 127)
 					return -5;
 				track->pan = value;
 				return 0;
-			case DIMUSE_P_DETUNE:
+			case IMUSE_P_DETUNE:
 				if (value < -9216 || value > 9216)
 					return -5;
 				track->detune = value;
 				track->pitchShift = value + track->transpose * 256;
 				return 0;
-			case DIMUSE_P_TRANSPOSE:
+			case IMUSE_P_TRANSPOSE:
 				if (value < 0 || value > 4095)
 					return -5;
 
 				track->pitchShift = value;
 				return 0;
-			case DIMUSE_P_MAILBOX:
+			case IMUSE_P_MAILBOX:
 				track->mailbox = value;
 				return 0;
 			default:
-				debug(5, "IMuseDigital::tracksSetParam(): unknown opcode %d", opcode);
+				debug(5, "IMuse::tracksSetParam(): unknown opcode %d", opcode);
 				return -5;
 			}
 		}
@@ -436,47 +436,47 @@ int IMuseDigital::tracksSetParam(int soundId, int opcode, int value) {
 	return -4;
 }
 
-int IMuseDigital::tracksGetParam(int soundId, int opcode) {
+int IMuse::tracksGetParam(int soundId, int opcode) {
 	if (!_trackList) {
-		if (opcode != DIMUSE_P_SND_TRACK_NUM)
+		if (opcode != IMUSE_P_SND_TRACK_NUM)
 			return -4;
 		else
 			return 0;
 	}
 
-	IMuseDigiTrack *track = _trackList;
+	IMuseTrack *track = _trackList;
 	int l = 0;
 	do {
 		if (track->soundId == soundId) {
 			switch (opcode) {
-			case DIMUSE_P_BOGUS_ID:
+			case IMUSE_P_BOGUS_ID:
 				return -1;
-			case DIMUSE_P_SND_TRACK_NUM:
+			case IMUSE_P_SND_TRACK_NUM:
 				l++;
 				break;
-			case DIMUSE_P_TRIGS_SNDS:
+			case IMUSE_P_TRIGS_SNDS:
 				return -1;
-			case DIMUSE_P_MARKER:
+			case IMUSE_P_MARKER:
 				return track->marker;
-			case DIMUSE_P_GROUP:
+			case IMUSE_P_GROUP:
 				return track->group;
-			case DIMUSE_P_PRIORITY:
+			case IMUSE_P_PRIORITY:
 				return track->priority;
-			case DIMUSE_P_VOLUME:
+			case IMUSE_P_VOLUME:
 				return track->vol;
-			case DIMUSE_P_PAN:
+			case IMUSE_P_PAN:
 				return track->pan;
-			case DIMUSE_P_DETUNE:
+			case IMUSE_P_DETUNE:
 				return track->detune;
-			case DIMUSE_P_TRANSPOSE:
+			case IMUSE_P_TRANSPOSE:
 				return track->transpose;
-			case DIMUSE_P_MAILBOX:
+			case IMUSE_P_MAILBOX:
 				return track->mailbox;
-			case DIMUSE_P_SND_HAS_STREAM:
+			case IMUSE_P_SND_HAS_STREAM:
 				return (track->dispatchPtr->streamPtr != 0);
-			case DIMUSE_P_STREAM_BUFID:
+			case IMUSE_P_STREAM_BUFID:
 				return track->dispatchPtr->streamBufID;
-			case DIMUSE_P_SND_POS_IN_MS: // getCurSoundPositionInMs
+			case IMUSE_P_SND_POS_IN_MS: // getCurSoundPositionInMs
 				if (track->dispatchPtr->wordSize == 0)
 					return 0;
 				if (track->dispatchPtr->sampleRate == 0)
@@ -492,19 +492,19 @@ int IMuseDigital::tracksGetParam(int soundId, int opcode) {
 		track = track->next;
 	} while (track);
 
-	if (opcode != DIMUSE_P_SND_TRACK_NUM)
+	if (opcode != IMUSE_P_SND_TRACK_NUM)
 		return -4;
 
 	return l;
 }
 
-int IMuseDigital::tracksSetHook(int soundId, int hookId) {
+int IMuse::tracksSetHook(int soundId, int hookId) {
 	if (hookId > 128)
 		return -5;
 	if (!_trackList)
 		return -4;
 
-	IMuseDigiTrack *track = _trackList;
+	IMuseTrack *track = _trackList;
 	while (track->soundId != soundId) {
 		track = track->next;
 		if (!track)
@@ -516,11 +516,11 @@ int IMuseDigital::tracksSetHook(int soundId, int hookId) {
 	return 0;
 }
 
-int IMuseDigital::tracksGetHook(int soundId) {
+int IMuse::tracksGetHook(int soundId) {
 	if (!_trackList)
 		return -4;
 
-	IMuseDigiTrack *track = _trackList;
+	IMuseTrack *track = _trackList;
 	while (track->soundId != soundId) {
 		track = track->next;
 		if (!track)
@@ -530,9 +530,9 @@ int IMuseDigital::tracksGetHook(int soundId) {
 	return track->jumpHook;
 }
 
-IMuseDigiTrack *IMuseDigital::tracksReserveTrack(int priority) {
-	IMuseDigiTrack *curTrack;
-	IMuseDigiTrack *reservedTrack = nullptr;
+IMuseTrack *IMuse::tracksReserveTrack(int priority) {
+	IMuseTrack *curTrack;
+	IMuseTrack *reservedTrack = nullptr;
 	int minPriorityFound;
 
 	// Pick the track from the pool of free tracks
@@ -559,7 +559,7 @@ IMuseDigiTrack *IMuseDigital::tracksReserveTrack(int priority) {
 	return nullptr;
 }
 
-int IMuseDigital::tracksDeinit() {
+int IMuse::tracksDeinit() {
 	tracksStopAllSounds();
 	waveOutDeinit();
 	dispatchTerminate();
diff --git a/engines/grim/imuse/dimuse_triggers.cpp b/engines/grim/imuse/imuse_triggers.cpp
similarity index 69%
rename from engines/grim/imuse/dimuse_triggers.cpp
rename to engines/grim/imuse/imuse_triggers.cpp
index b27f9c248f6..f3e19afeef7 100644
--- a/engines/grim/imuse/dimuse_triggers.cpp
+++ b/engines/grim/imuse/imuse_triggers.cpp
@@ -19,27 +19,27 @@
  *
  */
 
-#include "engines/grim/imuse/dimuse_engine.h"
-#include "engines/grim/imuse/dimuse_triggers.h"
+#include "engines/grim/imuse/imuse_engine.h"
+#include "engines/grim/imuse/imuse_triggers.h"
 
 namespace Grim {
 
-IMuseDigiTriggersHandler::IMuseDigiTriggersHandler(IMuseDigital *engine, Common::Mutex *mutex) {
+IMuseTriggersHandler::IMuseTriggersHandler(IMuse *engine, Common::Mutex *mutex) {
 	_engine = engine;
 	_mutex = mutex;
 	_emptyMarker[0] = '\0';
 }
 
-IMuseDigiTriggersHandler::~IMuseDigiTriggersHandler() {}
+IMuseTriggersHandler::~IMuseTriggersHandler() {}
 
-int IMuseDigiTriggersHandler::init() {
+int IMuseTriggersHandler::init() {
 	return clearAllTriggers();
 }
 
-int IMuseDigiTriggersHandler::clearAllTriggers() {
+int IMuseTriggersHandler::clearAllTriggers() {
 	Common::StackLock lock(*_mutex);
 
-	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+	for (int l = 0; l < IMUSE_MAX_TRIGGERS; l++) {
 		_trigs[l].sound = 0;
 		memset(_trigs[l].text, 0, sizeof(_trigs[l].text));
 		_trigs[l].opcode = 0;
@@ -56,7 +56,7 @@ int IMuseDigiTriggersHandler::clearAllTriggers() {
 		_trigs[l].clearLater = 0;
 	}
 
-	for (int l = 0; l < DIMUSE_MAX_DEFERS; l++) {
+	for (int l = 0; l < IMUSE_MAX_DEFERS; l++) {
 		_defers[l].counter = 0;
 		_defers[l].opcode = 0;
 		_defers[l].a = 0;
@@ -76,8 +76,8 @@ int IMuseDigiTriggersHandler::clearAllTriggers() {
 	return 0;
 }
 
-void IMuseDigiTriggersHandler::saveLoad(Common::Serializer &ser) {
-	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+void IMuseTriggersHandler::saveLoad(Common::Serializer &ser) {
+	for (int l = 0; l < IMUSE_MAX_TRIGGERS; l++) {
 		ser.syncAsSint32LE(_trigs[l].sound, VER(30));
 		ser.syncArray(_trigs[l].text, 256, Common::Serializer::SByte, VER(30));
 		ser.syncAsSint32LE(_trigs[l].opcode, VER(30));
@@ -94,7 +94,7 @@ void IMuseDigiTriggersHandler::saveLoad(Common::Serializer &ser) {
 		ser.syncAsSint32LE(_trigs[l].clearLater, VER(30));
 	}
 
-	for (int l = 0; l < DIMUSE_MAX_DEFERS; l++) {
+	for (int l = 0; l < IMUSE_MAX_DEFERS; l++) {
 		ser.syncAsSint32LE(_defers[l].counter, VER(30));
 		ser.syncAsSint32LE(_defers[l].opcode, VER(30));
 		ser.syncAsSint32LE(_defers[l].a, VER(30));
@@ -113,7 +113,7 @@ void IMuseDigiTriggersHandler::saveLoad(Common::Serializer &ser) {
 		_defersOn = 1;
 }
 
-int IMuseDigiTriggersHandler::setTrigger(int soundId, char *marker, int opcode, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
+int IMuseTriggersHandler::setTrigger(int soundId, char *marker, int opcode, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
 	Common::StackLock lock(*_mutex);
 
 	if (soundId == 0) {
@@ -125,11 +125,11 @@ int IMuseDigiTriggersHandler::setTrigger(int soundId, char *marker, int opcode,
 	}
 
 	if (strlen(marker) >= 256) {
-		debug(5, "IMuseDigiTriggersHandler::setTrigger(): ERROR: attempting to set trigger with oversized marker string");
+		debug(5, "IMuseTriggersHandler::setTrigger(): ERROR: attempting to set trigger with oversized marker string");
 		return -5;
 	}
 
-	for (int index = 0; index < DIMUSE_MAX_TRIGGERS; index++) {
+	for (int index = 0; index < IMUSE_MAX_TRIGGERS; index++) {
 		if (_trigs[index].sound == 0) {
 			_trigs[index].sound = soundId;
 			_trigs[index].clearLater = 0;
@@ -146,20 +146,20 @@ int IMuseDigiTriggersHandler::setTrigger(int soundId, char *marker, int opcode,
 			_trigs[index].i = l;
 			_trigs[index].j = m;
 
-			debug(5, "IMuseDigiTriggersHandler::setTrigger(): Successfully set trigger for soundId %d and marker '%s'", soundId, marker);
+			debug(5, "IMuseTriggersHandler::setTrigger(): Successfully set trigger for soundId %d and marker '%s'", soundId, marker);
 			return 0;
 		}
 	}
 
-	debug(5, "IMuseDigiTriggersHandler::setTrigger(): ERROR: unable to allocate trigger \"%s\" for sound %d, every slot is full", marker, soundId);
+	debug(5, "IMuseTriggersHandler::setTrigger(): ERROR: unable to allocate trigger \"%s\" for sound %d, every slot is full", marker, soundId);
 	return -6;
 }
 
-int IMuseDigiTriggersHandler::checkTrigger(int soundId, char *marker, int opcode) {
+int IMuseTriggersHandler::checkTrigger(int soundId, char *marker, int opcode) {
 	Common::StackLock lock(*_mutex);
 
 	int r = 0;
-	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+	for (int l = 0; l < IMUSE_MAX_TRIGGERS; l++) {
 		if (_trigs[l].sound != 0) {
 			if (soundId == -1 || _trigs[l].sound == soundId) {
 				if (!strcmp(marker, _emptyMarker) || !strcmp(marker, _trigs[l].text)) {
@@ -173,10 +173,10 @@ int IMuseDigiTriggersHandler::checkTrigger(int soundId, char *marker, int opcode
 	return r;
 }
 
-int IMuseDigiTriggersHandler::clearTrigger(int soundId, char *marker, int opcode) {
+int IMuseTriggersHandler::clearTrigger(int soundId, char *marker, int opcode) {
 	Common::StackLock lock(*_mutex);
 
-	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+	for (int l = 0; l < IMUSE_MAX_TRIGGERS; l++) {
 		if ((_trigs[l].sound != 0) && (soundId == -1 || _trigs[l].sound == soundId) &&
             (!strcmp(marker, _emptyMarker) || !strcmp(marker, _trigs[l].text)) &&
             (opcode == -1 || _trigs[l].opcode == opcode)) {
@@ -191,18 +191,18 @@ int IMuseDigiTriggersHandler::clearTrigger(int soundId, char *marker, int opcode
 	return 0;
 }
 
-void IMuseDigiTriggersHandler::processTriggers(int soundId, char *marker) {
+void IMuseTriggersHandler::processTriggers(int soundId, char *marker) {
 	char textBuffer[256];
 	int r;
 
 	if (strlen(marker) >= 256) {
-		debug(5, "IMuseDigiTriggersHandler::processTriggers(): ERROR: the input marker string is oversized");
+		debug(5, "IMuseTriggersHandler::processTriggers(): ERROR: the input marker string is oversized");
 		return;
 	}
 
 	Common::strlcpy(_textBuffer, marker, sizeof(textBuffer));
 	_midProcessing++;
-	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+	for (int l = 0; l < IMUSE_MAX_TRIGGERS; l++) {
 		if (!_trigs[l].sound || _trigs[l].sound != soundId || (_trigs[l].text[0] && strcmp(_textBuffer, _trigs[l].text))) {
 			continue;
 		}
@@ -219,15 +219,15 @@ void IMuseDigiTriggersHandler::processTriggers(int soundId, char *marker) {
 
 		_trigs[l].sound = 0;
 
-		debug(5, "IMuseDigiTriggersHandler::processTriggers(): executing trigger for soundId %d and marker '%s'", soundId, marker);
-		if (_trigs[l].opcode == DIMUSE_C_SCRIPT_CALLBACK) {
+		debug(5, "IMuseTriggersHandler::processTriggers(): executing trigger for soundId %d and marker '%s'", soundId, marker);
+		if (_trigs[l].opcode == IMUSE_C_SCRIPT_CALLBACK) {
 			// Call the script callback (a function which sets _stoppingSequence to 1)
 			_engine->scriptTriggerCallback(_textBuffer);
 		} else {
 			if (_trigs[l].opcode < 30) {
 				// Execute a command (the same argument on all slots is intentional)
 				int lastArg = _trigs[l].j;
-				_engine->cmdsHandleCmd(_trigs[l].opcode, (uint8 *)textBuffer,
+				_engine->imSoundCall(_trigs[l].opcode, (uint8 *)textBuffer,
 					lastArg, lastArg, lastArg, lastArg, lastArg,
 					lastArg, lastArg, lastArg, lastArg, lastArg);
 			}
@@ -244,7 +244,7 @@ void IMuseDigiTriggersHandler::processTriggers(int soundId, char *marker) {
 		_textBuffer[r] = '\0';
 	}
 	if (--_midProcessing == 0) {
-		for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+		for (int l = 0; l < IMUSE_MAX_TRIGGERS; l++) {
 			if (_trigs[l].clearLater) {
 				_trigs[l].sound = 0;
 			}
@@ -252,14 +252,14 @@ void IMuseDigiTriggersHandler::processTriggers(int soundId, char *marker) {
 	}
 }
 
-int IMuseDigiTriggersHandler::deferCommand(int count, int opcode, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
+int IMuseTriggersHandler::deferCommand(int count, int opcode, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m, int n) {
 	Common::StackLock lock(*_mutex);
 
 	if (!count) {
 		return -5;
 	}
 
-	for (int index = 0; index < DIMUSE_MAX_DEFERS; index++) {
+	for (int index = 0; index < IMUSE_MAX_DEFERS; index++) {
 		if (!_defers[index].counter) {
 			_defers[index].counter = count;
 			_defers[index].opcode = opcode;
@@ -277,16 +277,16 @@ int IMuseDigiTriggersHandler::deferCommand(int count, int opcode, int c, int d,
 			return 0;
 		}
 	}
-	debug(5, "IMuseDigiTriggersHandler::deferCommand(): ERROR: couldn't allocate deferred command");
+	debug(5, "IMuseTriggersHandler::deferCommand(): ERROR: couldn't allocate deferred command");
 	return -6;
 }
 
-void IMuseDigiTriggersHandler::loop() {
+void IMuseTriggersHandler::loop() {
 	if (!_defersOn)
 		return;
 
 	_defersOn = 0;
-	for (int l = 0; l < DIMUSE_MAX_DEFERS; l++) {
+	for (int l = 0; l < IMUSE_MAX_DEFERS; l++) {
 		if (_defers[l].counter == 0)
 			continue;
 
@@ -294,12 +294,12 @@ void IMuseDigiTriggersHandler::loop() {
 		_defers[l].counter--;
 
 		if (_defers[l].counter == 0) {
-			if (_defers[l].opcode == DIMUSE_C_SCRIPT_CALLBACK) {
+			if (_defers[l].opcode == IMUSE_C_SCRIPT_CALLBACK) {
 				_engine->scriptTriggerCallback(_emptyMarker);
 			} else {
 				if (_defers[l].opcode < 30) {
 					int lastArg = _defers[l].j;
-					_engine->cmdsHandleCmd(_defers[l].opcode, nullptr,
+					_engine->imSoundCall(_defers[l].opcode, nullptr,
 						lastArg, lastArg, lastArg, lastArg, lastArg,
 						lastArg, lastArg, lastArg, lastArg, lastArg);
 				}
@@ -308,28 +308,28 @@ void IMuseDigiTriggersHandler::loop() {
 	}
 }
 
-int IMuseDigiTriggersHandler::countPendingSounds(int soundId) {
+int IMuseTriggersHandler::countPendingSounds(int soundId) {
 	Common::StackLock lock(*_mutex);
 
 	int r = 0;
-	for (int l = 0; l < DIMUSE_MAX_TRIGGERS; l++) {
+	for (int l = 0; l < IMUSE_MAX_TRIGGERS; l++) {
 		if (!_trigs[l].sound)
 			continue;
 
 		int opcode = _trigs[l].opcode;
-		if ((opcode == DIMUSE_C_START_SND && _trigs[l].a == soundId) ||
-			(opcode == DIMUSE_C_SWITCH_STREAM && _trigs[l].b == soundId)) {
+		if ((opcode == IMUSE_C_START_SND && _trigs[l].a == soundId) ||
+			(opcode == IMUSE_C_SWITCH_STREAM && _trigs[l].b == soundId)) {
 			r++;
 		}
 	}
 
-	for (int l = 0; l < DIMUSE_MAX_DEFERS; l++) {
+	for (int l = 0; l < IMUSE_MAX_DEFERS; l++) {
 		if (!_defers[l].counter)
 			continue;
 
 		int opcode = _defers[l].opcode;
-		if ((opcode == DIMUSE_C_START_SND && _defers[l].a == soundId) ||
-			(opcode == DIMUSE_C_SWITCH_STREAM && _defers[l].b == soundId)) {
+		if ((opcode == IMUSE_C_START_SND && _defers[l].a == soundId) ||
+			(opcode == IMUSE_C_SWITCH_STREAM && _defers[l].b == soundId)) {
 			r++;
 		}
 	}
diff --git a/engines/grim/imuse/dimuse_triggers.h b/engines/grim/imuse/imuse_triggers.h
similarity index 85%
rename from engines/grim/imuse/dimuse_triggers.h
rename to engines/grim/imuse/imuse_triggers.h
index abea39fa17e..c935065e8f6 100644
--- a/engines/grim/imuse/dimuse_triggers.h
+++ b/engines/grim/imuse/imuse_triggers.h
@@ -25,17 +25,17 @@
 #include "common/scummsys.h"
 #include "common/textconsole.h"
 #include "common/util.h"
-#include "engines/grim/imuse/dimuse_defs.h"
+#include "engines/grim/imuse/imuse_defs.h"
 
 namespace Grim {
 
-class IMuseDigiTriggersHandler {
+class IMuseTriggersHandler {
 
 private:
-	IMuseDigital *_engine;
+	IMuse *_engine;
 	Common::Mutex *_mutex;
-	IMuseDigiTrigger _trigs[DIMUSE_MAX_TRIGGERS] = {};
-	IMuseDigiDefer _defers[DIMUSE_MAX_DEFERS] = {};
+	IMuseTrigger _trigs[IMUSE_MAX_TRIGGERS] = {};
+	IMuseDefer _defers[IMUSE_MAX_DEFERS] = {};
 
 	int  _defersOn = 0;
 	int  _midProcessing = 0;
@@ -43,8 +43,8 @@ private:
 	char _emptyMarker[1] = {};
 
 public:
-	IMuseDigiTriggersHandler(IMuseDigital *engine, Common::Mutex *mutex);
-	~IMuseDigiTriggersHandler();
+	IMuseTriggersHandler(IMuse *engine, Common::Mutex *mutex);
+	~IMuseTriggersHandler();
 
 	int  init();
 	int  clearAllTriggers();
diff --git a/engines/grim/imuse/dimuse_utils.cpp b/engines/grim/imuse/imuse_utils.cpp
similarity index 73%
rename from engines/grim/imuse/dimuse_utils.cpp
rename to engines/grim/imuse/imuse_utils.cpp
index 4e09b356e55..567609cd10f 100644
--- a/engines/grim/imuse/dimuse_utils.cpp
+++ b/engines/grim/imuse/imuse_utils.cpp
@@ -19,16 +19,16 @@
  *
  */
 
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 
 namespace Grim {
 
-int IMuseDigital::addTrackToList(IMuseDigiTrack **listPtr, IMuseDigiTrack *listPtr_Item) {
+int IMuse::addTrackToList(IMuseTrack **listPtr, IMuseTrack *listPtr_Item) {
 	Common::StackLock lock(*_mutex);
 
 	// [0] is ->prev, [1] is ->next
 	if (!listPtr_Item || listPtr_Item->prev || listPtr_Item->next) {
-		debug(5, "IMuseDigital::addTrackToList(): ERROR: arguments might be null");
+		debug(5, "IMuse::addTrackToList(): ERROR: arguments might be null");
 		return -5;
 	} else {
 		// Set item's next element to the list
@@ -50,11 +50,11 @@ int IMuseDigital::addTrackToList(IMuseDigiTrack **listPtr, IMuseDigiTrack *listP
 	return 0;
 }
 
-int IMuseDigital::removeTrackFromList(IMuseDigiTrack **listPtr, IMuseDigiTrack *listPtr_Item) {
+int IMuse::removeTrackFromList(IMuseTrack **listPtr, IMuseTrack *listPtr_Item) {
 	Common::StackLock lock(*_mutex);
 
-	IMuseDigiTrack *currentTrack = *listPtr;
-	IMuseDigiTrack *nextTrack;
+	IMuseTrack *currentTrack = *listPtr;
+	IMuseTrack *nextTrack;
 	if (listPtr_Item && currentTrack) {
 		do {
 			if (currentTrack == listPtr_Item)
@@ -78,18 +78,18 @@ int IMuseDigital::removeTrackFromList(IMuseDigiTrack **listPtr, IMuseDigiTrack *
 			listPtr_Item->next = nullptr;
 			return 0;
 		} else {
-			debug(5, "IMuseDigital::removeTrackFromList(): ERROR: item not on list");
+			debug(5, "IMuse::removeTrackFromList(): ERROR: item not on list");
 			return -3;
 		}
 	} else {
-		debug(5, "IMuseDigital::removeTrackFromList(): ERROR: arguments might be null");
+		debug(5, "IMuse::removeTrackFromList(): ERROR: arguments might be null");
 		return -5;
 	}
 }
 
-int IMuseDigital::addStreamZoneToList(IMuseDigiStreamZone **listPtr, IMuseDigiStreamZone *listPtr_Item) {
+int IMuse::addStreamZoneToList(IMuseStreamZone **listPtr, IMuseStreamZone *listPtr_Item) {
 	if (!listPtr_Item || listPtr_Item->prev || listPtr_Item->next) {
-		debug(5, "IMuseDigital::addStreamZoneToList(): ERROR: arguments might be null");
+		debug(5, "IMuse::addStreamZoneToList(): ERROR: arguments might be null");
 		return -5;
 	} else {
 		// Set item's next element to the list
@@ -111,9 +111,9 @@ int IMuseDigital::addStreamZoneToList(IMuseDigiStreamZone **listPtr, IMuseDigiSt
 	return 0;
 }
 
-int IMuseDigital::removeStreamZoneFromList(IMuseDigiStreamZone **listPtr, IMuseDigiStreamZone *listPtr_Item) {
-	IMuseDigiStreamZone *currentStrZone = *listPtr;
-	IMuseDigiStreamZone *nextStrZone;
+int IMuse::removeStreamZoneFromList(IMuseStreamZone **listPtr, IMuseStreamZone *listPtr_Item) {
+	IMuseStreamZone *currentStrZone = *listPtr;
+	IMuseStreamZone *nextStrZone;
 	if (listPtr_Item && currentStrZone) {
 		do {
 			if (currentStrZone == listPtr_Item)
@@ -137,16 +137,16 @@ int IMuseDigital::removeStreamZoneFromList(IMuseDigiStreamZone **listPtr, IMuseD
 			listPtr_Item->next = nullptr;
 			return 0;
 		} else {
-			debug(5, "IMuseDigital::removeStreamZoneFromList(): ERROR: item not on list");
+			debug(5, "IMuse::removeStreamZoneFromList(): ERROR: item not on list");
 			return -3;
 		}
 	} else {
-		debug(5, "IMuseDigital::removeStreamZoneFromList(): ERROR: arguments might be null");
+		debug(5, "IMuse::removeStreamZoneFromList(): ERROR: arguments might be null");
 		return -5;
 	}
 }
 
-int IMuseDigital::clampNumber(int value, int minValue, int maxValue) {
+int IMuse::clampNumber(int value, int minValue, int maxValue) {
 	if (value < minValue)
 		return minValue;
 
@@ -156,7 +156,7 @@ int IMuseDigital::clampNumber(int value, int minValue, int maxValue) {
 	return value;
 }
 
-int IMuseDigital::checkHookId(int &trackHookId, int sampleHookId) {
+int IMuse::checkHookId(int &trackHookId, int sampleHookId) {
 	if (sampleHookId) {
 		if (trackHookId == sampleHookId) {
 			trackHookId = 0;
diff --git a/engines/grim/imuse/dimuse_waveout.cpp b/engines/grim/imuse/imuse_waveout.cpp
similarity index 93%
rename from engines/grim/imuse/dimuse_waveout.cpp
rename to engines/grim/imuse/imuse_waveout.cpp
index 751a972088c..be56ec03a0e 100644
--- a/engines/grim/imuse/dimuse_waveout.cpp
+++ b/engines/grim/imuse/imuse_waveout.cpp
@@ -19,11 +19,11 @@
  *
  */
 
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 
 namespace Grim {
 
-int IMuseDigital::waveOutInit(waveOutParamsStruct *waveOutSettingsStruct) {
+int IMuse::waveOutInit(waveOutParamsStruct *waveOutSettingsStruct) {
 	_waveOutBytesPerSample = 2;
 	_waveOutNumChannels = _mixer->getOutputStereo() ? 2 : 1;
 	_waveOutZeroLevel = 0;
@@ -66,7 +66,7 @@ int IMuseDigital::waveOutInit(waveOutParamsStruct *waveOutSettingsStruct) {
 	return 0;
 }
 
-void IMuseDigital::waveOutWrite(uint8 **audioData, int &feedSize, int &sampleRate) {
+void IMuse::waveOutWrite(uint8 **audioData, int &feedSize, int &sampleRate) {
 	uint8 *curBufferBlock;
 	if (_waveOutDisableWrite)
 		return;
@@ -123,12 +123,12 @@ void IMuseDigital::waveOutWrite(uint8 **audioData, int &feedSize, int &sampleRat
 	}
 }
 
-int IMuseDigital::waveOutDeinit() {
+int IMuse::waveOutDeinit() {
 	_waveOutDisableWrite = 1;
 	return 0;
 }
 
-void IMuseDigital::waveOutCallback() {
+void IMuse::waveOutCallback() {
 	Common::StackLock lock(*_mutex);
 	if (_lowLatencyMode) {
 		tracksLowLatencyCallback();
@@ -137,7 +137,7 @@ void IMuseDigital::waveOutCallback() {
 	}
 }
 
-byte IMuseDigital::waveOutGetStreamFlags() {
+byte IMuse::waveOutGetStreamFlags() {
 	byte flags = Audio::FLAG_16BITS;
 
 	if (_mixer->getOutputStereo()) {
@@ -150,7 +150,7 @@ byte IMuseDigital::waveOutGetStreamFlags() {
 	return flags;
 }
 
-void IMuseDigital::waveOutLowLatencyWrite(uint8 **audioData, int &feedSize, int &sampleRate, int idx) {
+void IMuse::waveOutLowLatencyWrite(uint8 **audioData, int &feedSize, int &sampleRate, int idx) {
 	uint8 *curBufferBlock;
 	if (_waveOutDisableWrite)
 		return;
@@ -174,7 +174,7 @@ void IMuseDigital::waveOutLowLatencyWrite(uint8 **audioData, int &feedSize, int
 	}
 }
 
-void IMuseDigital::waveOutEmptyBuffer(int idx) {
+void IMuse::waveOutEmptyBuffer(int idx) {
 	// This is necessary in low latency mode to clean-up the buffers of stale/finished sounds
 	int bufferSize = _waveOutNumChannels * _waveOutBytesPerSample * _waveOutPreferredFeedSize;
 	memset(&_waveOutLowLatencyOutputBuffer[bufferSize * idx], _waveOutZeroLevel, bufferSize);
diff --git a/engines/grim/lua_v1_graphics.cpp b/engines/grim/lua_v1_graphics.cpp
index a7e9e2f7548..0c829a9d06c 100644
--- a/engines/grim/lua_v1_graphics.cpp
+++ b/engines/grim/lua_v1_graphics.cpp
@@ -28,7 +28,7 @@
 #include "engines/grim/gfx_base.h"
 #include "engines/grim/set.h"
 #include "engines/grim/actor.h"
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 #include "engines/grim/movie/movie.h"
 #include "engines/grim/lua/lua.h"
 
@@ -99,7 +99,7 @@ void Lua_V1::StartMovie() {
 	}
 
 	if (g_imuse)
-		g_imuse->floodMusicBuffer();
+		g_imuse->soundsFloodMusicBuffer();
 
 	int x = 0, y = 0;
 	if (!lua_isnil(lua_getparam(3)))
diff --git a/engines/grim/lua_v1_sound.cpp b/engines/grim/lua_v1_sound.cpp
index 20be48004ef..8b7d7f13778 100644
--- a/engines/grim/lua_v1_sound.cpp
+++ b/engines/grim/lua_v1_sound.cpp
@@ -28,7 +28,7 @@
 #include "engines/grim/savegame.h"
 #include "engines/grim/set.h"
 #include "engines/grim/sound.h"
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 #include "engines/grim/lua/lauxlib.h"
 
 namespace Grim {
@@ -64,7 +64,7 @@ void Lua_V1::ImStopSound() {
 }
 
 void Lua_V1::ImStopAllSounds() {
-	g_imuse->diMUSEStopAllSounds();
+	g_imuse->imStopAllSounds();
 }
 
 void Lua_V1::ImPause() {
@@ -86,33 +86,33 @@ void Lua_V1::ImSetMusicVol() {
 	lua_Object volObj = lua_getparam(1);
 	if (!lua_isnumber(volObj))
 		return;
-	g_imuse->diMUSESetMusicGroupVol((int)lua_getnumber(volObj));
+	g_imuse->setMusicGroupVol((int)lua_getnumber(volObj));
 }
 
 void Lua_V1::ImGetMusicVol() {
-	lua_pushnumber(g_imuse->diMUSEGetMusicGroupVol());
+	lua_pushnumber(g_imuse->getMusicGroupVol());
 }
 
 void Lua_V1::ImSetVoiceVol() {
 	lua_Object volObj = lua_getparam(1);
 	if (!lua_isnumber(volObj))
 		return;
-	g_imuse->diMUSESetVoiceGroupVol((int)lua_getnumber(volObj));
+	g_imuse->setVoiceGroupVol((int)lua_getnumber(volObj));
 }
 
 void Lua_V1::ImGetVoiceVol() {
-	lua_pushnumber(g_imuse->diMUSEGetVoiceGroupVol());
+	lua_pushnumber(g_imuse->getVoiceGroupVol());
 }
 
 void Lua_V1::ImSetSfxVol() {
 	lua_Object volObj = lua_getparam(1);
 	if (!lua_isnumber(volObj))
 		return;
-	g_imuse->diMUSESetSFXGroupVol((int)lua_getnumber(volObj));
+	g_imuse->setSFXGroupVol((int)lua_getnumber(volObj));
 }
 
 void Lua_V1::ImGetSfxVol() {
-	lua_pushnumber(g_imuse->diMUSEGetSFXGroupVol());
+	lua_pushnumber(g_imuse->getSFXGroupVol());
 }
 
 void Lua_V1::ImSetParam() {
@@ -182,7 +182,7 @@ void Lua_V1::ImSetSequence() {
 		return;
 
 	int state = (int)lua_getnumber(stateObj);
-	lua_pushnumber(g_imuse->diMUSESetSequence(state));
+	lua_pushnumber(g_imuse->imSetSequence(state));
 }
 
 void Lua_V1::SaveIMuse() {
diff --git a/engines/grim/module.mk b/engines/grim/module.mk
index 467c189b3fe..39e75c6eeaa 100644
--- a/engines/grim/module.mk
+++ b/engines/grim/module.mk
@@ -42,22 +42,22 @@ MODULE_OBJS := \
 	emi/lua_v2_actor.o \
 	emi/lua_v2_sound.o \
 	emi/emi_registry.o \
-	imuse/dimuse_cmds.o \
-	imuse/dimuse_dispatch.o \
-	imuse/dimuse_engine.o \
-	imuse/dimuse_fades.o \
-	imuse/dimuse_files.o \
-	imuse/dimuse_groups.o \
-	imuse/dimuse_hmi.o \
-	imuse/dimuse_internalmixer.o \
-	imuse/dimuse_scripts.o \
-	imuse/dimuse_streamer.o \
-	imuse/dimuse_tables.o \
-	imuse/dimuse_tracks.o \
-	imuse/dimuse_triggers.o \
-	imuse/dimuse_utils.o \
-	imuse/dimuse_waveout.o \
+	imuse/imuse_cmds.o \
+	imuse/imuse_dispatch.o \
+	imuse/imuse_engine.o \
+	imuse/imuse_fades.o \
+	imuse/imuse_files.o \
+	imuse/imuse_groups.o \
+	imuse/imuse_hmi.o \
+	imuse/imuse_internalmixer.o \
 	imuse/imuse_mcmp_mgr.o \
+	imuse/imuse_scripts.o \
+	imuse/imuse_streamer.o \
+	imuse/imuse_tables.o \
+	imuse/imuse_tracks.o \
+	imuse/imuse_triggers.o \
+	imuse/imuse_utils.o \
+	imuse/imuse_waveout.o \
 	lua/lapi.o \
 	lua/lauxlib.o \
 	lua/lbuffer.o \
diff --git a/engines/grim/set.cpp b/engines/grim/set.cpp
index aa214bcb2a6..a624dfa92bf 100644
--- a/engines/grim/set.cpp
+++ b/engines/grim/set.cpp
@@ -30,7 +30,7 @@
 #include "engines/grim/gfx_base.h"
 #include "engines/grim/sound.h"
 #include "engines/grim/emi/sound/emisound.h"
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 
 #include "math/frustum.h"
 
diff --git a/engines/grim/sound.cpp b/engines/grim/sound.cpp
index 40c9d6a4fe4..47f8f75cd0d 100644
--- a/engines/grim/sound.cpp
+++ b/engines/grim/sound.cpp
@@ -23,7 +23,7 @@
 #include "common/serializer.h"
 
 #include "engines/grim/grim.h"
-#include "engines/grim/imuse/dimuse_engine.h"
+#include "engines/grim/imuse/imuse_engine.h"
 #include "engines/grim/emi/sound/emisound.h"
 #include "engines/grim/sound.h"
 
@@ -34,10 +34,10 @@ SoundPlayer *g_sound = nullptr;
 bool SoundPlayer::startVoice(const char *soundName, int volume, int pan, bool background) {
 	if (g_grim->getGameType() == GType_GRIM) {
 		if (background) {
-			if (!g_imuse->soundsLoadProcessStartSound(soundName, 127, DIMUSE_GROUP_SPEECH))
+			if (!g_imuse->soundsLoadProcessStartSound(soundName, 127, IMUSE_GROUP_SPEECH))
 				return false;
 
-			g_imuse->soundsSetParam(soundName, DIMUSE_P_VOLUME, volume);
+			g_imuse->soundsSetParam(soundName, IMUSE_P_VOLUME, volume);
 			return true;
 		}
 
@@ -55,7 +55,7 @@ bool SoundPlayer::getSoundStatus(const char *soundName) {
 			return false;
 
 		if (_streamedVoice == soundName)
-			return g_imuse->diMUSEGetParam(kTalkSoundID, DIMUSE_P_SND_TRACK_NUM) > 0;
+			return g_imuse->imGetParam(kTalkSoundID, IMUSE_P_SND_TRACK_NUM) > 0;
 
 		return g_imuse->soundsIsSoundPlaying(soundName);
 	} else {
@@ -79,7 +79,7 @@ int32 SoundPlayer::getPosIn16msTicks(const char *soundName) {
 		if (_streamedVoice == soundName)
 			return g_imuse->soundGetVoiceTime() >> 4;
 
-		return g_imuse->soundsGetParam(soundName, DIMUSE_P_SND_POS_IN_MS) >> 4;
+		return g_imuse->soundsGetParam(soundName, IMUSE_P_SND_POS_IN_MS) >> 4;
 	} else {
 		return g_emiSound->getPosIn16msTicks(soundName);
 	}
@@ -87,7 +87,7 @@ int32 SoundPlayer::getPosIn16msTicks(const char *soundName) {
 
 void SoundPlayer::setVolume(const char *soundName, int volume) {
 	if (g_grim->getGameType() == GType_GRIM) {
-		g_imuse->soundsSetParam(soundName, DIMUSE_P_VOLUME, volume);
+		g_imuse->soundsSetParam(soundName, IMUSE_P_VOLUME, volume);
 	} else {
 		g_emiSound->setVolume(soundName, volume);
 	}
@@ -95,7 +95,7 @@ void SoundPlayer::setVolume(const char *soundName, int volume) {
 
 void SoundPlayer::setPan(const char *soundName, int pan) {
 	if (g_grim->getGameType() == GType_GRIM) {
-		g_imuse->soundsSetParam(soundName, DIMUSE_P_PAN, pan);
+		g_imuse->soundsSetParam(soundName, IMUSE_P_PAN, pan);
 	} else {
 		g_emiSound->setPan(soundName, pan);
 	}
@@ -103,7 +103,7 @@ void SoundPlayer::setPan(const char *soundName, int pan) {
 
 void SoundPlayer::setMusicState(int stateId) {
 	if (g_grim->getGameType() == GType_GRIM) {
-		g_imuse->diMUSESetState(stateId);
+		g_imuse->imSetState(stateId);
 	} else {
 		g_emiSound->setMusicState(stateId);
 	}


Commit: bcce93fce5e150aa975931d81b65c7a647ed08aa
    https://github.com/scummvm/scummvm/commit/bcce93fce5e150aa975931d81b65c7a647ed08aa
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Insert missing mutex lock

Changed paths:
    engines/grim/imuse/imuse_engine.cpp


diff --git a/engines/grim/imuse/imuse_engine.cpp b/engines/grim/imuse/imuse_engine.cpp
index 8d3f2c0fad4..47333ae833b 100644
--- a/engines/grim/imuse/imuse_engine.cpp
+++ b/engines/grim/imuse/imuse_engine.cpp
@@ -523,6 +523,7 @@ int IMuse::imStopAllSounds() {
 }
 
 int IMuse::imGetNextSound(int soundId) {
+	Common::StackLock lock(*_mutex);
 	return tracksGetNextSound(soundId);
 }
 


Commit: 49efc2380ac39cb924da5700a281f149fea026d8
    https://github.com/scummvm/scummvm/commit/49efc2380ac39cb924da5700a281f149fea026d8
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Remove unused SCUMM leftovers

Changed paths:
    engines/grim/imuse/imuse_engine.cpp
    engines/grim/imuse/imuse_engine.h
    engines/grim/imuse/imuse_tracks.cpp


diff --git a/engines/grim/imuse/imuse_engine.cpp b/engines/grim/imuse/imuse_engine.cpp
index 47333ae833b..cadae72c5d1 100644
--- a/engines/grim/imuse/imuse_engine.cpp
+++ b/engines/grim/imuse/imuse_engine.cpp
@@ -61,9 +61,6 @@ IMuse::IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool low
 	_curMixerMusicVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType);
 	_curMixerSpeechVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType);
 	_curMixerSFXVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType);
-	_currentSpeechVolume = 0;
-	_currentSpeechFrequency = 0;
-	_currentSpeechPan = 0;
 
 	_waveOutXorTrigger = 0;
 	_waveOutWriteIndex = 0;
@@ -78,9 +75,7 @@ IMuse::IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool low
 	_openedSoundsList = nullptr;
 	_scriptInitializedFlag = false;
 	_callbackInterruptFlag = false;
-	_spooledMusicEnabled = true;
 
-	_isEngineDisabled = false;
 	_checkForUnderrun = false;
 	_underrunCooldown = 0;
 
@@ -185,35 +180,11 @@ IMuse::~IMuse() {
 	_waveOutLowLatencyOutputBuffer = nullptr;
 }
 
-int IMuse::roundRobinSetBufferCount() {
-	int minStreams = MAX<int>(_nominalBufferCount - 5, 1);
-	int maxStreams = _nominalBufferCount + 5;
-	_maxQueuedStreams++;
-
-	if (_maxQueuedStreams > maxStreams) {
-		_maxQueuedStreams = minStreams;
-	}
-
-	return _maxQueuedStreams;
-}
-
 void IMuse::adaptBufferCount() {
 	_maxQueuedStreams++;
 	_nominalBufferCount = _maxQueuedStreams;
 }
 
-void IMuse::stopSound(int sound) {
-	imStopSound(sound);
-}
-
-void IMuse::stopAllSounds() {
-	imStopAllSounds();
-}
-
-int IMuse::isSoundRunning(int soundId) {
-	return imGetParam(soundId, IMUSE_P_SND_TRACK_NUM) > 0;
-}
-
 void IMuse::imHeartbeat() {
 	int soundId, musicTargetVolume, musicEffVol, musicVol, tempVol, tempEffVol;
 
@@ -299,51 +270,7 @@ void IMuse::imHeartbeat() {
 	_callbackInterruptFlag = false;
 }
 
-void IMuse::setPriority(int soundId, int priority) {
-	imSetParam(soundId, IMUSE_P_PRIORITY, priority);
-}
-
-void IMuse::setVolume(int soundId, int volume) {
-	imSetParam(soundId, IMUSE_P_VOLUME, volume);
-	if (soundId == kTalkSoundID)
-		_currentSpeechVolume = volume;
-}
-
-void IMuse::setPan(int soundId, int pan) {
-	imSetParam(soundId, IMUSE_P_PAN, pan);
-	if (soundId == kTalkSoundID)
-		_currentSpeechPan = pan;
-}
-
-void IMuse::setFrequency(int soundId, int frequency) {
-	imSetParam(soundId, IMUSE_P_TRANSPOSE, frequency);
-	if (soundId == kTalkSoundID)
-		_currentSpeechFrequency = frequency;
-}
-
-int IMuse::getCurSpeechVolume() const {
-	return _currentSpeechVolume;
-}
-
-int IMuse::getCurSpeechPan() const {
-	return _currentSpeechPan;
-}
-
-int IMuse::getCurSpeechFrequency() const {
-	return _currentSpeechFrequency;
-}
-
-// This is used in order to avoid crash everything
-// if a compressed audio resource file is found
-void IMuse::disableEngine() {
-	_isEngineDisabled = true;
-}
-
-bool IMuse::isEngineDisabled() {
-	return _isEngineDisabled;
-}
-
-int32 IMuse::getCurMusicPosInMs() {
+int32 IMuse::soundsGetMusicPosition() {
 	int soundId, curSoundId;
 
 	curSoundId = 0;
@@ -362,13 +289,6 @@ int32 IMuse::getCurMusicPosInMs() {
 	return imGetParam(soundId, IMUSE_P_SND_POS_IN_MS);
 }
 
-int32 IMuse::getSoundElapsedTimeInMs(int soundId) {
-	if (imGetParam(soundId, IMUSE_P_SND_HAS_STREAM)) {
-		return imGetParam(soundId, IMUSE_P_SND_POS_IN_MS);
-	}
-	return 0;
-}
-
 void IMuse::pause(bool p) {
 	if (p) {
 		debug(5, "IMuse::pause(): pausing...");
@@ -428,14 +348,6 @@ bool IMuse::queryMusicStream(int32 &bufSize, int32 &criticalSize, int32 &freeSpa
 	return false;
 }
 
-int IMuse::getSampleRate() {
-	return _internalSampleRate;
-}
-
-int IMuse::getFeedSize() {
-	return _internalFeedSize;
-}
-
 int IMuse::imTerminate() {
 	return tracksDeinit();
 }
@@ -685,111 +597,4 @@ int IMuse::imSetAttribute(int attrIndex, int attrVal) {
 	return scriptParse(IMUSE_C_SCRIPT_SET_ATTRIBUTE, attrIndex, attrVal);
 }
 
-void IMuse::enableSpooledMusic() {
-	_spooledMusicEnabled = true;
-}
-
-void IMuse::disableSpooledMusic() {
-	_spooledMusicEnabled = true;
-	imSetState(0);
-	imSetSequence(0);
-	_spooledMusicEnabled = false;
-}
-
-// Debugger utility functions
-
-// TODO
-#if 0
-void IMuse::listStates() {
-	_vm->getDebugger()->debugPrintf("+---------------------------------+\n");
-	_vm->getDebugger()->debugPrintf("| stateId |         name          |\n");
-	_vm->getDebugger()->debugPrintf("+---------+-----------------------+\n");
-	if (_vm->_game.id == GID_CMI) {
-		if (_vm->_game.features & GF_DEMO) {
-			for (int i = 0; _comiDemoStateMusicTable[i].soundId != -1; i++) {
-				_vm->getDebugger()->debugPrintf("|  %4d   | %20s  |\n", _comiDemoStateMusicTable[i].soundId, _comiDemoStateMusicTable[i].name);
-			}
-		} else {
-			for (int i = 0; _comiStateMusicTable[i].soundId != -1; i++) {
-				_vm->getDebugger()->debugPrintf("|  %4d   | %20s  |\n", _comiStateMusicTable[i].soundId, _comiStateMusicTable[i].name);
-			}
-		}
-	} else if (_vm->_game.id == GID_DIG) {
-		for (int i = 0; _digStateMusicTable[i].soundId != -1; i++) {
-			_vm->getDebugger()->debugPrintf("|  %4d   | %20s  |\n", _digStateMusicTable[i].soundId, _digStateMusicTable[i].name);
-		}
-	} else if (_vm->_game.id == GID_FT) {
-		for (int i = 0; _ftStateMusicTable[i].name[0]; i++) {
-			_vm->getDebugger()->debugPrintf("|  %4d   | %21s |\n", i, _ftStateMusicTable[i].name);
-		}
-	}
-	_vm->getDebugger()->debugPrintf("+---------+-----------------------+\n\n");
-}
-
-void IMuse::listSeqs() {
-	_vm->getDebugger()->debugPrintf("+--------------------------------+\n");
-	_vm->getDebugger()->debugPrintf("|  seqId  |         name         |\n");
-	_vm->getDebugger()->debugPrintf("+---------+----------------------+\n");
-	if (_vm->_game.id == GID_CMI) {
-		for (int i = 0; _comiSeqMusicTable[i].soundId != -1; i++) {
-			_vm->getDebugger()->debugPrintf("|  %4d   | %20s |\n", _comiSeqMusicTable[i].soundId, _comiSeqMusicTable[i].name);
-		}
-	} else if (_vm->_game.id == GID_DIG) {
-		for (int i = 0; _digSeqMusicTable[i].soundId != -1; i++) {
-			_vm->getDebugger()->debugPrintf("|  %4d   | %20s |\n", _digSeqMusicTable[i].soundId, _digSeqMusicTable[i].name);
-		}
-	} else if (_vm->_game.id == GID_FT) {
-		for (int i = 0; _ftSeqNames[i].name[0]; i++) {
-			_vm->getDebugger()->debugPrintf("|  %4d   | %20s |\n", i, _ftSeqNames[i].name);
-		}
-	}
-	_vm->getDebugger()->debugPrintf("+---------+----------------------+\n\n");
-}
-
-void IMuse::listCues() {
-	int curId = -1;
-	if (_curMusicSeq) {
-		_vm->getDebugger()->debugPrintf("Available cues for current sequence:\n");
-		_vm->getDebugger()->debugPrintf("+---------------------------------------+\n");
-		_vm->getDebugger()->debugPrintf("|   cueName   | transitionType | volume |\n");
-		_vm->getDebugger()->debugPrintf("+-------------+----------------+--------+\n");
-		for (int i = 0; i < 4; i++) {
-			curId = ((_curMusicSeq - 1) * 4) + i;
-			_vm->getDebugger()->debugPrintf("|  %9s  |        %d       |  %3d   |\n",
-				_ftSeqMusicTable[curId].audioName, (int)_ftSeqMusicTable[curId].transitionType, (int)_ftSeqMusicTable[curId].volume);
-		}
-		_vm->getDebugger()->debugPrintf("+-------------+----------------+--------+\n\n");
-	} else {
-		_vm->getDebugger()->debugPrintf("Current sequence is NULL, no cues available.\n\n");
-	}
-}
-
-void IMuse::listTracks() {
-	_vm->getDebugger()->debugPrintf("Virtual audio tracks currently playing:\n");
-	_vm->getDebugger()->debugPrintf("+-------------------------------------------------------------------------+\n");
-	_vm->getDebugger()->debugPrintf("| # | soundId | group | hasStream | vol/effVol/pan  | priority | jumpHook |\n");
-	_vm->getDebugger()->debugPrintf("+---+---------+-------+-----------+-----------------+----------+----------+\n");
-
-	for (int i = 0; i < _trackCount; i++) {
-		IMuseTrack curTrack = _tracks[i];
-		if (curTrack.soundId != 0) {
-			_vm->getDebugger()->debugPrintf("| %1d |  %5d  |   %d   |     %d     |   %3d/%3d/%3d   |   %3d    |   %3d    |\n",
-				i, curTrack.soundId, curTrack.group, imGetParam(curTrack.soundId, IMUSE_P_SND_HAS_STREAM),
-				curTrack.vol, curTrack.effVol, curTrack.pan, curTrack.priority, curTrack.jumpHook);
-		} else {
-			_vm->getDebugger()->debugPrintf("| %1d |   ---   |  ---  |    ---    |   ---/---/---   |   ---    |   ---    |\n", i);
-		}
-	}
-	_vm->getDebugger()->debugPrintf("+---+---------+-------+-----------+-----------------+----------+----------+\n\n");
-}
-
-void IMuse::listGroups() {
-	_vm->getDebugger()->debugPrintf("Volume groups:\n");
-	_vm->getDebugger()->debugPrintf("\tSFX:      %3d\n", _groupsHandler->getGroupVol(IMUSE_GROUP_SFX));
-	_vm->getDebugger()->debugPrintf("\tSPEECH:   %3d\n", _groupsHandler->getGroupVol(IMUSE_GROUP_SPEECH));
-	_vm->getDebugger()->debugPrintf("\tMUSIC:    %3d\n", _groupsHandler->getGroupVol(IMUSE_GROUP_MUSIC));
-	_vm->getDebugger()->debugPrintf("\tMUSICEFF: %3d\n\n", _groupsHandler->getGroupVol(IMUSE_GROUP_MUSICEFF));
-}
-#endif
-
 } // End of namespace Grim
diff --git a/engines/grim/imuse/imuse_engine.h b/engines/grim/imuse/imuse_engine.h
index ab44525ee86..089ee760acb 100644
--- a/engines/grim/imuse/imuse_engine.h
+++ b/engines/grim/imuse/imuse_engine.h
@@ -67,7 +67,6 @@ private:
 	int _callbackFps;
 	static void timer_handler(void *refConf);
 
-	bool _isEngineDisabled;
 	bool _checkForUnderrun;
 	int _underrunCooldown;
 	bool _lowLatencyMode;
@@ -86,7 +85,6 @@ private:
 	int _maxQueuedStreams; // maximum number of streams which can be queued before they are played
 	int _nominalBufferCount;
 
-	int _currentSpeechVolume, _currentSpeechFrequency, _currentSpeechPan;
 	int _curMixerMusicVolume, _curMixerSpeechVolume, _curMixerSFXVolume;
 
 	int32 _attributes[228];	// internal attributes for each music file to store and check later
@@ -96,7 +94,6 @@ private:
 
 	bool _scriptInitializedFlag;
 	char _emptyMarker[1];
-	bool _spooledMusicEnabled;
 
 	int _usecPerInt; // Microseconds between each callback (will be set to 50 Hz)
 	bool _callbackInterruptFlag;
@@ -344,27 +341,12 @@ public:
 
 	// Wrapper functions used by the main engine
 
-	void stopSound(int sound);
-	void stopAllSounds();
-	int isSoundRunning(int soundId);
-	void setPriority(int soundId, int priority);
-	void setVolume(int soundId, int volume);
-	void setPan(int soundId, int pan);
-	void setFrequency(int soundId, int frequency);
-	int  getCurSpeechVolume() const;
-	int  getCurSpeechPan() const;
-	int  getCurSpeechFrequency() const;
 	void pause(bool pause);
-	void disableEngine();
-	bool isEngineDisabled();
 	void soundsFloodMusicBuffer();
 	void soundsFillStreamsWhileMusicCritical(int fillTimesAfter);
 	bool queryMusicStream(int32 &bufSize, int32 &criticalSize, int32 &freeSpace, int &paused);
-	int getSampleRate();
-	int getFeedSize();
 
-	int32 getCurMusicPosInMs();
-	int32 getSoundElapsedTimeInMs(int soundId);
+	int32 soundsGetMusicPosition();
 
 	// Sounds API
 	int soundsLoadStartSound(const char *soundName, int priority, int group);
@@ -435,8 +417,6 @@ public:
 	int imSetSequence(int soundId);
 	int imSetCuePoint(int cueId);
 	int imSetAttribute(int attrIndex, int attrVal);
-	void enableSpooledMusic();
-	void disableSpooledMusic();
 
 	// Utils
 	int addTrackToList(IMuseTrack **listPtr, IMuseTrack *listPtr_Item);
@@ -445,7 +425,6 @@ public:
 	int removeStreamZoneFromList(IMuseStreamZone **listPtr, IMuseStreamZone *itemPtr);
 	int clampNumber(int value, int minValue, int maxValue);
 	int checkHookId(int &trackHookId, int sampleHookId);
-	int roundRobinSetBufferCount();
 	void adaptBufferCount();
 
 	// CMDs
@@ -456,13 +435,6 @@ public:
 
 	// Script
 	int scriptTriggerCallback(char *marker);
-
-	// Debugger utility functions
-	void listStates();
-	void listSeqs();
-	void listCues();
-	void listTracks();
-	void listGroups();
 };
 
 extern IMuse *g_imuse;
diff --git a/engines/grim/imuse/imuse_tracks.cpp b/engines/grim/imuse/imuse_tracks.cpp
index 66397f6725a..922b5f44172 100644
--- a/engines/grim/imuse/imuse_tracks.cpp
+++ b/engines/grim/imuse/imuse_tracks.cpp
@@ -368,12 +368,6 @@ void IMuse::tracksClear(IMuseTrack *trackPtr) {
 	_fadesHandler->clearFadeStatus(trackPtr->soundId, -1);
 	_triggersHandler->clearTrigger(trackPtr->soundId, _emptyMarker, -1);
 
-	// Unlock the sound, if it's loaded as a resource
-	// TODO
-	// if (trackPtr->soundId < 1000 && trackPtr->soundId) {
-	// 	_vm->_res->unlock(rtSound, trackPtr->soundId);
-	// }
-
 	if (_lowLatencyMode)
 		waveOutEmptyBuffer(trackPtr->index);
 


Commit: d9ba5b2d82dfb2717904bdb08f537605d2f8446c
    https://github.com/scummvm/scummvm/commit/d9ba5b2d82dfb2717904bdb08f537605d2f8446c
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Apply GMM mixer volumes to the sound groups

Changed paths:
    engines/grim/imuse/imuse_engine.cpp


diff --git a/engines/grim/imuse/imuse_engine.cpp b/engines/grim/imuse/imuse_engine.cpp
index cadae72c5d1..873f28e2d6d 100644
--- a/engines/grim/imuse/imuse_engine.cpp
+++ b/engines/grim/imuse/imuse_engine.cpp
@@ -195,25 +195,20 @@ void IMuse::imHeartbeat() {
 
 	waveOutCallback();
 
-	// TODO
-	// if (!_vm->isUsingOriginalGUI()) {
-	// 	// Update volumes
-	//
-	// 	if (_curMixerMusicVolume != _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType)) {
-	// 		_curMixerMusicVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType);
-	// 		setMusicGroupVol(CLIP(_mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType) / 2, 0, 127));
-	// 	}
-	//
-	// 	if (_curMixerSpeechVolume != _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType)) {
-	// 		_curMixerSpeechVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType);
-	// 		setVoiceGroupVol(CLIP(_mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType) / 2, 0, 127));
-	// 	}
-	//
-	// 	if (_curMixerSFXVolume != _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType)) {
-	// 		_curMixerSFXVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType);
-	// 		setSFXGroupVol(CLIP(_mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType) / 2, 0, 127));
-	// 	}
-	// }
+	if (_curMixerMusicVolume != _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType)) {
+		_curMixerMusicVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType);
+		setMusicGroupVol(CLIP(_curMixerMusicVolume / 2, 0, 127));
+	}
+
+	if (_curMixerSpeechVolume != _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType)) {
+		_curMixerSpeechVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType);
+		setVoiceGroupVol(CLIP(_curMixerSpeechVolume / 2, 0, 127));
+	}
+
+	if (_curMixerSFXVolume != _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType)) {
+		_curMixerSFXVolume = _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType);
+		setSFXGroupVol(CLIP(_curMixerSFXVolume / 2, 0, 127));
+	}
 
 	if (!_cmdsPauseCount) {
 		// Handle fades and triggers
@@ -521,32 +516,14 @@ int IMuse::imFeedStream(int soundId, uint8 *srcBuf, int32 sizeToFeed, int paused
 }
 
 int IMuse::getMusicGroupVol() {
-	// TODO
-	// if (_vm->isUsingOriginalGUI()) {
-	// 	return imSetGroupVol(IMUSE_GROUP_MUSIC, -1);
-	// }
-	//
-	// return _mixer->getVolumeForSoundType(Audio::Mixer::kMusicSoundType) / 2;
 	return imSetGroupVol(IMUSE_GROUP_MUSIC, -1);
 }
 
 int IMuse::getSFXGroupVol() {
-	// TODO
-	// if (_vm->isUsingOriginalGUI()) {
-	// 	return imSetGroupVol(IMUSE_GROUP_SFX, -1);
-	// }
-	//
-	// return _mixer->getVolumeForSoundType(Audio::Mixer::kSFXSoundType) / 2;
 	return imSetGroupVol(IMUSE_GROUP_SFX, -1);
 }
 
 int IMuse::getVoiceGroupVol() {
-	// TODO
-	// if (_vm->isUsingOriginalGUI()) {
-	// 	return imSetGroupVol(IMUSE_GROUP_SPEECH, -1);
-	// }
-	//
-	// return _mixer->getVolumeForSoundType(Audio::Mixer::kSpeechSoundType) / 2;
 	return imSetGroupVol(IMUSE_GROUP_SPEECH, -1);
 }
 


Commit: 7feed580ece3ed81f9b88d572aed5dd73120bb42
    https://github.com/scummvm/scummvm/commit/7feed580ece3ed81f9b88d572aed5dd73120bb42
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Add missing ImSetAttribute and ImSetCuePoint Lua opcodes

Changed paths:
    engines/grim/lua_v1.cpp
    engines/grim/lua_v1.h
    engines/grim/lua_v1_sound.cpp


diff --git a/engines/grim/lua_v1.cpp b/engines/grim/lua_v1.cpp
index 24af3a32a01..662bbb5263e 100644
--- a/engines/grim/lua_v1.cpp
+++ b/engines/grim/lua_v1.cpp
@@ -948,6 +948,8 @@ struct luaL_reg grimMainOpcodes[] = {
 	{ "ImSetMusicVol", LUA_OPCODE(Lua_V1, ImSetMusicVol) },
 	{ "ImSetState", LUA_OPCODE(Lua_V1, ImSetState) },
 	{ "ImSetSequence", LUA_OPCODE(Lua_V1, ImSetSequence) },
+	{ "ImSetAttribute", LUA_OPCODE(Lua_V1, ImSetAttribute) },
+	{ "ImSetCuePoint", LUA_OPCODE(Lua_V1, ImSetCuePoint) },
 	{ "ImPause", LUA_OPCODE(Lua_V1, ImPause) },
 	{ "ImResume", LUA_OPCODE(Lua_V1, ImResume) },
 	{ "ImSetVoiceEffect", LUA_OPCODE(Lua_V1, ImSetVoiceEffect) },
diff --git a/engines/grim/lua_v1.h b/engines/grim/lua_v1.h
index e4d89b88070..0f1cbeb55ef 100644
--- a/engines/grim/lua_v1.h
+++ b/engines/grim/lua_v1.h
@@ -175,6 +175,8 @@ protected:
 	DECLARE_LUA_OPCODE(ImFadeParam);
 	DECLARE_LUA_OPCODE(ImSetState);
 	DECLARE_LUA_OPCODE(ImSetSequence);
+	DECLARE_LUA_OPCODE(ImSetAttribute);
+	DECLARE_LUA_OPCODE(ImSetCuePoint);
 	DECLARE_LUA_OPCODE(SaveIMuse);
 	DECLARE_LUA_OPCODE(RestoreIMuse);
 	DECLARE_LUA_OPCODE(SetSoundPosition);
diff --git a/engines/grim/lua_v1_sound.cpp b/engines/grim/lua_v1_sound.cpp
index 8b7d7f13778..81c8b9a3368 100644
--- a/engines/grim/lua_v1_sound.cpp
+++ b/engines/grim/lua_v1_sound.cpp
@@ -185,6 +185,25 @@ void Lua_V1::ImSetSequence() {
 	lua_pushnumber(g_imuse->imSetSequence(state));
 }
 
+void Lua_V1::ImSetAttribute() {
+	lua_Object attrIndexObj = lua_getparam(1);
+	lua_Object attrValObj = lua_getparam(2);
+	if (!lua_isnumber(attrIndexObj) || !lua_isnumber(attrValObj))
+		return;
+
+	int attrIndex = (int)lua_getnumber(attrIndexObj);
+	int attrVal = (int)lua_getnumber(attrValObj);
+	lua_pushnumber(g_imuse->imSetAttribute(attrIndex, attrVal));
+}
+
+void Lua_V1::ImSetCuePoint() {
+	lua_Object cueObj = lua_getparam(1);
+	if (!lua_isnumber(cueObj))
+		return;
+
+	g_imuse->imSetCuePoint((int)lua_getnumber(cueObj));
+}
+
 void Lua_V1::SaveIMuse() {
 	SaveGame *savedIMuse = SaveGame::openForSaving("grim.tmp");
 	if (!savedIMuse)


Commit: c29231a73d7f610b318552a4d5f4e385245141f1
    https://github.com/scummvm/scummvm/commit/c29231a73d7f610b318552a4d5f4e385245141f1
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Clean-up a TODO comment

Changed paths:
    engines/grim/imuse/imuse_scripts.cpp


diff --git a/engines/grim/imuse/imuse_scripts.cpp b/engines/grim/imuse/imuse_scripts.cpp
index fda13a93133..2ab3bd7c9b6 100644
--- a/engines/grim/imuse/imuse_scripts.cpp
+++ b/engines/grim/imuse/imuse_scripts.cpp
@@ -316,7 +316,6 @@ void IMuse::scriptPlayMusic(const IMuseStateTable *tableEntry, int curSongEntryI
 	case 10:
 	case 11:
 	case 12:
-		// TODO
 		// The original remaps the name through a table which always appends ".IMC"
 		Common::strlcpy(fileName, tableEntry->name, sizeof(fileName));
 		Common::strlcat(fileName, ".IMC", sizeof(fileName));


Commit: a2ade3c20540c714977c45a5f1914d673b96cbdb
    https://github.com/scummvm/scummvm/commit/a2ade3c20540c714977c45a5f1914d673b96cbdb
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Sync the lipsync code with the disasm

Changed paths:
    engines/grim/actor.cpp
    engines/grim/actor.h
    engines/grim/imuse/imuse_files.cpp
    engines/grim/lipsync.cpp
    engines/grim/lipsync.h
    engines/grim/sound.cpp
    engines/grim/sound.h


diff --git a/engines/grim/actor.cpp b/engines/grim/actor.cpp
index f70bc9f44ef..75c577b0cac 100644
--- a/engines/grim/actor.cpp
+++ b/engines/grim/actor.cpp
@@ -29,7 +29,7 @@
 #include "engines/grim/lipsync.h"
 #include "engines/grim/movie/movie.h"
 #include "engines/grim/sound.h"
-#include "engines/grim/imuse/imuse_defs.h"
+#include "engines/grim/imuse/imuse_engine.h"
 #include "engines/grim/lua.h"
 #include "engines/grim/resource.h"
 #include "engines/grim/savegame.h"
@@ -93,7 +93,7 @@ Actor::Actor() :
 		_globalAlpha(1.f), _alphaMode(AlphaOff),
 		 _mustPlaceText(false),
 		_puckOrient(false), _talking(false),
-		_inOverworld(false), _drawnToClean(false), _backgroundTalk(false), _voiceIs3D(false),
+		_inOverworld(false), _drawnToClean(false), _backgroundTalk(false), _voiceIs3D(false), _talkSoundId(0),
 		_sortOrder(0), _useParentSortOrder(false),
 		_sectorSortOrder(0), _hasSectorSortOrder(false), _fakeUnbound(false), _lightMode(LightFastDyn),
 		_hasFollowedBoxes(false), _lookAtActor(0) {
@@ -147,6 +147,7 @@ void Actor::saveState(SaveGame *savedState) const {
 	savedState->writeBool(_talking);
 	savedState->writeBool(_backgroundTalk);
 	savedState->writeBool(_voiceIs3D);
+	savedState->writeLESint32(_talkSoundId);
 
 	savedState->writeLEUint32((uint32)_collisionMode);
 	savedState->writeFloat(_collisionScale);
@@ -305,8 +306,10 @@ bool Actor::restoreState(SaveGame *savedState) {
 	_talkSoundName      = savedState->readString();
 	_talking = savedState->readBool();
 	_backgroundTalk = savedState->readBool();
-	if (savedState->saveMinorVersion() >= 30)
+	if (savedState->saveMinorVersion() >= 30) {
 		_voiceIs3D = savedState->readBool();
+		_talkSoundId = savedState->readLESint32();
+	}
 
 	if (isTalking()) {
 		g_grim->addTalkingActor(this);
@@ -1190,13 +1193,16 @@ void Actor::sayLine(const char *msgId, bool background, float x, float y) {
 
 	Set *currSet = g_grim->getCurrSet();
 
+	bool started = false;
+	_talkSoundId = 0;
+
 	if (g_grim->getSpeechMode() != GrimEngine::TextOnly) {
 		// if there is no costume probably the character is drawn by a smush movie, so
 		// we don't want to go out of sync with it.
 		if (g_grim->getGameType() == GType_GRIM && getCurrentCostume()) {
 			_talkDelay = 500;
 		}
-		bool started = g_sound->startVoice(_talkSoundName.c_str(), 127, 64, background);
+		started = g_sound->startVoice(_talkSoundName.c_str(), 127, 64, background, &_talkSoundId);
 
 		// The voice can be positioned in the set, like the original does
 		if (started && _voiceIs3D && currSet && g_grim->getGameType() == GType_GRIM) {
@@ -1223,6 +1229,18 @@ void Actor::sayLine(const char *msgId, bool background, float x, float y) {
 		// In these cases, revert to using the mumble chore.
 		if (g_grim->getSpeechMode() != GrimEngine::TextOnly)
 			_lipSync = g_resourceloader->getLipSync(soundLip);
+
+		// Ask iMUSE if there's lipsync data...
+		if (g_grim->getGameType() == GType_GRIM && _lipSync) {
+			bool hasTalkChore = false;
+			for (int i = 1; i < 10; i++) {
+				if (_talkChore[i].isValid())
+					hasTalkChore = true;
+			}
+
+			if (!started || !g_imuse->iMUSEGetPhoneme(_talkSoundId, 0) || !hasTalkChore)
+				_lipSync = nullptr;
+		}
 		// If there's no lip sync file then load the mumble chore if it exists
 		// (the mumble chore doesn't exist with the cat races announcer)
 		if (!_lipSync)
@@ -1331,6 +1349,7 @@ void Actor::shutUp() {
 		g_sound->stopSound(_talkSoundName.c_str());
 		_talkSoundName = "";
 	}
+	_talkSoundId = 0;
 
 	if (_lipSync) {
 		if (_talkAnim != -1)
@@ -1654,16 +1673,32 @@ void Actor::update(uint frameTime) {
 
 	// Update lip syncing
 	if (_lipSync) {
-		int posSound;
+		int anim = -1;
+		bool hasAnim = false;
 
 		// While getPosIn16msTicks will return "-1" to indicate that the
 		// sound is no longer playing, it is more appropriate to check first
-		if (g_grim->getSpeechMode() != GrimEngine::TextOnly && g_sound->getSoundStatus(_talkSoundName.c_str()))
-			posSound = g_sound->getPosIn16msTicks(_talkSoundName.c_str());
-		else
-			posSound = -1;
-		if (posSound != -1) {
-			int anim = _lipSync->getAnim(posSound);
+		if (g_grim->getSpeechMode() != GrimEngine::TextOnly && g_sound->getSoundStatus(_talkSoundName.c_str())) {
+			if (g_grim->getGameType() == GType_GRIM) {
+				// The original gets the phoneme from iMUSE, and stops
+				// talking if there's no lip sync data for the voice
+				int phoneme = g_imuse->iMUSEGetPhoneme(_talkSoundId, 0);
+				if (phoneme) {
+					anim = LipSync::getAnimFromPhoneme(phoneme);
+					hasAnim = true;
+				} else {
+					shutUp();
+				}
+			} else {
+				int posSound = g_sound->getPosIn16msTicks(_talkSoundName.c_str());
+				if (posSound != -1) {
+					anim = _lipSync->getAnim(posSound);
+					hasAnim = true;
+				}
+			}
+		}
+
+		if (hasAnim) {
 			if (_talkAnim != anim) {
 				if (anim != -1) {
 					if (_talkChore[anim].isValid()) {
diff --git a/engines/grim/actor.h b/engines/grim/actor.h
index feed0db6136..d9562e63b9e 100644
--- a/engines/grim/actor.h
+++ b/engines/grim/actor.h
@@ -616,6 +616,7 @@ private:
 	bool _talking;
 	bool _backgroundTalk;
 	bool _voiceIs3D;
+	int _talkSoundId;
 	ObjectPtr<LipSync> _lipSync;
 	Common::List<Costume *> _costumeStack;
 
diff --git a/engines/grim/imuse/imuse_files.cpp b/engines/grim/imuse/imuse_files.cpp
index df9162a8d4c..ea451262ca8 100644
--- a/engines/grim/imuse/imuse_files.cpp
+++ b/engines/grim/imuse/imuse_files.cpp
@@ -1547,6 +1547,8 @@ int IMuse::loadLip(const char *lipsyncFilename, int soundId) {
 
 		int fileSize = lipsyncFile->size();
 		if (fileSize <= IMUSE_LIPSYNC_MAX_SIZE) {
+			// Clear the old data, or it would be read after the end of the new file
+			memset(_lipsyncBufs[slot], 0, sizeof(_lipsyncBufs[slot]));
 			lipsyncFile->read(_lipsyncBufs[slot], fileSize);
 
 			if (memcmp(_lipsyncBufs[slot], "LIP!", 4))
@@ -1584,6 +1586,12 @@ int IMuse::soundsGetPhoneme(int soundId, int offset) {
 	}
 
 	int numEntries = READ_LE_INT32(lipsyncBuffer + 4);
+
+	// The number of entries in the file is often bigger than the real one, don't read out of the buffer
+	int maxEntries = (sizeof(_lipsyncBufs[0]) - 12) / 4;
+	if (numEntries > maxEntries)
+		numEntries = maxEntries;
+
 	int offset16MsTicks = offset >> 4;
 	uint8 *entry = lipsyncBuffer + 8;
 
diff --git a/engines/grim/lipsync.cpp b/engines/grim/lipsync.cpp
index 12e0ef4dcc0..8238eeb045e 100644
--- a/engines/grim/lipsync.cpp
+++ b/engines/grim/lipsync.cpp
@@ -92,6 +92,20 @@ int LipSync::getAnim(int pos) {
 	return -1;
 }
 
+int LipSync::getAnimFromPhoneme(int phoneme) {
+	// The silence phoneme
+	if (phoneme == 0x5F)
+		return 0;
+
+	// The original table doesn't have the last two entries
+	for (int i = 0; i < _animTableSize - 2; i++) {
+		if (phoneme == _animTable[i].phoneme)
+			return _animTable[i].anim;
+	}
+
+	return 1;
+}
+
 // TODO: Figure out which one is 0x0000, use 0 for now.
 const LipSync::PhonemeAnim LipSync::_animTable[] = {
 	{0x005F, 0}, {0x0251, 1}, {0x0061, 1}, {0x00E6, 1}, {0x028C, 8},
diff --git a/engines/grim/lipsync.h b/engines/grim/lipsync.h
index 07844969388..a082d07b44d 100644
--- a/engines/grim/lipsync.h
+++ b/engines/grim/lipsync.h
@@ -38,6 +38,7 @@ public:
 	~LipSync();
 
 	int getAnim(int pos);
+	static int getAnimFromPhoneme(int phoneme);
 	bool isValid() { return _numEntries > 0; }
 	const Common::String &getFilename() const { return _fname; };
 
diff --git a/engines/grim/sound.cpp b/engines/grim/sound.cpp
index 47f8f75cd0d..4d4e9e0198a 100644
--- a/engines/grim/sound.cpp
+++ b/engines/grim/sound.cpp
@@ -31,18 +31,23 @@ namespace Grim {
 
 SoundPlayer *g_sound = nullptr;
 
-bool SoundPlayer::startVoice(const char *soundName, int volume, int pan, bool background) {
+bool SoundPlayer::startVoice(const char *soundName, int volume, int pan, bool background, int *soundId) {
 	if (g_grim->getGameType() == GType_GRIM) {
 		if (background) {
-			if (!g_imuse->soundsLoadProcessStartSound(soundName, 127, IMUSE_GROUP_SPEECH))
+			int luaSoundId = g_imuse->soundsLoadProcessStartSound(soundName, 127, IMUSE_GROUP_SPEECH);
+			if (!luaSoundId)
 				return false;
 
 			g_imuse->soundsSetParam(soundName, IMUSE_P_VOLUME, volume);
+			if (soundId)
+				*soundId = luaSoundId;
 			return true;
 		}
 
 		bool started = !g_imuse->soundStartVoiceStream(soundName, volume, pan);
 		_streamedVoice = started ? soundName : "";
+		if (started && soundId)
+			*soundId = kTalkSoundID;
 		return started;
 	} else {
 		return g_emiSound->startVoice(soundName, volume, pan);
diff --git a/engines/grim/sound.h b/engines/grim/sound.h
index 5b700c5e4cb..5cef1d2980b 100644
--- a/engines/grim/sound.h
+++ b/engines/grim/sound.h
@@ -32,7 +32,7 @@ class EMISound;
 
 class SoundPlayer {
 public:
-	bool startVoice(const char *soundName, int volume = 127, int pan = 64, bool background = false);
+	bool startVoice(const char *soundName, int volume = 127, int pan = 64, bool background = false, int *soundId = nullptr);
 	bool getSoundStatus(const char *soundName);
 	void stopSound(const char *soundName);
 	int32 getPosIn16msTicks(const char *soundName);


Commit: 691550b0cfa0391e132bc8efe07242a64f3b999a
    https://github.com/scummvm/scummvm/commit/691550b0cfa0391e132bc8efe07242a64f3b999a
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Add ImStartVoice, ImStopVoice, master volume and other missing Lua opcodes

Changed paths:
    engines/grim/imuse/imuse_defs.h
    engines/grim/imuse/imuse_engine.h
    engines/grim/imuse/imuse_files.cpp
    engines/grim/lua_v1.cpp
    engines/grim/lua_v1.h
    engines/grim/lua_v1_sound.cpp


diff --git a/engines/grim/imuse/imuse_defs.h b/engines/grim/imuse/imuse_defs.h
index 6a490d4c3a8..617145ed182 100644
--- a/engines/grim/imuse/imuse_defs.h
+++ b/engines/grim/imuse/imuse_defs.h
@@ -63,6 +63,7 @@ enum {
 };
 
 #define IMUSE_BUN_CHUNK_SIZE  0x2000
+#define IMUSE_GROUP_MASTER    0
 #define IMUSE_GROUP_SFX       1
 #define IMUSE_GROUP_SPEECH    2
 #define IMUSE_GROUP_MUSIC     3
diff --git a/engines/grim/imuse/imuse_engine.h b/engines/grim/imuse/imuse_engine.h
index 089ee760acb..3ff19701145 100644
--- a/engines/grim/imuse/imuse_engine.h
+++ b/engines/grim/imuse/imuse_engine.h
@@ -359,6 +359,8 @@ public:
 	bool soundsIsSoundPlaying(const char *soundName);
 	int iMUSESetHook(const char *soundName, int hookId);
 	int iMUSEGetHook(const char *soundName);
+	int iMUSEGetMemoryFootprint();
+	int iMUSEGetSoundCacheSize();
 	void iMUSESetVoiceEffect(const char *effectName);
 	void soundsSaveLoad(Common::Serializer &ser);
 	void soundsRestoreLegacy(int32 stateIndex, int32 seqIndex);
diff --git a/engines/grim/imuse/imuse_files.cpp b/engines/grim/imuse/imuse_files.cpp
index ea451262ca8..cef670a7f34 100644
--- a/engines/grim/imuse/imuse_files.cpp
+++ b/engines/grim/imuse/imuse_files.cpp
@@ -1362,6 +1362,16 @@ int IMuse::iMUSEGetHook(const char *soundName) {
 	return -1;
 }
 
+int IMuse::iMUSEGetMemoryFootprint() {
+	// The original variable is never set
+	return 0;
+}
+
+int IMuse::iMUSEGetSoundCacheSize() {
+	// The original variable is never set
+	return 0;
+}
+
 void IMuse::iMUSESetVoiceEffect(const char *effectName) {
 	Common::strlcpy(_curEffectName, effectName, sizeof(_curEffectName));
 
diff --git a/engines/grim/lua_v1.cpp b/engines/grim/lua_v1.cpp
index 662bbb5263e..b9ec13e4053 100644
--- a/engines/grim/lua_v1.cpp
+++ b/engines/grim/lua_v1.cpp
@@ -953,6 +953,15 @@ struct luaL_reg grimMainOpcodes[] = {
 	{ "ImPause", LUA_OPCODE(Lua_V1, ImPause) },
 	{ "ImResume", LUA_OPCODE(Lua_V1, ImResume) },
 	{ "ImSetVoiceEffect", LUA_OPCODE(Lua_V1, ImSetVoiceEffect) },
+	{ "ImStartVoice", LUA_OPCODE(Lua_V1, ImStartVoice) },
+	{ "ImStopVoice", LUA_OPCODE(Lua_V1, ImStopVoice) },
+	{ "ImGetMemoryFootprint", LUA_OPCODE(Lua_V1, ImGetMemoryFootprint) },
+	{ "ImGetSoundCacheSize", LUA_OPCODE(Lua_V1, ImGetSoundCacheSize) },
+	{ "ImSetMasterVol", LUA_OPCODE(Lua_V1, ImSetMasterVol) },
+	{ "ImGetMasterVol", LUA_OPCODE(Lua_V1, ImGetMasterVol) },
+	{ "play", LUA_OPCODE(Lua_V1, ImStartSound) },
+	{ "quiet", LUA_OPCODE(Lua_V1, ImStopAllSounds) },
+	{ "vfx", LUA_OPCODE(Lua_V1, ImSetVoiceEffect) },
 	{ "LoadBundle", LUA_OPCODE(Lua_V1, LoadBundle) },
 	{ "SetGamma", LUA_OPCODE(Lua_V1, SetGamma) },
 	{ "SetActorWalkDominate", LUA_OPCODE(Lua_V1, SetActorWalkDominate) },
diff --git a/engines/grim/lua_v1.h b/engines/grim/lua_v1.h
index 0f1cbeb55ef..10adb5ab771 100644
--- a/engines/grim/lua_v1.h
+++ b/engines/grim/lua_v1.h
@@ -164,6 +164,12 @@ protected:
 	DECLARE_LUA_OPCODE(ImPause);
 	DECLARE_LUA_OPCODE(ImResume);
 	DECLARE_LUA_OPCODE(ImSetVoiceEffect);
+	DECLARE_LUA_OPCODE(ImStartVoice);
+	DECLARE_LUA_OPCODE(ImStopVoice);
+	DECLARE_LUA_OPCODE(ImGetMemoryFootprint);
+	DECLARE_LUA_OPCODE(ImGetSoundCacheSize);
+	DECLARE_LUA_OPCODE(ImSetMasterVol);
+	DECLARE_LUA_OPCODE(ImGetMasterVol);
 	DECLARE_LUA_OPCODE(ImSetMusicVol);
 	DECLARE_LUA_OPCODE(ImGetMusicVol);
 	DECLARE_LUA_OPCODE(ImSetVoiceVol);
diff --git a/engines/grim/lua_v1_sound.cpp b/engines/grim/lua_v1_sound.cpp
index 81c8b9a3368..1e1b02960be 100644
--- a/engines/grim/lua_v1_sound.cpp
+++ b/engines/grim/lua_v1_sound.cpp
@@ -82,6 +82,44 @@ void Lua_V1::ImSetVoiceEffect() {
 	g_imuse->iMUSESetVoiceEffect(effectName);
 }
 
+void Lua_V1::ImStartVoice() {
+	lua_Object nameObj = lua_getparam(1);
+	lua_Object volObj = lua_getparam(2);
+	lua_Object panObj = lua_getparam(3);
+
+	// The original accepts nil too, but it would crash in iMUSE
+	if (!lua_isstring(nameObj))
+		return;
+
+	if (!lua_isnumber(volObj) || !lua_isnumber(panObj))
+		return;
+
+	g_imuse->soundStartVoiceStream(lua_getstring(nameObj), (int)lua_getnumber(volObj), (int)lua_getnumber(panObj));
+}
+
+void Lua_V1::ImStopVoice() {
+	g_imuse->soundStopVoiceStream();
+}
+
+void Lua_V1::ImGetMemoryFootprint() {
+	lua_pushnumber(g_imuse->iMUSEGetMemoryFootprint());
+}
+
+void Lua_V1::ImGetSoundCacheSize() {
+	lua_pushnumber(g_imuse->iMUSEGetSoundCacheSize());
+}
+
+void Lua_V1::ImSetMasterVol() {
+	lua_Object volObj = lua_getparam(1);
+	if (!lua_isnumber(volObj))
+		return;
+	g_imuse->imSetGroupVol(IMUSE_GROUP_MASTER, (int)lua_getnumber(volObj));
+}
+
+void Lua_V1::ImGetMasterVol() {
+	lua_pushnumber(g_imuse->imSetGroupVol(IMUSE_GROUP_MASTER, -1));
+}
+
 void Lua_V1::ImSetMusicVol() {
 	lua_Object volObj = lua_getparam(1);
 	if (!lua_isnumber(volObj))


Commit: 2424c530d66caf84d82c1aef1da2f6f4c3ac2d04
    https://github.com/scummvm/scummvm/commit/2424c530d66caf84d82c1aef1da2f6f4c3ac2d04
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Remove speech delay hack

This was not in the original, and it messes up timings with the new implementation

Changed paths:
    engines/grim/actor.cpp
    engines/grim/actor.h
    engines/grim/grim.cpp


diff --git a/engines/grim/actor.cpp b/engines/grim/actor.cpp
index 75c577b0cac..4ead2c187f8 100644
--- a/engines/grim/actor.cpp
+++ b/engines/grim/actor.cpp
@@ -88,7 +88,7 @@ Actor::Actor() :
 		_walkedLast(false), _walkedCur(false),
 		_collisionMode(CollisionOff), _collisionScale(1.f),
 		_lastTurnDir(0), _currTurnDir(0),
-		_sayLineText(0), _talkDelay(0),
+		_sayLineText(0),
 		_attachedActor(0), _attachedJoint(""),
 		_globalAlpha(1.f), _alphaMode(AlphaOff),
 		 _mustPlaceText(false),
@@ -1197,11 +1197,6 @@ void Actor::sayLine(const char *msgId, bool background, float x, float y) {
 	_talkSoundId = 0;
 
 	if (g_grim->getSpeechMode() != GrimEngine::TextOnly) {
-		// if there is no costume probably the character is drawn by a smush movie, so
-		// we don't want to go out of sync with it.
-		if (g_grim->getGameType() == GType_GRIM && getCurrentCostume()) {
-			_talkDelay = 500;
-		}
 		started = g_sound->startVoice(_talkSoundName.c_str(), 127, 64, background, &_talkSoundId);
 
 		// The voice can be positioned in the set, like the original does
@@ -1289,7 +1284,7 @@ void Actor::sayLine(const char *msgId, bool background, float x, float y) {
 		textObject->setDefaults(&g_grim->_sayLineDefaults);
 		textObject->setFGColor(_talkColor);
 		textObject->setIsSpeech();
-		if (m == GrimEngine::TextOnly || g_grim->getMode() == GrimEngine::SmushMode) {
+		if (m == GrimEngine::TextOnly || g_grim->getMode() == GrimEngine::SmushMode || (g_grim->getGameType() == GType_GRIM && !started)) {
 			textObject->setDuration(500 + msg.size() * 15 * (11 - g_grim->getTextSpeed()));
 		}
 		if (g_grim->getGameType() == GType_MONKEY4 && (x != -1 || y != -1)) {
@@ -1765,23 +1760,21 @@ void Actor::update(uint frameTime) {
 
 // Not all the talking actors are in the current set, and so on not all the talking actors
 // update() is called. For example, Don when he comes out of his office after reaping Meche.
-bool Actor::updateTalk(uint frameTime) {
+bool Actor::updateTalk() {
 	if (_talking) {
 		// If there's no sound file then we're obviously not talking
 		GrimEngine::SpeechMode m = g_grim->getSpeechMode();
 		TextObject *textObject = nullptr;
 		if (_sayLineText)
 			textObject = TextObject::getPool().getObject(_sayLineText);
-		if (m == GrimEngine::TextOnly && !textObject) {
+
+		bool hasVoice = m != GrimEngine::TextOnly && (g_grim->getGameType() != GType_GRIM || _talkSoundId);
+		if (!hasVoice && !textObject) {
+			shutUp();
+			return false;
+		} else if (hasVoice && (_talkSoundName.empty() || !g_sound->getSoundStatus(_talkSoundName.c_str()))) {
 			shutUp();
 			return false;
-		} else if (m != GrimEngine::TextOnly && (_talkSoundName.empty() || !g_sound->getSoundStatus(_talkSoundName.c_str()))) {
-			_talkDelay -= frameTime;
-			if (_talkDelay <= 0) {
-				_talkDelay = 0;
-				shutUp();
-				return false;
-			}
 		}
 		return true;
 	}
diff --git a/engines/grim/actor.h b/engines/grim/actor.h
index d9562e63b9e..7abd1f65202 100644
--- a/engines/grim/actor.h
+++ b/engines/grim/actor.h
@@ -501,7 +501,7 @@ public:
 	/**
 	 * Check if the actor is still talking. If it is returns true, otherwise false.
 	 */
-	bool updateTalk(uint frameTime);
+	bool updateTalk();
 	void draw();
 
 	bool isLookAtVectorZero() {
@@ -711,7 +711,6 @@ private:
 	bool _puckOrient;
 
 	static bool _isTalkingBackground;
-	int _talkDelay;
 	int _attachedActor;
 	int _lookAtActor;
 	Common::String _attachedJoint;
diff --git a/engines/grim/grim.cpp b/engines/grim/grim.cpp
index bd9ee00e2c6..847c4d5ff6a 100644
--- a/engines/grim/grim.cpp
+++ b/engines/grim/grim.cpp
@@ -837,7 +837,7 @@ void GrimEngine::luaUpdate() {
 		// the costumes are updated in update().
 		for (Common::List<Actor *>::iterator i = _talkingActors.begin(); i != _talkingActors.end(); ++i) {
 			Actor *a = *i;
-			if (!a->updateTalk(_frameTime)) {
+			if (!a->updateTalk()) {
 				i = _talkingActors.reverse_erase(i);
 			}
 		}


Commit: 567ae10dc290aea1ff8af267f4c83c56a0535c85
    https://github.com/scummvm/scummvm/commit/567ae10dc290aea1ff8af267f4c83c56a0535c85
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Clean-up

Changed paths:
    engines/grim/imuse/imuse_files.cpp
    engines/grim/imuse/imuse_tables.cpp


diff --git a/engines/grim/imuse/imuse_files.cpp b/engines/grim/imuse/imuse_files.cpp
index cef670a7f34..d7493617ac2 100644
--- a/engines/grim/imuse/imuse_files.cpp
+++ b/engines/grim/imuse/imuse_files.cpp
@@ -1237,8 +1237,7 @@ uint8 *IMuse::soundsGetExtFormatBuffer(uint8 *streamHeader, int *formatId, int *
 		return nullptr;
 	}
 
-	// TODO
-	// Headerless audio: CreateAudioChunk() guesses the format from the data
+	// The original guesses the format of headerless audio (CreateAudioChunk), but no caller accepts it
 	return nullptr;
 }
 
diff --git a/engines/grim/imuse/imuse_tables.cpp b/engines/grim/imuse/imuse_tables.cpp
index 8b5db93056e..cfbd6444edc 100644
--- a/engines/grim/imuse/imuse_tables.cpp
+++ b/engines/grim/imuse/imuse_tables.cpp
@@ -26,231 +26,231 @@
 namespace Grim {
 
 const IMuseStateTable _grimStateMusicTable[181] = {
-	{"",                        0, 1000, "STATE_NULL",           0,  0,   0, 127, 0}, /* 000 */
-	{"",                        0, 1999, "stateNoChange",        0,  0,   0, 127, 0}, /* 001 */
-	{"1001 - Manny's Office",   3, 1001, "stateMO",              0,  0,   0, 127, 0}, /* 002 */
-	{"1002 - Mr. Frustration",  3, 1002, "stateHA_INTLS",        3,  8,   0,  20, 50}, /* 003 */
-	{"1002 - Mr. Frustration",  3, 1003, "stateHA_REVLS",        3,  8,   0,  80, 12}, /* 004 */
+	{"",                        0, 1000, "STATE_NULL",           0,  0,   0, 127,  0 }, /* 000 */
+	{"",                        0, 1999, "stateNoChange",        0,  0,   0, 127,  0 }, /* 001 */
+	{"1001 - Manny's Office",   3, 1001, "stateMO",              0,  0,   0, 127,  0 }, /* 002 */
+	{"1002 - Mr. Frustration",  3, 1002, "stateHA_INTLS",        3,  8,   0,  20, 50 }, /* 003 */
+	{"1002 - Mr. Frustration",  3, 1003, "stateHA_REVLS",        3,  8,   0,  80, 12 }, /* 004 */
 	{"1002 - Mr. Frustration",  3, 1004, "stateHA_ELVOS",        3,  8,   0,  90, 110}, /* 005 */
 	{"1002 - Mr. Frustration",  3, 1005, "stateHA_MNYCU",        3,  8,   0,  60, 110}, /* 006 */
-	{"1002 - Mr. Frustration",  3, 1006, "stateHA_EVACU",        3,  8,   0,  80, 64}, /* 007 */
-	{"1002 - Mr. Frustration",  3, 1007, "stateHA_EVAWS",        3,  8,   0,  60, 60}, /* 008 */
-	{"1008 - Domino's Office",  3, 1008, "stateDO",              0,  0,   0, 127, 0}, /* 009 */
-	{"1009 - Copal's Office",   3, 1009, "stateCO",              0,  0,   0, 127, 0}, /* 010 */
-	{"1010 - Ledge",            3, 1010, "stateLE",              0,  0,   0, 127, 0}, /* 011 */
-	{"1011 - Roof",             3, 1011, "stateRF",              0,  0,   0, 127, 0}, /* 012 */
-	{"1020 - Tube Room",        3, 1020, "stateTU",              0,  0,   0, 127, 0}, /* 013 */
-	{"1021 - Brennis",          3, 1021, "stateTU_BRENNIS",      0,  0,   0, 127, 0}, /* 014 */
-	{"1022 - Lobby",            3, 1022, "stateLO",              0,  0,   0, 127, 0}, /* 015 */
-	{"1023 - Packing Room",     3, 1023, "statePK",              0,  0,   0, 127, 0}, /* 016 */
-	{"1030 - Garage",           3, 1030, "stateGA",              0,  0,   0, 127, 0}, /* 017 */
-	{"1031 - Glottis' Shop",    3, 1031, "stateGS",              0,  0,   0, 127, 0}, /* 018 */
-	{"1030 - Garage",           3, 1032, "stateGS_JAIL",         0,  0,   0, 127, 0}, /* 019 */
-	{"1040 - Festival Wet",     3, 1040, "stateAL",             21,  4, 500,  60, 0}, /* 020 */
-	{"1041 - Festival Dry",     3, 1041, "stateFE",             21,  4, 200, 127, 0}, /* 021 */
-	{"1041 - Festival Dry",     3, 1042, "stateST",             21,  4, 200,  60, 0}, /* 022 */
-	{"1041 - Festival Dry",     3, 1043, "stateOS",             21,  4, 200,  46, 0}, /* 023 */
-	{"1040 - Festival Wet",     3, 1044, "stateRP",             21,  4, 200,  85, 0}, /* 024 */
-	{"1050 - Headquarters",     3, 1050, "stateHQ",              0,  0,   0, 127, 0}, /* 025 */
-	{"1060 - Real World",       2, 1060, "stateLR",              0,  0, 300,  80, 0}, /* 026 */
-	{"1070 - Stump Room",       2, 1070, "stateSM",              0,  0,   0, 127, 0}, /* 027 */
-	{"1071 - Signpost Room",    2, 1071, "stateSG",              0,  3,   0, 127, 0}, /* 028 */
-	{"1072 - Navigation",       2, 1072, "stateNA",              0,  0,   0, 127, 0}, /* 029 */
-	{"1071 - Signpost Room",    2, 1073, "stateNA_SOLVED",       0,  3,   0, 127, 0}, /* 030 */
-	{"1074 - Bone Wagon",       2, 1074, "stateOO_BONE",         0,  0,   0, 127, 0}, /* 031 */
-	{"1075 - Spider's Eye",     2, 1075, "stateSP_ENTLA",        0,  0,   0, 127, 0}, /* 032 */
-	{"1076 - Spider Room",      2, 1076, "stateSP_WEBWS",        0,  0,   0, 127, 0}, /* 033 */
-	{"1077 - Tree Pump Amb",    2, 1077, "stateTR_PMPWS",        0,  0,   0, 127, 0}, /* 034 */
-	{"1078 - Tree Pump",        2, 1078, "stateTR_ESTHA",        0,  0,   0, 127, 0}, /* 035 */
-	{"1071 - Signpost Room",    2, 1079, "stateTR_SOLVED",       0,  3,   0, 127, 0}, /* 036 */
-	{"1080 - Beaver Room Lbby", 2, 1080, "stateLB",              0,  0,   0, 127, 0}, /* 037 */
-	{"1081 - Beaver Dam",       2, 1081, "stateBD",              0,  0,   0, 127, 0}, /* 038 */
-	{"1083 - Beaver Room",      2, 1082, "stateBD_SOLVED",       0,  0,   0, 127, 0}, /* 039 */
-	{"1083 - Beaver Room",      2, 1083, "stateBV",              0,  0,   0, 127, 0}, /* 040 */
-	{"1084 - Foggy Cactus",     2, 1084, "stateFC",              0,  0,   0,  80, 0}, /* 041 */
-	{"1085 - Rubamat Exterior", 2, 1085, "stateRE",              0,  0,   0, 105, 0}, /* 042 */
-	{"1087 - Blue Hector",      2, 1086, "stateRI",              0,  4,   0,  80, 30}, /* 043 */
-	{"1109 - Cafe Exterior",    2, 1100, "stateCB",              0,  0,   0, 127, 0}, /* 044 */
-	{"1101 - Cafe Office",      3, 1101, "stateCF",             45,  5, 400,  60, 0}, /* 045 */
-	{"1102 - Cafe Intercom",    3, 1102, "stateCF_INTRCM",      45,  0, 400, 127, 0}, /* 046 */
+	{"1002 - Mr. Frustration",  3, 1006, "stateHA_EVACU",        3,  8,   0,  80, 64 }, /* 007 */
+	{"1002 - Mr. Frustration",  3, 1007, "stateHA_EVAWS",        3,  8,   0,  60, 60 }, /* 008 */
+	{"1008 - Domino's Office",  3, 1008, "stateDO",              0,  0,   0, 127, 0  }, /* 009 */
+	{"1009 - Copal's Office",   3, 1009, "stateCO",              0,  0,   0, 127, 0  }, /* 010 */
+	{"1010 - Ledge",            3, 1010, "stateLE",              0,  0,   0, 127, 0  }, /* 011 */
+	{"1011 - Roof",             3, 1011, "stateRF",              0,  0,   0, 127, 0  }, /* 012 */
+	{"1020 - Tube Room",        3, 1020, "stateTU",              0,  0,   0, 127, 0  }, /* 013 */
+	{"1021 - Brennis",          3, 1021, "stateTU_BRENNIS",      0,  0,   0, 127, 0  }, /* 014 */
+	{"1022 - Lobby",            3, 1022, "stateLO",              0,  0,   0, 127, 0  }, /* 015 */
+	{"1023 - Packing Room",     3, 1023, "statePK",              0,  0,   0, 127, 0  }, /* 016 */
+	{"1030 - Garage",           3, 1030, "stateGA",              0,  0,   0, 127, 0  }, /* 017 */
+	{"1031 - Glottis' Shop",    3, 1031, "stateGS",              0,  0,   0, 127, 0  }, /* 018 */
+	{"1030 - Garage",           3, 1032, "stateGS_JAIL",         0,  0,   0, 127, 0  }, /* 019 */
+	{"1040 - Festival Wet",     3, 1040, "stateAL",             21,  4, 500,  60, 0  }, /* 020 */
+	{"1041 - Festival Dry",     3, 1041, "stateFE",             21,  4, 200, 127, 0  }, /* 021 */
+	{"1041 - Festival Dry",     3, 1042, "stateST",             21,  4, 200,  60, 0  }, /* 022 */
+	{"1041 - Festival Dry",     3, 1043, "stateOS",             21,  4, 200,  46, 0  }, /* 023 */
+	{"1040 - Festival Wet",     3, 1044, "stateRP",             21,  4, 200,  85, 0  }, /* 024 */
+	{"1050 - Headquarters",     3, 1050, "stateHQ",              0,  0,   0, 127, 0  }, /* 025 */
+	{"1060 - Real World",       2, 1060, "stateLR",              0,  0, 300,  80, 0  }, /* 026 */
+	{"1070 - Stump Room",       2, 1070, "stateSM",              0,  0,   0, 127, 0  }, /* 027 */
+	{"1071 - Signpost Room",    2, 1071, "stateSG",              0,  3,   0, 127, 0  }, /* 028 */
+	{"1072 - Navigation",       2, 1072, "stateNA",              0,  0,   0, 127, 0  }, /* 029 */
+	{"1071 - Signpost Room",    2, 1073, "stateNA_SOLVED",       0,  3,   0, 127, 0  }, /* 030 */
+	{"1074 - Bone Wagon",       2, 1074, "stateOO_BONE",         0,  0,   0, 127, 0  }, /* 031 */
+	{"1075 - Spider's Eye",     2, 1075, "stateSP_ENTLA",        0,  0,   0, 127, 0  }, /* 032 */
+	{"1076 - Spider Room",      2, 1076, "stateSP_WEBWS",        0,  0,   0, 127, 0  }, /* 033 */
+	{"1077 - Tree Pump Amb",    2, 1077, "stateTR_PMPWS",        0,  0,   0, 127, 0  }, /* 034 */
+	{"1078 - Tree Pump",        2, 1078, "stateTR_ESTHA",        0,  0,   0, 127, 0  }, /* 035 */
+	{"1071 - Signpost Room",    2, 1079, "stateTR_SOLVED",       0,  3,   0, 127, 0  }, /* 036 */
+	{"1080 - Beaver Room Lbby", 2, 1080, "stateLB",              0,  0,   0, 127, 0  }, /* 037 */
+	{"1081 - Beaver Dam",       2, 1081, "stateBD",              0,  0,   0, 127, 0  }, /* 038 */
+	{"1083 - Beaver Room",      2, 1082, "stateBD_SOLVED",       0,  0,   0, 127, 0  }, /* 039 */
+	{"1083 - Beaver Room",      2, 1083, "stateBV",              0,  0,   0, 127, 0  }, /* 040 */
+	{"1084 - Foggy Cactus",     2, 1084, "stateFC",              0,  0,   0,  80, 0  }, /* 041 */
+	{"1085 - Rubamat Exterior", 2, 1085, "stateRE",              0,  0,   0, 105, 0  }, /* 042 */
+	{"1087 - Blue Hector",      2, 1086, "stateRI",              0,  4,   0,  80, 30 }, /* 043 */
+	{"1109 - Cafe Exterior",    2, 1100, "stateCB",              0,  0,   0, 127, 0  }, /* 044 */
+	{"1101 - Cafe Office",      3, 1101, "stateCF",             45,  5, 400,  60, 0  }, /* 045 */
+	{"1102 - Cafe Intercom",    3, 1102, "stateCF_INTRCM",      45,  0, 400, 127, 0  }, /* 046 */
 	{"1103 - Coat Check",       3, 1103, "stateCC",             49,  4, 400,  60, 100}, /* 047 */
-	{"1104 - Lupe",             2, 1104, "stateCC_LUPE",         0,  0, 300, 127, 0}, /* 048 */
-	{"1106 - Glottis Noodle",   3, 1105, "stateCI",             49,  4, 400, 127, 75}, /* 049 */
-	{"1106 - Glottis Noodle",   3, 1106, "stateCI_NOODLE",      49,  4, 400, 127, 75}, /* 050 */
-	{"1106 - Glottis Noodle",   3, 1190, "stateCI_WIDHA",       49,  4, 400,  80, 45}, /* 051 */
+	{"1104 - Lupe",             2, 1104, "stateCC_LUPE",         0,  0, 300, 127, 0  }, /* 048 */
+	{"1106 - Glottis Noodle",   3, 1105, "stateCI",             49,  4, 400, 127, 75 }, /* 049 */
+	{"1106 - Glottis Noodle",   3, 1106, "stateCI_NOODLE",      49,  4, 400, 127, 75 }, /* 050 */
+	{"1106 - Glottis Noodle",   3, 1190, "stateCI_WIDHA",       49,  4, 400,  80, 45 }, /* 051 */
 	{"1106 - Glottis Noodle",   3, 1191, "stateCI_BARWS",       49,  4, 400, 127, 127}, /* 052 */
-	{"1101 - Cafe Office",      3, 1107, "stateCI_EMPTY",       45,  5, 400, 127, 0}, /* 053 */
-	{"1108 - Casino Interior",  3, 1108, "stateCN",             45,  6, 400, 127, 0}, /* 054 */
-	{"1109 - Cafe Exterior",    2, 1109, "stateCE",              0,  0, 400, 127, 0}, /* 055 */
-	{"1110 - Cafe Ledge",       2, 1110, "stateCL",              0,  0, 400, 105, 0}, /* 056 */
-	{"1108 - Casino Interior",  3, 1111, "stateCN_QUIET",        0,  0, 400,  60, 0}, /* 057 */
-	{"1112 - Rusty Sans Vox",   2, 1112, "stateCI_SONG",         0,  0, 400, 127, 68}, /* 058 */
-	{"1120 - Elevator Station", 2, 1120, "stateEV",              0,  0,   0, 127, 0}, /* 059 */
-	{"1122 - Blue Exterior",    3, 1121, "stateBW",              0,  0, 400, 127, 0}, /* 060 */
-	{"1122 - Blue Exterior",    3, 1122, "stateBE",              0,  0, 400, 127, 0}, /* 061 */
-	{"1123 - Blue Casket Ins",  2, 1123, "stateBI",              0,  4, 700, 127, 0}, /* 062 */
-	{"1124 - Blue Casket Amb",  2, 1124, "stateBI_POE",          0,  0,   0, 127, 0}, /* 063 */
-	{"1125 - Smooth Hector",    2, 1125, "stateBK",              0,  4,   0,  80, 75}, /* 064 */
-	{"1122 - Blue Exterior",    3, 1126, "stateHB",              0,  0, 400, 127, 0}, /* 065 */
-	{"1127 - Limbo Dock",       3, 1127, "stateLM",             66,  0,   0, 127, 0}, /* 066 */
-	{"1128 - Limbo Talk",       2, 1128, "stateLM_TALK",         0,  0, 400, 127, 0}, /* 067 */
-	{"1129 - Limbo Poem",       3, 1129, "stateLM_POEM",        66,  0,   0, 127, 0}, /* 068 */
-	{"1130 - Dry Dock",         2, 1130, "stateDD",              0,  0, 400, 127, 0}, /* 069 */
-	{"1131 - Dry Dock Strike",  2, 1131, "stateDD_STRIKE",       0,  0, 400, 127, 0}, /* 070 */
-	{"1132 - Lighthouse Ext",   2, 1132, "stateLX",              0,  0,   0, 127, 0}, /* 071 */
-	{"1133 - Lola's Last",      2, 1133, "stateLX_LOLA",         0,  0,   0, 127, 0}, /* 072 */
-	{"1140 - Police Station",   3, 1140, "statePC",              0,  0,   0, 127, 0}, /* 073 */
-	{"1141 - Police Interior",  2, 1141, "statePI",              0,  0,   0, 105, 0}, /* 074 */
-	{"1141 - Police Interior",  2, 1142, "statePI_MALLOY",       0,  0,   0, 105, 0}, /* 075 */
-	{"1143 - Morgue",           2, 1143, "stateMG",              0,  0,   0, 105, 0}, /* 076 */
-	{"1140 - Police Station",   3, 1144, "stateBP",              0,  0,   0, 105, 0}, /* 077 */
-	{"1145 - Bridge Blimp",     2, 1145, "stateBB",              0,  0,   0, 127, 0}, /* 078 */
-	{"1146 - LOL Security Ext", 2, 1146, "stateGT",              0,  0,   0,  80, 0}, /* 079 */
-	{"1147 - LOL Security Int", 2, 1147, "stateSL",              0,  0,   0, 127, 0}, /* 080 */
-	{"1148 - Carla's Life",     2, 1148, "stateSL_TALK",         0,  0,   0, 127, 0}, /* 081 */
-	{"1149 - Bomb",             2, 1149, "stateSL_BOMB",         0,  0, 400, 127, 0}, /* 082 */
-	{"1152 - Track Stairs",     3, 1150, "stateTB",             83,  0,   0, 105, 0}, /* 083 */
-	{"1152 - Track Stairs",     3, 1151, "stateTW",             83,  0,   0, 105, 0}, /* 084 */
-	{"1152 - Track Stairs",     3, 1152, "stateTS",             83,  0,   0, 105, 0}, /* 085 */
-	{"1153 - Track Base",       2, 1153, "stateTX",              0,  0, 400, 127, 0}, /* 086 */
-	{"1154 - Kitty Hall",       2, 1154, "stateKH",              0,  0,   0, 127, 0}, /* 087 */
-	{"1155 - Sanspoof",         2, 1155, "stateKH_SANS",         0,  0,   0, 127, 0}, /* 088 */
-	{"1156 - Kitty Stables",    2, 1156, "stateKS",              0,  0,   0, 127, 0}, /* 089 */
-	{"1160 - High Roller Hall", 2, 1160, "stateHH",              0,  0,   0, 127, 0}, /* 090 */
-	{"1161 - High Roller Lnge", 3, 1161, "stateHL",              0,  0, 400, 127, 0}, /* 091 */
-	{"1162 - Glottis Gambling", 2, 1162, "stateHL_GLOT",         0,  0,   0, 127, 0}, /* 092 */
-	{"1163 - Max's Office",     3, 1163, "stateMX",              0,  0, 400, 127, 0}, /* 093 */
-	{"1125 - Hector Steps Out", 3, 1164, "stateHK",             94,  4, 200, 127, 80}, /* 094 */
-	{"1125 - Hector Steps Out", 3, 1165, "stateHP",             94,  4, 200,  20, 64}, /* 095 */
-	{"1125 - Hector Steps Out", 3, 1166, "stateHE",             94,  4, 200, 127, 10}, /* 096 */
-	{"1167 - Dillopede Elev",   3, 1167, "stateDE",              0,  0,   0, 127, 0}, /* 097 */
-	{"1167 - Dillopede Elev",   3, 1168, "stateDH",              0,  0,   0, 127, 0}, /* 098 */
-	{"1167 - Dillopede Elev",   3, 1169, "stateWC",              0,  0,   0, 127, 0}, /* 099 */
-	{"1170 - Extendo Bridge",   3, 1170, "stateXB",              0,  0, 400, 105, 0}, /* 100 */
-	{"1170 - Extendo Bridge",   3, 1171, "stateSD",              0,  0, 400, 105, 0}, /* 101 */
-	{"1170 - Extendo Bridge",   3, 1172, "stateSE",              0,  0, 400, 105, 0}, /* 102 */
-	{"1173 - Scrimshaw Int",    2, 1173, "stateSI",              0,  0, 400, 127, 0}, /* 103 */
-	{"1174 - Scrim Sleep",      2, 1174, "stateSI_SLEEP",        0,  0, 400, 127, 0}, /* 104 */
-	{"1180 - Note to Manny",    2, 1180, "stateNT",              0,  0,   0,  72, 0}, /* 105 */
-	{"1155 - Sanspoof",         2, 1181, "statePF",              0,  0,   0, 127, 0}, /* 106 */
-	{"1201 - Lola Zapata",      2, 1201, "stateLZ",              0,  0,   0, 127, 0}, /* 107 */
-	{"1202 - Inside The Lola",  2, 1202, "stateIL",              0,  0,   0, 127, 0}, /* 108 */
-	{"1203 - Engine Room",      2, 1203, "stateEI",              0,  0,   0, 127, 0}, /* 109 */
-	{"1204 - Porthole",         2, 1204, "stateDP",              0,  0,   0, 127, 0}, /* 110 */
-	{"1204 - Porthole",         2, 1205, "stateOP",              0,  0,   0, 127, 0}, /* 111 */
-	{"1210 - Sunken Lola",      2, 1210, "stateSU",              0,  0,   0, 127, 0}, /* 112 */
-	{"1211 - Pearl Crater Sub", 2, 1211, "statePS",              0,  0,   0, 127, 0}, /* 113 */
-	{"1220 - Miner's Room",     3, 1220, "stateMN",              0,  0,   0, 127, 0}, /* 114 */
-	{"1220 - Miner's Room",     3, 1221, "stateMN_CHEPITO",      0,  0,   0, 127, 0}, /* 115 */
-	{"1222 - Exterior Airlock", 2, 1222, "stateEA",              0,  0,   0, 127, 0}, /* 116 */
-	{"1223 - Factory Hub",      2, 1223, "stateFH",              0,  4,   0, 127, 0}, /* 117 */
-	{"1224 - Foreman's Office", 2, 1224, "stateFO",              0,  0,   0, 127, 0}, /* 118 */
-	{"1230 - Vault Door",       2, 1230, "stateVD",              0,  0,   0, 127, 0}, /* 119 */
-	{"1231 - Outer Vault",      2, 1231, "stateVO",              0,  0,   0, 127, 0}, /* 120 */
-	{"1232 - Inner Vault",      2, 1232, "stateVI",              0,  0,   0, 127, 0}, /* 121 */
-	{"1233 - Ashtray Room",     2, 1233, "stateAR",              0,  0,   0, 127, 0}, /* 122 */
-	{"1234 - Ashtray Scary",    2, 1234, "stateAR_SCARY",        0,  0,   0, 127, 0}, /* 123 */
-	{"1235 - Ashtray Pensive",  2, 1235, "stateAR_PENSV",        0,  0,   0, 127, 0}, /* 124 */
-	{"1236 - Domino's Room",    2, 1236, "stateDR",              0,  0,   0, 127, 0}, /* 125 */
-	{"1240 - Conveyor Under",   3, 1240, "stateCY",              0,  4,   0, 127, 0}, /* 126 */
-	{"1240 - Conveyor Under",   3, 1241, "stateCW",              0,  0,   0, 127, 0}, /* 127 */
-	{"1241 - Crane Intro",      2, 1242, "stateCV",              0,  0,   0, 127, 0}, /* 128 */
-	{"1243 - Anchor Room",      3, 1243, "stateAC",              0,  0,   0, 127, 0}, /* 129 */
-	{"1244 - Glottis Hanging",  2, 1244, "stateGH",              0,  0,   0, 127, 0}, /* 130 */
-	{"1245 - End of the World", 2, 1245, "stateEW",              0,  0,   0, 127, 0}, /* 131 */
-	{"1246 - End World Later",  2, 1246, "stateEW_LATER",        0,  0,   0, 127, 0}, /* 132 */
-	{"1241 - Crane Intro",      2, 1247, "stateCU",              0,  0,   0, 127, 0}, /* 133 */
-	{"1250 - Upper Beach",      3, 1250, "stateBU",              0,  0,   0, 127, 0}, /* 134 */
-	{"1250 - Upper Beach",      3, 1251, "stateBL",              0,  0,   0, 127, 0}, /* 135 */
-	{"1252 - Lower Beach Boat", 3, 1252, "stateBL_BOAT",         0,  0,   0, 127, 0}, /* 136 */
-	{"1253 - Lamancha Sub",     2, 1253, "stateLU",              0,  0,   0, 127, 0}, /* 137 */
-	{"1254 - Crane Later",      2, 1254, "stateCUV_LATER",       0,  0,   0, 127, 0}, /* 138 */
-	{"1301 - Temple Gate",      3, 1301, "stateTG",              0,  0,   0, 127, 0}, /* 139 */
-	{"1301 - Temple Gate",      3, 1302, "stateBS",              0,  0,   0, 127, 0}, /* 140 */
-	{"1303 - Truck Depot",      2, 1303, "stateTD",              0,  0,   0, 105, 0}, /* 141 */
-	{"1306 - Mayan Train Pad",  3, 1306, "stateMT_CHEPITO",    143,  0,   0, 127, 0}, /* 142 */
-	{"1304 - Mayan Train Sta",  3, 1304, "stateMT",            143,  0,   0, 127, 0}, /* 143 */
-	{"1305 - Mayan Workshop",   2, 1305, "stateMY",              0,  0,   0, 127, 0}, /* 144 */
-	{"1307 - Mechanic's Kitch", 2, 1307, "stateMK",              0,  4,   0,  40, 64}, /* 145 */
-	{"1310 - Jello Bomb",       3, 1310, "stateJB",              0,  0,   0, 127, 0}, /* 146 */
-	{"1310 - Jello Bomb",       3, 1311, "stateXB_YEAR4",        0,  0,   0, 127, 0}, /* 147 */
-	{"1125 - Smooth Hector",    3, 1312, "stateBI_CLBYR4",     150,  4, 200,  20, 64}, /* 148 */
-	{"1125 - Smooth Hector",    3, 1313, "stateBI_KITYR4",     150,  4, 200,  50, 32}, /* 149 */
-	{"1125 - Smooth Hector",    3, 1314, "stateBK_YR4",        150,  4, 200, 105, 75}, /* 150 */
-	{"1122 - Blue Exterior",    3, 1315, "stateHB_YR4",          0,  0,   0, 127, 0}, /* 151 */
-	{"1122 - Blue Exterior",    3, 1316, "stateBW_YR4",          0,  0,   0, 127, 0}, /* 152 */
-	{"1122 - Blue Exterior",    3, 1317, "stateBE_YR4",          0,  0,   0, 127, 0}, /* 153 */
-	{"1332 - Hector's Foyer",   3, 1318, "stateHN",              0,  0,   0, 127, 0}, /* 154 */
-	{"1319 - Florist Video",    2, 1319, "stateFVID",            0,  0,   0, 127, 0}, /* 155 */
-	{"1320 - New LSA HQ",       2, 1320, "stateNQ",              0,  0,   0, 127, 0}, /* 156 */
-	{"1321 - LSA Sewer",        3, 1321, "stateLW",              0,  0,   0, 127, 0}, /* 157 */
-	{"1321 - LSA Sewer",        3, 1322, "stateSH",              0,  0,   0, 127, 0}, /* 158 */
-	{"1323 - Sewer Maze",       3, 1323, "stateZW",              0,  2,   0, 127, 0}, /* 159 */
-	{"1324 - Albinozod",        3, 1324, "stateAT",              0,  0,   0, 127, 0}, /* 160 */
-	{"1334 - Albino Trap",      3, 1334, "stateAT_TRAP",         0,  0,   0, 127, 0}, /* 161 */
-	{"1325 - Florist Shop",     3, 1325, "stateFP",            162,  0,   0, 127, 0}, /* 162 */
-	{"1326 - Florist Shop Int", 3, 1326, "stateFI",            162,  0,   0, 127, 0}, /* 163 */
-	{"1327 - Florist OK",       2, 1327, "stateFI_OK",           0,  0,   0, 127, 0}, /* 164 */
-	{"1323 - Sewer Maze",       3, 1328, "stateTE",              0,  2,   0, 127, 0}, /* 165 */
-	{"1329 - Theater Backstag", 2, 1329, "stateTH",              0,  4,   0, 127, 0}, /* 166 */
-	{"1330 - Lemans Lobby",     2, 1330, "stateLY",              0,  0,   0, 127, 0}, /* 167 */
-	{"1330 - Lemans Lobby",     2, 1331, "stateLY_CHOW",         0,  0,   0,  60, 0}, /* 168 */
-	{"1333 - Brennis Talk",     2, 1333, "stateLY_BREN",         0,  0,   0, 127, 0}, /* 169 */
-	{"1332 - Hector's Foyer",   3, 1332, "stateHF",              0,  0,   0, 127, 0}, /* 170 */
-	{"1342 - Neon Ledge",       2, 1340, "stateNL",              0,  0,   0, 127, 0}, /* 171 */
-	{"1350 - Meadow Flowers",   2, 1350, "stateMF",              0,  0,   0, 127, 0}, /* 172 */
-	{"1351 - Meadow",           2, 1351, "stateME",              0,  0,   0, 127, 0}, /* 173 */
-	{"1352 - Car Head",         2, 1352, "stateHI",              0,  0,   0, 127, 0}, /* 174 */
-	{"1353 - Greenhouse Appr",  2, 1353, "stateGE",              0,  0,   0, 127, 0}, /* 175 */
-	{"1355 - Shootout",         2, 1355, "stateSHOOT",           0,  0,   0, 127, 0}, /* 176 */
-	{"1354 - Game Ending",      2, 1354, "stateEND",             0,  0,   0, 127, 0}, /* 177 */
-	{"1400 - Start Credits",    2, 1400, "stateOPEN_CRED",       0,  0,   0, 127, 0}, /* 178 */
-	{"1401 - Smooth Hector",    2, 1401, "stateEND_CRED",        0,  0,  20, 105, 0}, /* 179 */
-	{"",                        0, 1500, "stateMenu",            0,  0,   0, 127, 0}, /* 180 */
+	{"1101 - Cafe Office",      3, 1107, "stateCI_EMPTY",       45,  5, 400, 127, 0  }, /* 053 */
+	{"1108 - Casino Interior",  3, 1108, "stateCN",             45,  6, 400, 127, 0  }, /* 054 */
+	{"1109 - Cafe Exterior",    2, 1109, "stateCE",              0,  0, 400, 127, 0  }, /* 055 */
+	{"1110 - Cafe Ledge",       2, 1110, "stateCL",              0,  0, 400, 105, 0  }, /* 056 */
+	{"1108 - Casino Interior",  3, 1111, "stateCN_QUIET",        0,  0, 400,  60, 0  }, /* 057 */
+	{"1112 - Rusty Sans Vox",   2, 1112, "stateCI_SONG",         0,  0, 400, 127, 68 }, /* 058 */
+	{"1120 - Elevator Station", 2, 1120, "stateEV",              0,  0,   0, 127, 0  }, /* 059 */
+	{"1122 - Blue Exterior",    3, 1121, "stateBW",              0,  0, 400, 127, 0  }, /* 060 */
+	{"1122 - Blue Exterior",    3, 1122, "stateBE",              0,  0, 400, 127, 0  }, /* 061 */
+	{"1123 - Blue Casket Ins",  2, 1123, "stateBI",              0,  4, 700, 127, 0  }, /* 062 */
+	{"1124 - Blue Casket Amb",  2, 1124, "stateBI_POE",          0,  0,   0, 127, 0  }, /* 063 */
+	{"1125 - Smooth Hector",    2, 1125, "stateBK",              0,  4,   0,  80, 75 }, /* 064 */
+	{"1122 - Blue Exterior",    3, 1126, "stateHB",              0,  0, 400, 127, 0  }, /* 065 */
+	{"1127 - Limbo Dock",       3, 1127, "stateLM",             66,  0,   0, 127, 0  }, /* 066 */
+	{"1128 - Limbo Talk",       2, 1128, "stateLM_TALK",         0,  0, 400, 127, 0  }, /* 067 */
+	{"1129 - Limbo Poem",       3, 1129, "stateLM_POEM",        66,  0,   0, 127, 0  }, /* 068 */
+	{"1130 - Dry Dock",         2, 1130, "stateDD",              0,  0, 400, 127, 0  }, /* 069 */
+	{"1131 - Dry Dock Strike",  2, 1131, "stateDD_STRIKE",       0,  0, 400, 127, 0  }, /* 070 */
+	{"1132 - Lighthouse Ext",   2, 1132, "stateLX",              0,  0,   0, 127, 0  }, /* 071 */
+	{"1133 - Lola's Last",      2, 1133, "stateLX_LOLA",         0,  0,   0, 127, 0  }, /* 072 */
+	{"1140 - Police Station",   3, 1140, "statePC",              0,  0,   0, 127, 0  }, /* 073 */
+	{"1141 - Police Interior",  2, 1141, "statePI",              0,  0,   0, 105, 0  }, /* 074 */
+	{"1141 - Police Interior",  2, 1142, "statePI_MALLOY",       0,  0,   0, 105, 0  }, /* 075 */
+	{"1143 - Morgue",           2, 1143, "stateMG",              0,  0,   0, 105, 0  }, /* 076 */
+	{"1140 - Police Station",   3, 1144, "stateBP",              0,  0,   0, 105, 0  }, /* 077 */
+	{"1145 - Bridge Blimp",     2, 1145, "stateBB",              0,  0,   0, 127, 0  }, /* 078 */
+	{"1146 - LOL Security Ext", 2, 1146, "stateGT",              0,  0,   0,  80, 0  }, /* 079 */
+	{"1147 - LOL Security Int", 2, 1147, "stateSL",              0,  0,   0, 127, 0  }, /* 080 */
+	{"1148 - Carla's Life",     2, 1148, "stateSL_TALK",         0,  0,   0, 127, 0  }, /* 081 */
+	{"1149 - Bomb",             2, 1149, "stateSL_BOMB",         0,  0, 400, 127, 0  }, /* 082 */
+	{"1152 - Track Stairs",     3, 1150, "stateTB",             83,  0,   0, 105, 0  }, /* 083 */
+	{"1152 - Track Stairs",     3, 1151, "stateTW",             83,  0,   0, 105, 0  }, /* 084 */
+	{"1152 - Track Stairs",     3, 1152, "stateTS",             83,  0,   0, 105, 0  }, /* 085 */
+	{"1153 - Track Base",       2, 1153, "stateTX",              0,  0, 400, 127, 0  }, /* 086 */
+	{"1154 - Kitty Hall",       2, 1154, "stateKH",              0,  0,   0, 127, 0  }, /* 087 */
+	{"1155 - Sanspoof",         2, 1155, "stateKH_SANS",         0,  0,   0, 127, 0  }, /* 088 */
+	{"1156 - Kitty Stables",    2, 1156, "stateKS",              0,  0,   0, 127, 0  }, /* 089 */
+	{"1160 - High Roller Hall", 2, 1160, "stateHH",              0,  0,   0, 127, 0  }, /* 090 */
+	{"1161 - High Roller Lnge", 3, 1161, "stateHL",              0,  0, 400, 127, 0  }, /* 091 */
+	{"1162 - Glottis Gambling", 2, 1162, "stateHL_GLOT",         0,  0,   0, 127, 0  }, /* 092 */
+	{"1163 - Max's Office",     3, 1163, "stateMX",              0,  0, 400, 127, 0  }, /* 093 */
+	{"1125 - Hector Steps Out", 3, 1164, "stateHK",             94,  4, 200, 127, 80 }, /* 094 */
+	{"1125 - Hector Steps Out", 3, 1165, "stateHP",             94,  4, 200,  20, 64 }, /* 095 */
+	{"1125 - Hector Steps Out", 3, 1166, "stateHE",             94,  4, 200, 127, 10 }, /* 096 */
+	{"1167 - Dillopede Elev",   3, 1167, "stateDE",              0,  0,   0, 127, 0  }, /* 097 */
+	{"1167 - Dillopede Elev",   3, 1168, "stateDH",              0,  0,   0, 127, 0  }, /* 098 */
+	{"1167 - Dillopede Elev",   3, 1169, "stateWC",              0,  0,   0, 127, 0  }, /* 099 */
+	{"1170 - Extendo Bridge",   3, 1170, "stateXB",              0,  0, 400, 105, 0  }, /* 100 */
+	{"1170 - Extendo Bridge",   3, 1171, "stateSD",              0,  0, 400, 105, 0  }, /* 101 */
+	{"1170 - Extendo Bridge",   3, 1172, "stateSE",              0,  0, 400, 105, 0  }, /* 102 */
+	{"1173 - Scrimshaw Int",    2, 1173, "stateSI",              0,  0, 400, 127, 0  }, /* 103 */
+	{"1174 - Scrim Sleep",      2, 1174, "stateSI_SLEEP",        0,  0, 400, 127, 0  }, /* 104 */
+	{"1180 - Note to Manny",    2, 1180, "stateNT",              0,  0,   0,  72, 0  }, /* 105 */
+	{"1155 - Sanspoof",         2, 1181, "statePF",              0,  0,   0, 127, 0  }, /* 106 */
+	{"1201 - Lola Zapata",      2, 1201, "stateLZ",              0,  0,   0, 127, 0  }, /* 107 */
+	{"1202 - Inside The Lola",  2, 1202, "stateIL",              0,  0,   0, 127, 0  }, /* 108 */
+	{"1203 - Engine Room",      2, 1203, "stateEI",              0,  0,   0, 127, 0  }, /* 109 */
+	{"1204 - Porthole",         2, 1204, "stateDP",              0,  0,   0, 127, 0  }, /* 110 */
+	{"1204 - Porthole",         2, 1205, "stateOP",              0,  0,   0, 127, 0  }, /* 111 */
+	{"1210 - Sunken Lola",      2, 1210, "stateSU",              0,  0,   0, 127, 0  }, /* 112 */
+	{"1211 - Pearl Crater Sub", 2, 1211, "statePS",              0,  0,   0, 127, 0  }, /* 113 */
+	{"1220 - Miner's Room",     3, 1220, "stateMN",              0,  0,   0, 127, 0  }, /* 114 */
+	{"1220 - Miner's Room",     3, 1221, "stateMN_CHEPITO",      0,  0,   0, 127, 0  }, /* 115 */
+	{"1222 - Exterior Airlock", 2, 1222, "stateEA",              0,  0,   0, 127, 0  }, /* 116 */
+	{"1223 - Factory Hub",      2, 1223, "stateFH",              0,  4,   0, 127, 0  }, /* 117 */
+	{"1224 - Foreman's Office", 2, 1224, "stateFO",              0,  0,   0, 127, 0  }, /* 118 */
+	{"1230 - Vault Door",       2, 1230, "stateVD",              0,  0,   0, 127, 0  }, /* 119 */
+	{"1231 - Outer Vault",      2, 1231, "stateVO",              0,  0,   0, 127, 0  }, /* 120 */
+	{"1232 - Inner Vault",      2, 1232, "stateVI",              0,  0,   0, 127, 0  }, /* 121 */
+	{"1233 - Ashtray Room",     2, 1233, "stateAR",              0,  0,   0, 127, 0  }, /* 122 */
+	{"1234 - Ashtray Scary",    2, 1234, "stateAR_SCARY",        0,  0,   0, 127, 0  }, /* 123 */
+	{"1235 - Ashtray Pensive",  2, 1235, "stateAR_PENSV",        0,  0,   0, 127, 0  }, /* 124 */
+	{"1236 - Domino's Room",    2, 1236, "stateDR",              0,  0,   0, 127, 0  }, /* 125 */
+	{"1240 - Conveyor Under",   3, 1240, "stateCY",              0,  4,   0, 127, 0  }, /* 126 */
+	{"1240 - Conveyor Under",   3, 1241, "stateCW",              0,  0,   0, 127, 0  }, /* 127 */
+	{"1241 - Crane Intro",      2, 1242, "stateCV",              0,  0,   0, 127, 0  }, /* 128 */
+	{"1243 - Anchor Room",      3, 1243, "stateAC",              0,  0,   0, 127, 0  }, /* 129 */
+	{"1244 - Glottis Hanging",  2, 1244, "stateGH",              0,  0,   0, 127, 0  }, /* 130 */
+	{"1245 - End of the World", 2, 1245, "stateEW",              0,  0,   0, 127, 0  }, /* 131 */
+	{"1246 - End World Later",  2, 1246, "stateEW_LATER",        0,  0,   0, 127, 0  }, /* 132 */
+	{"1241 - Crane Intro",      2, 1247, "stateCU",              0,  0,   0, 127, 0  }, /* 133 */
+	{"1250 - Upper Beach",      3, 1250, "stateBU",              0,  0,   0, 127, 0  }, /* 134 */
+	{"1250 - Upper Beach",      3, 1251, "stateBL",              0,  0,   0, 127, 0  }, /* 135 */
+	{"1252 - Lower Beach Boat", 3, 1252, "stateBL_BOAT",         0,  0,   0, 127, 0  }, /* 136 */
+	{"1253 - Lamancha Sub",     2, 1253, "stateLU",              0,  0,   0, 127, 0  }, /* 137 */
+	{"1254 - Crane Later",      2, 1254, "stateCUV_LATER",       0,  0,   0, 127, 0  }, /* 138 */
+	{"1301 - Temple Gate",      3, 1301, "stateTG",              0,  0,   0, 127, 0  }, /* 139 */
+	{"1301 - Temple Gate",      3, 1302, "stateBS",              0,  0,   0, 127, 0  }, /* 140 */
+	{"1303 - Truck Depot",      2, 1303, "stateTD",              0,  0,   0, 105, 0  }, /* 141 */
+	{"1306 - Mayan Train Pad",  3, 1306, "stateMT_CHEPITO",    143,  0,   0, 127, 0  }, /* 142 */
+	{"1304 - Mayan Train Sta",  3, 1304, "stateMT",            143,  0,   0, 127, 0  }, /* 143 */
+	{"1305 - Mayan Workshop",   2, 1305, "stateMY",              0,  0,   0, 127, 0  }, /* 144 */
+	{"1307 - Mechanic's Kitch", 2, 1307, "stateMK",              0,  4,   0,  40, 64 }, /* 145 */
+	{"1310 - Jello Bomb",       3, 1310, "stateJB",              0,  0,   0, 127, 0  }, /* 146 */
+	{"1310 - Jello Bomb",       3, 1311, "stateXB_YEAR4",        0,  0,   0, 127, 0  }, /* 147 */
+	{"1125 - Smooth Hector",    3, 1312, "stateBI_CLBYR4",     150,  4, 200,  20, 64 }, /* 148 */
+	{"1125 - Smooth Hector",    3, 1313, "stateBI_KITYR4",     150,  4, 200,  50, 32 }, /* 149 */
+	{"1125 - Smooth Hector",    3, 1314, "stateBK_YR4",        150,  4, 200, 105, 75 }, /* 150 */
+	{"1122 - Blue Exterior",    3, 1315, "stateHB_YR4",          0,  0,   0, 127, 0  }, /* 151 */
+	{"1122 - Blue Exterior",    3, 1316, "stateBW_YR4",          0,  0,   0, 127, 0  }, /* 152 */
+	{"1122 - Blue Exterior",    3, 1317, "stateBE_YR4",          0,  0,   0, 127, 0  }, /* 153 */
+	{"1332 - Hector's Foyer",   3, 1318, "stateHN",              0,  0,   0, 127, 0  }, /* 154 */
+	{"1319 - Florist Video",    2, 1319, "stateFVID",            0,  0,   0, 127, 0  }, /* 155 */
+	{"1320 - New LSA HQ",       2, 1320, "stateNQ",              0,  0,   0, 127, 0  }, /* 156 */
+	{"1321 - LSA Sewer",        3, 1321, "stateLW",              0,  0,   0, 127, 0  }, /* 157 */
+	{"1321 - LSA Sewer",        3, 1322, "stateSH",              0,  0,   0, 127, 0  }, /* 158 */
+	{"1323 - Sewer Maze",       3, 1323, "stateZW",              0,  2,   0, 127, 0  }, /* 159 */
+	{"1324 - Albinozod",        3, 1324, "stateAT",              0,  0,   0, 127, 0  }, /* 160 */
+	{"1334 - Albino Trap",      3, 1334, "stateAT_TRAP",         0,  0,   0, 127, 0  }, /* 161 */
+	{"1325 - Florist Shop",     3, 1325, "stateFP",            162,  0,   0, 127, 0  }, /* 162 */
+	{"1326 - Florist Shop Int", 3, 1326, "stateFI",            162,  0,   0, 127, 0  }, /* 163 */
+	{"1327 - Florist OK",       2, 1327, "stateFI_OK",           0,  0,   0, 127, 0  }, /* 164 */
+	{"1323 - Sewer Maze",       3, 1328, "stateTE",              0,  2,   0, 127, 0  }, /* 165 */
+	{"1329 - Theater Backstag", 2, 1329, "stateTH",              0,  4,   0, 127, 0  }, /* 166 */
+	{"1330 - Lemans Lobby",     2, 1330, "stateLY",              0,  0,   0, 127, 0  }, /* 167 */
+	{"1330 - Lemans Lobby",     2, 1331, "stateLY_CHOW",         0,  0,   0,  60, 0  }, /* 168 */
+	{"1333 - Brennis Talk",     2, 1333, "stateLY_BREN",         0,  0,   0, 127, 0  }, /* 169 */
+	{"1332 - Hector's Foyer",   3, 1332, "stateHF",              0,  0,   0, 127, 0  }, /* 170 */
+	{"1342 - Neon Ledge",       2, 1340, "stateNL",              0,  0,   0, 127, 0  }, /* 171 */
+	{"1350 - Meadow Flowers",   2, 1350, "stateMF",              0,  0,   0, 127, 0  }, /* 172 */
+	{"1351 - Meadow",           2, 1351, "stateME",              0,  0,   0, 127, 0  }, /* 173 */
+	{"1352 - Car Head",         2, 1352, "stateHI",              0,  0,   0, 127, 0  }, /* 174 */
+	{"1353 - Greenhouse Appr",  2, 1353, "stateGE",              0,  0,   0, 127, 0  }, /* 175 */
+	{"1355 - Shootout",         2, 1355, "stateSHOOT",           0,  0,   0, 127, 0  }, /* 176 */
+	{"1354 - Game Ending",      2, 1354, "stateEND",             0,  0,   0, 127, 0  }, /* 177 */
+	{"1400 - Start Credits",    2, 1400, "stateOPEN_CRED",       0,  0,   0, 127, 0  }, /* 178 */
+	{"1401 - Smooth Hector",    2, 1401, "stateEND_CRED",        0,  0,  20, 105, 0  }, /* 179 */
+	{"",                        0, 1500, "stateMenu",            0,  0,   0, 127, 0  }, /* 180 */
 };
 
 const IMuseStateTable _grimSeqMusicTable[41] = {
-	{"",                        0, 2000, "SEQ_NULL",             0,  0, 300, 127, 0}, /* 000 */
-	{"2001 - Climb Rope",       2, 2001, "seqClimbRope",         0,  0, 300, 127, 0}, /* 001 */
-	{"2010 - Glottis OK",       2, 2010, "seqGlottisOK",         0,  0, 300, 127, 0}, /* 002 */
-	{"2020 - Reap Bruno",       2, 2020, "seqReapBruno",         0,  0, 300, 127, 0}, /* 003 */
-	{"2030 - Ledgepeckers",     2, 2030, "seqLedgepeckers",      0,  0, 300, 127, 0}, /* 004 */
-	{"2050 - Glottis Heart",    2, 2050, "seqGlottisHeart",      0,  0, 300, 105, 0}, /* 005 */
-	{"2055 - Slingshot Bone",   2, 2055, "seqSlingshotBone",     0,  0, 300, 127, 0}, /* 006 */
-	{"2060 - Glott Tree Fall",  2, 2060, "seqGlottTreeFall",     0,  0, 300, 127, 0}, /* 007 */
-	{"2070 - Beaver Fly",       2, 2070, "seqBeaverFly",         0,  0, 300, 127, 0}, /* 008 */
-	{"2071 - Beaver Sink",      2, 2071, "seqBeaverSink",        0,  0, 300, 127, 0}, /* 009 */
-	{"2080 - Meet Velasco",     2, 2080, "seqMeetVelasco",       0,  0, 300, 127, 0}, /* 010 */
+	{"",                        0, 2000, "SEQ_NULL",             0,  0, 300, 127, 0 }, /* 000 */
+	{"2001 - Climb Rope",       2, 2001, "seqClimbRope",         0,  0, 300, 127, 0 }, /* 001 */
+	{"2010 - Glottis OK",       2, 2010, "seqGlottisOK",         0,  0, 300, 127, 0 }, /* 002 */
+	{"2020 - Reap Bruno",       2, 2020, "seqReapBruno",         0,  0, 300, 127, 0 }, /* 003 */
+	{"2030 - Ledgepeckers",     2, 2030, "seqLedgepeckers",      0,  0, 300, 127, 0 }, /* 004 */
+	{"2050 - Glottis Heart",    2, 2050, "seqGlottisHeart",      0,  0, 300, 105, 0 }, /* 005 */
+	{"2055 - Slingshot Bone",   2, 2055, "seqSlingshotBone",     0,  0, 300, 127, 0 }, /* 006 */
+	{"2060 - Glott Tree Fall",  2, 2060, "seqGlottTreeFall",     0,  0, 300, 127, 0 }, /* 007 */
+	{"2070 - Beaver Fly",       2, 2070, "seqBeaverFly",         0,  0, 300, 127, 0 }, /* 008 */
+	{"2071 - Beaver Sink",      2, 2071, "seqBeaverSink",        0,  0, 300, 127, 0 }, /* 009 */
+	{"2080 - Meet Velasco",     2, 2080, "seqMeetVelasco",       0,  0, 300, 127, 0 }, /* 010 */
 	{"2140 - Ooo Bonewagon",    2, 2140, "seqGlottSingBone",     0,  0, 300, 127, 75}, /* 011 */
 	{"2141 - Ooo Meche",        2, 2141, "seqMannySingMeche",    0,  0, 300, 127, 75}, /* 012 */
-	{"2155 - Find Detector",    2, 2155, "seqFindDetector",      0,  0, 300, 127, 0}, /* 013 */
-	{"2156 - Glott Drink Wine", 2, 2156, "seqGlottDrinkWine",    0,  0, 300, 127, 0}, /* 014 */
-	{"2157 - Glott No Wine",    2, 2157, "seqGlottNoWine",       0,  0, 300, 127, 0}, /* 015 */
-	{"2161 - Raoul Appears",    2, 2161, "seqRaoulAppears",      0,  0, 300, 127, 0}, /* 016 */
-	{"2162 - Raoul KO",         2, 2162, "seqRaoulKO",           0,  0, 300, 127, 0}, /* 017 */
-	{"2163 - Raoul Dissed",     2, 2163, "seqRaoulDissed",       0,  0, 300, 127, 0}, /* 018 */
-	{"2165 - Fake Tix",         2, 2165, "seqFakeTix",           0,  0, 300, 127, 0}, /* 019 */
-	{"2180 - Befriend Commies", 2, 2180, "seqBefriendCommies",   0,  0, 300, 127, 0}, /* 020 */
-	{"2186 - Nick Punchout",    2, 2186, "seqNickPunchout",      0,  0, 300, 127, 0}, /* 021 */
-	{"2200 - Yr 3 Iris",        2, 2200, "seqYr3Iris",           0,  0, 300, 127, 0}, /* 022 */
-	{"2210 - Hit Men",          2, 2210, "seqHitMen",            0,  0, 700, 127, 0}, /* 023 */
-	{"2230 - Open Vault",       2, 2230, "seqOpenVault",         0,  0, 300, 127, 0}, /* 024 */
-	{"2235 - Dead Tix",         2, 2235, "seqDeadTix",           0,  0, 300, 127, 0}, /* 025 */
-	{"2240 - Sprinkler",        2, 2240, "seqSprinkler",         0,  0, 500, 127, 0}, /* 026 */
-	{"2250 - Crane Track",      2, 2250, "seqCraneTrack",        0,  0, 300, 127, 0}, /* 027 */
-	{"2255 - Crane Fall",       2, 2255, "seqCraneFall",         0,  0, 300, 127, 0}, /* 028 */
-	{"2300 - Yr 4 Iris",        2, 2300, "seqYr4Iris",           0,  0, 300, 127, 0}, /* 029 */
-	{"2301 - Pop Bruno Casket", 2, 2301, "seqPopBrunoCasket",    0,  0, 300, 127, 0}, /* 030 */
-	{"2310 - Rocket Idea",      2, 2310, "seqRocketIdea",        0,  0, 300, 127, 0}, /* 031 */
-	{"2320 - Jello Suspense",   2, 2320, "seqJelloSuspense",     0,  0, 300, 127, 0}, /* 032 */
-	{"2325 - Lumbago Lemo",     2, 2325, "seqLumbagoLemo",       0,  0, 300, 127, 0}, /* 033 */
-	{"2327 - Breath Mint",      2, 2327, "seqBreathMint",        0,  0, 300, 127, 0}, /* 034 */
-	{"2330 - Pigeon Fly",       2, 2330, "seqPigeonFly",         0,  0, 300, 127, 0}, /* 035 */
-	{"2340 - Coffee On Boys",   2, 2340, "seqCoffeeOnBoys",      0,  0, 300, 127, 0}, /* 036 */
-	{"2350 - Sprout Aha",       2, 2350, "seqSproutAha",         0,  0, 300, 127, 0}, /* 037 */
-	{"2360 - Chowchilla Bye",   2, 2360, "seqChowchillaBye",     0,  0, 300, 127, 0}, /* 038 */
-	{"2370 - Salvador Death",   2, 2370, "seqSalvadorDeath",     0,  0, 300, 127, 0}, /* 039 */
-	{"2399 - End Credits",      2, 2399, "seqEndCredits",        0,  0, 200, 127, 0}, /* 040 */
+	{"2155 - Find Detector",    2, 2155, "seqFindDetector",      0,  0, 300, 127, 0 }, /* 013 */
+	{"2156 - Glott Drink Wine", 2, 2156, "seqGlottDrinkWine",    0,  0, 300, 127, 0 }, /* 014 */
+	{"2157 - Glott No Wine",    2, 2157, "seqGlottNoWine",       0,  0, 300, 127, 0 }, /* 015 */
+	{"2161 - Raoul Appears",    2, 2161, "seqRaoulAppears",      0,  0, 300, 127, 0 }, /* 016 */
+	{"2162 - Raoul KO",         2, 2162, "seqRaoulKO",           0,  0, 300, 127, 0 }, /* 017 */
+	{"2163 - Raoul Dissed",     2, 2163, "seqRaoulDissed",       0,  0, 300, 127, 0 }, /* 018 */
+	{"2165 - Fake Tix",         2, 2165, "seqFakeTix",           0,  0, 300, 127, 0 }, /* 019 */
+	{"2180 - Befriend Commies", 2, 2180, "seqBefriendCommies",   0,  0, 300, 127, 0 }, /* 020 */
+	{"2186 - Nick Punchout",    2, 2186, "seqNickPunchout",      0,  0, 300, 127, 0 }, /* 021 */
+	{"2200 - Yr 3 Iris",        2, 2200, "seqYr3Iris",           0,  0, 300, 127, 0 }, /* 022 */
+	{"2210 - Hit Men",          2, 2210, "seqHitMen",            0,  0, 700, 127, 0 }, /* 023 */
+	{"2230 - Open Vault",       2, 2230, "seqOpenVault",         0,  0, 300, 127, 0 }, /* 024 */
+	{"2235 - Dead Tix",         2, 2235, "seqDeadTix",           0,  0, 300, 127, 0 }, /* 025 */
+	{"2240 - Sprinkler",        2, 2240, "seqSprinkler",         0,  0, 500, 127, 0 }, /* 026 */
+	{"2250 - Crane Track",      2, 2250, "seqCraneTrack",        0,  0, 300, 127, 0 }, /* 027 */
+	{"2255 - Crane Fall",       2, 2255, "seqCraneFall",         0,  0, 300, 127, 0 }, /* 028 */
+	{"2300 - Yr 4 Iris",        2, 2300, "seqYr4Iris",           0,  0, 300, 127, 0 }, /* 029 */
+	{"2301 - Pop Bruno Casket", 2, 2301, "seqPopBrunoCasket",    0,  0, 300, 127, 0 }, /* 030 */
+	{"2310 - Rocket Idea",      2, 2310, "seqRocketIdea",        0,  0, 300, 127, 0 }, /* 031 */
+	{"2320 - Jello Suspense",   2, 2320, "seqJelloSuspense",     0,  0, 300, 127, 0 }, /* 032 */
+	{"2325 - Lumbago Lemo",     2, 2325, "seqLumbagoLemo",       0,  0, 300, 127, 0 }, /* 033 */
+	{"2327 - Breath Mint",      2, 2327, "seqBreathMint",        0,  0, 300, 127, 0 }, /* 034 */
+	{"2330 - Pigeon Fly",       2, 2330, "seqPigeonFly",         0,  0, 300, 127, 0 }, /* 035 */
+	{"2340 - Coffee On Boys",   2, 2340, "seqCoffeeOnBoys",      0,  0, 300, 127, 0 }, /* 036 */
+	{"2350 - Sprout Aha",       2, 2350, "seqSproutAha",         0,  0, 300, 127, 0 }, /* 037 */
+	{"2360 - Chowchilla Bye",   2, 2360, "seqChowchillaBye",     0,  0, 300, 127, 0 }, /* 038 */
+	{"2370 - Salvador Death",   2, 2370, "seqSalvadorDeath",     0,  0, 300, 127, 0 }, /* 039 */
+	{"2399 - End Credits",      2, 2399, "seqEndCredits",        0,  0, 200, 127, 0 }, /* 040 */
 };
 
 // The state table of the previous iMUSE implementation had some entries in a different order, so


Commit: 07787ada452707cc1e6a90ea676cea73b983e0d0
    https://github.com/scummvm/scummvm/commit/07787ada452707cc1e6a90ea676cea73b983e0d0
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Add support for demo

Changed paths:
    engines/grim/costume/sound_component.cpp
    engines/grim/grim.cpp
    engines/grim/imuse/imuse_dispatch.cpp
    engines/grim/imuse/imuse_engine.cpp
    engines/grim/imuse/imuse_engine.h
    engines/grim/imuse/imuse_files.cpp
    engines/grim/imuse/imuse_internalmixer.cpp
    engines/grim/imuse/imuse_internalmixer.h
    engines/grim/imuse/imuse_scripts.cpp
    engines/grim/imuse/imuse_tables.cpp
    engines/grim/imuse/imuse_tables.h
    engines/grim/imuse/imuse_tracks.cpp
    engines/grim/lua_v1_sound.cpp
    engines/grim/sound.cpp


diff --git a/engines/grim/costume/sound_component.cpp b/engines/grim/costume/sound_component.cpp
index 6db290f0a13..9f940b0f960 100644
--- a/engines/grim/costume/sound_component.cpp
+++ b/engines/grim/costume/sound_component.cpp
@@ -49,10 +49,17 @@ void SoundComponent::setKey(int val) {
 	switch (val) {
 	case 0: // "Play"
 		if (!g_imuse->soundsIsSoundPlaying(_name.c_str())) {
+			// In the demo the last value is the group, and the sound isn't positioned in the set
+			bool demo = g_grim->getGameFlags() & ADGF_DEMO;
+
 			if (isComponentType('I','M','S','S')) {
 				g_imuse->soundStartVoiceStream(_name.c_str(), _maxVolume, _pan);
-				g_imuse->soundsSetParam(_name.c_str(), IMUSE_P_GROUP, IMUSE_GROUP_SFX);
+				g_imuse->soundsSetParam(_name.c_str(), IMUSE_P_GROUP, demo ? _minVolume : IMUSE_GROUP_SFX);
 				g_imuse->soundsSetParam(_name.c_str(), IMUSE_P_PRIORITY, _priority);
+			} else if (demo) {
+				g_imuse->soundsLoadStartSound(_name.c_str(), _priority, _minVolume);
+				g_imuse->soundsSetParam(_name.c_str(), IMUSE_P_VOLUME, _maxVolume);
+				g_imuse->soundsSetParam(_name.c_str(), IMUSE_P_PAN, _pan);
 			} else {
 				g_imuse->soundsLoadStartSound(_name.c_str(), _priority, IMUSE_GROUP_SFX);
 
diff --git a/engines/grim/grim.cpp b/engines/grim/grim.cpp
index 847c4d5ff6a..05e7c5a7b0f 100644
--- a/engines/grim/grim.cpp
+++ b/engines/grim/grim.cpp
@@ -401,7 +401,7 @@ Common::Error GrimEngine::run() {
 		if (ConfMan.hasKey("imuse_low_latency_mode", _targetName))
 			lowLatencyMode = ConfMan.getBool("imuse_low_latency_mode");
 
-		g_imuse = new IMuse(sampleRate, _mixer, &_imuseMutex, lowLatencyMode);
+		g_imuse = new IMuse(sampleRate, _mixer, &_imuseMutex, lowLatencyMode, demo);
 		g_emiSound = nullptr;
 		if (g_grim->isRemastered()) {
 			// This must happen here, since we need the resource loader set up.
diff --git a/engines/grim/imuse/imuse_dispatch.cpp b/engines/grim/imuse/imuse_dispatch.cpp
index b90bb0221d5..e449e4e6780 100644
--- a/engines/grim/imuse/imuse_dispatch.cpp
+++ b/engines/grim/imuse/imuse_dispatch.cpp
@@ -725,6 +725,11 @@ int IMuse::dispatchNavigateMap(IMuseDispatch *dispatchPtr) {
 			// - Block size in bytes minus 8 (4 bytes)
 			// - Block offset (4 bytes)
 			// - Region length (4 bytes)
+			if (_demo && (int32)READ_UINT32(mapCurEvent + 8) != dispatchPtr->currentOffset) {
+				debug(5, "IMuse::dispatchNavigateMap(): ERROR: region offset %d != currentOffset %d", (int32)READ_UINT32(mapCurEvent + 8), dispatchPtr->currentOffset);
+				return -1;
+			}
+
 			dispatchPtr->audioRemaining = READ_UINT32(mapCurEvent + 12);
 			return 0;
 		case MKTAG('T', 'E', 'X', 'T'):
@@ -737,7 +742,9 @@ int IMuse::dispatchNavigateMap(IMuseDispatch *dispatchPtr) {
 			marker = (char *)mapCurEvent + 12;
 			soundId = dispatchPtr->trackPtr->soundId;
 			_triggersHandler->processTriggers(soundId, marker);
-			if (soundId != dispatchPtr->trackPtr->soundId)
+
+			// (The demo doesn't check if the trigger has switched the sound)
+			if (!_demo && soundId != dispatchPtr->trackPtr->soundId)
 				return -3;
 
 			if (dispatchPtr->audioRemaining)
diff --git a/engines/grim/imuse/imuse_engine.cpp b/engines/grim/imuse/imuse_engine.cpp
index 873f28e2d6d..67f022f87ad 100644
--- a/engines/grim/imuse/imuse_engine.cpp
+++ b/engines/grim/imuse/imuse_engine.cpp
@@ -42,10 +42,12 @@ void IMuse::timer_handler(void *refCon) {
 	imuse->imHeartbeat();
 }
 
-IMuse::IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode)
+IMuse::IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode, bool demo)
 	: _mixer(mixer), _mutex(mutex) {
 	assert(mixer);
 
+	_demo = demo;
+
 	// 50 Hz rate for the callback
 	_callbackFps = IMUSE_TIMER_BASE_RATE_HZ;
 	_usecPerInt = IMUSE_TIMER_BASE_RATE_USEC;
@@ -80,7 +82,7 @@ IMuse::IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool low
 	_underrunCooldown = 0;
 
 	_emptyMarker[0] = '\0';
-	_internalMixer = new IMuseInternalMixer(mixer, _internalSampleRate, _lowLatencyMode);
+	_internalMixer = new IMuseInternalMixer(mixer, _internalSampleRate, _lowLatencyMode, _demo);
 	_groupsHandler = new IMuseGroupsHandler(this, mutex);
 	_fadesHandler = new IMuseFadesHandler(this, mutex);
 	_triggersHandler = new IMuseTriggersHandler(this, mutex);
@@ -116,8 +118,13 @@ IMuse::IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool low
 	setupHMI(IMUSE_HMI_HEAP_SIZE);
 
 	imInitialize();
-	soundsAllocateBuffer(IMUSE_BUFFER_MUSIC, 440000, 44000, 352000);
-	soundsAllocateBuffer(IMUSE_BUFFER_SPEECH, 88000, 44000, 88000);
+	if (_demo) {
+		soundsAllocateBuffer(IMUSE_BUFFER_MUSIC, 528000, 44000, 352000);
+		soundsAllocateBuffer(IMUSE_BUFFER_SPEECH, 176000, 44000, 88000);
+	} else {
+		soundsAllocateBuffer(IMUSE_BUFFER_MUSIC, 440000, 44000, 352000);
+		soundsAllocateBuffer(IMUSE_BUFFER_SPEECH, 88000, 44000, 88000);
+	}
 	imInitializeScript();
 
 	if (_mixer->getOutputBufSize() != 0) {
@@ -220,15 +227,21 @@ void IMuse::imHeartbeat() {
 		}
 
 		// Music gain reduction while speech is playing
+		// (The demo does it twice as often, with a different reduction and different steps)
+		int gainRedRateUsec = _demo ? 100000 : IMUSE_TIMER_GAIN_RED_RATE_USEC;
+		int gainRedFactor = _demo ? 80 : 77;
+		int gainRedStepUp = _demo ? 3 : 1;
+		int gainRedStepDown = _demo ? 18 : 36;
+
 		_cmdsRunning5HzCount += _usecPerInt;
-		if (_cmdsRunning5HzCount >= IMUSE_TIMER_GAIN_RED_RATE_USEC) {
+		if (_cmdsRunning5HzCount >= gainRedRateUsec) {
 			while (1) {
-				_cmdsRunning5HzCount -= IMUSE_TIMER_GAIN_RED_RATE_USEC;
+				_cmdsRunning5HzCount -= gainRedRateUsec;
 
 				musicTargetVolume = _groupsHandler->setGroupVol(IMUSE_GROUP_MUSIC, -1);
 				for (soundId = imGetNextSound(0); soundId; soundId = imGetNextSound(soundId)) {
 					if (imGetParam(soundId, IMUSE_P_GROUP) == IMUSE_GROUP_SPEECH) {
-						musicTargetVolume = (77 * musicTargetVolume) >> 7;
+						musicTargetVolume = (gainRedFactor * musicTargetVolume) >> 7;
 						break;
 					}
 				}
@@ -237,7 +250,7 @@ void IMuse::imHeartbeat() {
 				musicVol = _groupsHandler->setGroupVol(IMUSE_GROUP_MUSIC, -1);
 
 				if (musicEffVol > musicTargetVolume) {
-					tempVol = musicEffVol - 36;
+					tempVol = musicEffVol - gainRedStepDown;
 					if (tempVol <= musicTargetVolume) {
 						if (musicTargetVolume < musicVol)
 							musicVol = musicTargetVolume;
@@ -246,7 +259,7 @@ void IMuse::imHeartbeat() {
 					}
 					_groupsHandler->setGroupVol(IMUSE_GROUP_MUSICEFF, musicVol);
 				} else if (musicEffVol < musicTargetVolume) {
-					tempEffVol = musicEffVol + 1;
+					tempEffVol = musicEffVol + gainRedStepUp;
 					if (tempEffVol < musicTargetVolume) {
 						if (tempEffVol > musicVol)
 							musicVol = tempEffVol;
@@ -256,7 +269,7 @@ void IMuse::imHeartbeat() {
 					_groupsHandler->setGroupVol(IMUSE_GROUP_MUSICEFF, musicVol);
 				}
 
-				if (_cmdsRunning5HzCount < IMUSE_TIMER_GAIN_RED_RATE_USEC)
+				if (_cmdsRunning5HzCount < gainRedRateUsec)
 					break;
 			}
 		}
diff --git a/engines/grim/imuse/imuse_engine.h b/engines/grim/imuse/imuse_engine.h
index 3ff19701145..48fbda4be23 100644
--- a/engines/grim/imuse/imuse_engine.h
+++ b/engines/grim/imuse/imuse_engine.h
@@ -87,6 +87,8 @@ private:
 
 	int _curMixerMusicVolume, _curMixerSpeechVolume, _curMixerSFXVolume;
 
+	bool _demo;
+
 	int32 _attributes[228];	// internal attributes for each music file to store and check later
 	int32 _nextSeqToPlay;
 	int32 _curMusicState;
@@ -109,9 +111,10 @@ private:
 	void scriptSaveLoad(Common::Serializer &ser);
 	void scriptDeinit();
 	void scriptRefresh();
-	void scriptSetState(int soundId);
-	void scriptSetSequence(int soundId);
+	int scriptSetState(int soundId);
+	int scriptSetSequence(int soundId);
 	void scriptPlayMusic(const IMuseStateTable *tableEntry, int curSongEntryId, int isSequence);
+	void scriptPlayMusicDemo(const IMuseStateTable *tableEntry, int curSongEntryId, int isSequence);
 	void scriptSetCuePoint(int cueId);
 	int scriptSetAttribute(int attrIndex, int attrVal);
 
@@ -336,7 +339,7 @@ private:
 	uint8 *_waveOutLowLatencyOutputBuffer;
 
 public:
-	IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode = false);
+	IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode = false, bool demo = false);
 	~IMuse();
 
 	// Wrapper functions used by the main engine
diff --git a/engines/grim/imuse/imuse_files.cpp b/engines/grim/imuse/imuse_files.cpp
index d7493617ac2..690bcbee8c2 100644
--- a/engines/grim/imuse/imuse_files.cpp
+++ b/engines/grim/imuse/imuse_files.cpp
@@ -891,85 +891,112 @@ int IMuse::cacheGetSoundId(const char *soundName) {
 	if (!soundName)
 		return 0;
 
-	if (soundKey == 10000)
-		return 10000;
+	if (_demo) {
+		// The cache of the demo has 16 slots and sounds are only looked up by name: there are
+		// no Lua sound IDs (so a number can't be a valid name), and no lipsync data is loaded here
+		if (soundKey <= 0xFFFF)
+			return 0;
 
-	if (soundKey <= 1111)
-		return 0;
+		for (slot = 15; slot >= 0; slot--) {
+			if (!scumm_stricmp(_soundCache[slot].soundFilename, soundName))
+				return slot + 100;
 
-	isLuaSoundId = soundKey < 1367;
-	if (soundKey > 1367) {
-		if (strlen(soundName) <= 4) {
-			soundId = atoi(soundName);
-			if (soundId == 10000)
-				return soundId;
+			if (!_soundCache[slot].soundFilename[0])
+				loadSlot = slot;
+		}
 
-			if (soundId >= 1111 && soundId < 1367)
+		// The sound is not in the cache: pick an empty slot or purge the oldest one
+		if (loadSlot < 0) {
+			loadSlot = cachePurgeOldestStoppedSound();
+			if (loadSlot < 0)
 				return 0;
 		}
 
-		isLuaSoundId = false;
-	}
+		sound = &_soundCache[loadSlot];
+		Common::strlcpy(sound->soundFilename, soundName, sizeof(sound->soundFilename));
+		sound->tsOfAllocation = g_system->getMillis();
+		allocated = true;
+	} else {
+		if (soundKey == 10000)
+			return 10000;
+
+		if (soundKey <= 1111)
+			return 0;
 
-	sound = &_soundCache[IMUSE_MAX_CACHED_SOUNDS - 1];
-	slot = IMUSE_MAX_CACHED_SOUNDS - 1;
+		isLuaSoundId = soundKey < 1367;
+		if (soundKey > 1367) {
+			if (strlen(soundName) <= 4) {
+				soundId = atoi(soundName);
+				if (soundId == 10000)
+					return soundId;
 
-	if (isLuaSoundId) {
-		while ((uintptr)sound->luaSoundId != soundKey) {
-			--sound;
-			if (!slot--)
-				return 0;
+				if (soundId >= 1111 && soundId < 1367)
+					return 0;
+			}
+
+			isLuaSoundId = false;
 		}
 
-		if (sound->soundUncompData)
-			return slot + 100;
+		sound = &_soundCache[IMUSE_MAX_CACHED_SOUNDS - 1];
+		slot = IMUSE_MAX_CACHED_SOUNDS - 1;
 
-		loadSlot = slot;
-	} else {
-		while (scumm_stricmp(sound->soundFilename, soundName)) {
-			if (!sound->soundFilename[0])
-				loadSlot = slot;
+		if (isLuaSoundId) {
+			while ((uintptr)sound->luaSoundId != soundKey) {
+				--sound;
+				if (!slot--)
+					return 0;
+			}
 
-			--sound;
-			if (!slot--) {
-				// The sound is not in the cache: pick an empty slot or purge the oldest one
-				if (loadSlot < 0) {
-					loadSlot = cachePurgeOldestStoppedSound();
-					if (loadSlot < 0)
-						return 0;
-				}
+			if (sound->soundUncompData)
+				return slot + 100;
 
-				sound = &_soundCache[loadSlot];
-				Common::strlcpy(sound->soundFilename, soundName, sizeof(sound->soundFilename));
-
-				int slotCounter = _currentSoundSlot;
-				bool collision;
-				do {
-					collision = false;
-					int candidateId = abs(slotCounter) % 256 + 1111;
-					for (int i = 0; i < IMUSE_MAX_CACHED_SOUNDS; i++) {
-						if (_soundCache[i].soundFilename[0] && _soundCache[i].luaSoundId == candidateId) {
-							collision = true;
-							slotCounter++;
-							break;
-						}
+			loadSlot = slot;
+		} else {
+			while (scumm_stricmp(sound->soundFilename, soundName)) {
+				if (!sound->soundFilename[0])
+					loadSlot = slot;
+
+				--sound;
+				if (!slot--) {
+					// The sound is not in the cache: pick an empty slot or purge the oldest one
+					if (loadSlot < 0) {
+						loadSlot = cachePurgeOldestStoppedSound();
+						if (loadSlot < 0)
+							return 0;
 					}
-				} while (collision);
 
-				_currentSoundSlot = slotCounter;
-				sound->luaSoundId = abs(slotCounter) % 256 + 1111;
-				++_currentSoundSlot;
+					sound = &_soundCache[loadSlot];
+					Common::strlcpy(sound->soundFilename, soundName, sizeof(sound->soundFilename));
+
+					int slotCounter = _currentSoundSlot;
+					bool collision;
+					do {
+						collision = false;
+						int candidateId = abs(slotCounter) % 256 + 1111;
+						for (int i = 0; i < IMUSE_MAX_CACHED_SOUNDS; i++) {
+							if (_soundCache[i].soundFilename[0] && _soundCache[i].luaSoundId == candidateId) {
+								collision = true;
+								slotCounter++;
+								break;
+							}
+						}
+					} while (collision);
 
-				allocated = true;
-				break;
+					_currentSoundSlot = slotCounter;
+					sound->luaSoundId = abs(slotCounter) % 256 + 1111;
+					++_currentSoundSlot;
+
+					allocated = true;
+					break;
+				}
 			}
-		}
 
-		if (!allocated) {
-			if (sound->soundUncompData)
-				return slot + 100;
+			if (!allocated) {
+				if (sound->soundUncompData)
+					return slot + 100;
 
-			loadSlot = slot;
+				loadSlot = slot;
+			}
 		}
 	}
 
@@ -978,18 +1005,23 @@ int IMuse::cacheGetSoundId(const char *soundName) {
 
 	IMuseResource *res = soundsOpenFile(sound->soundFilename);
 	if (!res) {
-		memset(sound, 0, sizeof(IMuseCachedSound));
+		// (The demo leaves the name of the sound in the slot)
+		if (!_demo)
+			memset(sound, 0, sizeof(IMuseCachedSound));
+
 		return 0;
 	}
 
 	sound->tsOfAllocation = g_system->getMillis();
 
-	char lipsyncFilename[32];
-	Common::strlcpy(lipsyncFilename, sound->soundFilename, sizeof(lipsyncFilename));
-	char *extension = strrchr(lipsyncFilename, '.');
-	if (extension) {
-		Common::strlcpy(extension, ".lip", lipsyncFilename + sizeof(lipsyncFilename) - extension);
-		loadLip(lipsyncFilename, sound->luaSoundId);
+	if (!_demo) {
+		char lipsyncFilename[32];
+		Common::strlcpy(lipsyncFilename, sound->soundFilename, sizeof(lipsyncFilename));
+		char *extension = strrchr(lipsyncFilename, '.');
+		if (extension) {
+			Common::strlcpy(extension, ".lip", lipsyncFilename + sizeof(lipsyncFilename) - extension);
+			loadLip(lipsyncFilename, sound->luaSoundId);
+		}
 	}
 
 	soundsFileSeek(res, 0, SEEK_END);
@@ -1038,7 +1070,15 @@ int IMuse::cacheGetSoundId(const char *soundName) {
 			createSoundHeader(newHeader, 3, sampleRate, 16, numChannels, dataLength);
 			sound->soundMap = newHeader;
 			sound->soundAddrData = extFormatBuffer - 80;
-			newHeader[31] = swapEndianFlag;
+
+			if (!_demo) {
+				newHeader[31] = swapEndianFlag;
+			} else if (!swapEndianFlag) {
+				// The demo swaps the samples right away
+				uint32 numSamples = (uint32)(sound->soundUncompData + dataLength - extFormatBuffer) >> 1;
+				for (uint32 i = 0; i < numSamples; i++)
+					SWAP(extFormatBuffer[2 * i], extFormatBuffer[2 * i + 1]);
+			}
 		}
 
 		return loadSlot + 100;
@@ -1054,8 +1094,9 @@ int IMuse::cachePurgeOldestStoppedSound() {
 	int foundSlot = -1;
 	int emptySlot = -1;
 	uint32 oldestTimestamp = g_system->getMillis();
+	int numSlots = _demo ? 16 : IMUSE_MAX_CACHED_SOUNDS;
 
-	for (int slot = IMUSE_MAX_CACHED_SOUNDS - 1; slot >= 0; slot--) {
+	for (int slot = numSlots - 1; slot >= 0; slot--) {
 		IMuseCachedSound *sound = &_soundCache[slot];
 
 		if (sound->soundFilename[0] && sound->soundUncompData) {
@@ -1073,7 +1114,8 @@ int IMuse::cachePurgeOldestStoppedSound() {
 	if (foundSlot >= 0) {
 		IMuseCachedSound *sound = &_soundCache[foundSlot];
 		sound->soundFilename[0] = 0;
-		soundsResetLipsyncState(sound->luaSoundId);
+		if (!_demo)
+			soundsResetLipsyncState(sound->luaSoundId);
 
 		free(sound->soundUncompData);
 		memset(sound, 0, sizeof(IMuseCachedSound));
@@ -1274,6 +1316,11 @@ int IMuse::soundsLoadStartSound(const char *soundName, int priority, int group)
 	if (!soundId)
 		return 0;
 
+	if (_demo) {
+		imStartSound(soundId, priority);
+		return imSetParam(soundId, IMUSE_P_GROUP, group);
+	}
+
 	if (priority > 124)
 		priority = 124;
 
@@ -1326,7 +1373,7 @@ void IMuse::soundsSetParam(const char *soundName, int paramId, int value) {
 int IMuse::soundsFadeParam(const char *soundName, int paramId, int value, int length) {
 	int soundId = cacheGetSoundId(soundName);
 	if (soundId)
-		return imFadeParam(soundId, paramId, value, 60 * length / 1000);
+		return imFadeParam(soundId, paramId, value, _demo ? length : 60 * length / 1000);
 
 	return 1;
 }
@@ -1428,7 +1475,7 @@ void IMuse::soundsPeriodic() {
 	imProcessStreams();
 	imRefreshScript();
 
-	for (int slot = IMUSE_MAX_CACHED_SOUNDS - 1; slot >= 0; slot--) {
+	for (int slot = (_demo ? 16 : IMUSE_MAX_CACHED_SOUNDS) - 1; slot >= 0; slot--) {
 		if (_soundCache[slot].soundFilename[0] && _soundCache[slot].soundUncompData)
 			cachedSize += _soundCache[slot].uncompResourceSize;
 	}
@@ -1458,14 +1505,20 @@ int IMuse::soundsRegisterVoice(const char *filename) {
 	Common::strlcpy(_curSpeechFile, filename, sizeof(_curSpeechFile));
 	Common::strlcpy(lipsyncFilename, filename, sizeof(lipsyncFilename));
 
-	char *extension = strrchr(lipsyncFilename, '.');
-	if (extension) {
-		Common::strlcpy(extension, ".lip", lipsyncFilename + sizeof(lipsyncFilename) - extension);
-		loadLip(lipsyncFilename, kTalkSoundID);
+	// The demo doesn't register the lipsync here, and doesn't compute the duration of the file
+	if (!_demo) {
+		char *extension = strrchr(lipsyncFilename, '.');
+		if (extension) {
+			Common::strlcpy(extension, ".lip", lipsyncFilename + sizeof(lipsyncFilename) - extension);
+			loadLip(lipsyncFilename, kTalkSoundID);
+		}
 	}
 
 	IMuseResource *res = soundsOpenFile(filename);
 	_openAudioFiles[0].resourcePtr = res;
+	if (_demo)
+		return res ? 1 : 0;
+
 	if (!res) {
 		_millisecsInCurSpeechFile = 0;
 		return 0;
@@ -1481,7 +1534,8 @@ int IMuse::soundsRegisterVoice(const char *filename) {
 void IMuse::soundsCloseVoiceFile() {
 	if (_openAudioFiles[0].resourcePtr) {
 		soundsCloseFile(_openAudioFiles[0].resourcePtr);
-		soundsResetLipsyncState(kTalkSoundID);
+		if (!_demo)
+			soundsResetLipsyncState(kTalkSoundID);
 		_openAudioFiles[0].resourcePtr = nullptr;
 	}
 }
diff --git a/engines/grim/imuse/imuse_internalmixer.cpp b/engines/grim/imuse/imuse_internalmixer.cpp
index 6ba3fb122c5..95389b199d3 100644
--- a/engines/grim/imuse/imuse_internalmixer.cpp
+++ b/engines/grim/imuse/imuse_internalmixer.cpp
@@ -30,10 +30,19 @@
 
 namespace Grim {
 
-IMuseInternalMixer::IMuseInternalMixer(Audio::Mixer *mixer, int sampleRate, bool lowLatencyMode) {
+// The demo's mixer keeps all of its tables in a single block (sizes in int16 units):
+// 17 volume tables for 8 bit sources (256 entries each), 17 volume tables for 16 bit
+// sources (4096 entries each) and the soft clipping table (indexes from -16384 to 16383)
+#define DEMO_TABLES_SIZE      0x34200
+#define DEMO_VOLTABLES8_POS   0
+#define DEMO_VOLTABLES16_POS  4352
+#define DEMO_SOFTTABLE_POS    90368
+
+IMuseInternalMixer::IMuseInternalMixer(Audio::Mixer *mixer, int sampleRate, bool lowLatencyMode, bool demo) {
 	_mixer = mixer;
 	_sampleRate = sampleRate;
 	_lowLatencyMode = lowLatencyMode;
+	_demo = demo;
 
 	// Mark all separate streams for low latency mode as available...
 	for (int i = 0; i < ARRAYSIZE(_separateStreams); i++) {
@@ -62,22 +71,66 @@ int IMuseInternalMixer::init(int numChannels, int mixBufSize, int mixChannelsNum
 	// Pan table: 17 volume levels x 17 pan positions
 	for (int i = 0; i < 17; i++) {
 		for (int j = 0; j < 17; j++) {
-			_mixerTable[17 * i + j] = (uint8)(int)((sin((double)j * 3.1415 * 0.03125) * (double)i + 0.5) * 8.0);
+			if (_demo)
+				_mixerTable[17 * i + j] = (uint8)(int)(sin((double)j * 3.1415 * 0.03125) * (double)i + 0.5);
+			else
+				_mixerTable[17 * i + j] = (uint8)(int)((sin((double)j * 3.1415 * 0.03125) * (double)i + 0.5) * 8.0);
 		}
 	}
 
 	_outChannelCount = numChannels;
-	_mixBufSize = 2 * mixBufSize;
-	_mixBuf = (int32 *)malloc(_mixBufSize);
 
-	_softLTable = (int16 *)malloc(mixChannelsNum << 16);
-	if (!_softLTable) {
-		debug(5, "IMuseInternalMixer::init(): ERROR: couldn't allocate mixer tables");
-		return -1;
-	}
+	if (_demo) {
+		// The demo mixes in 16 bit
+		_mixBufSize = mixBufSize;
+		_mixBuf = (int32 *)malloc(_mixBufSize);
+
+		_softLTable = (int16 *)malloc(DEMO_TABLES_SIZE);
+		if (!_softLTable) {
+			debug(5, "IMuseInternalMixer::init(): ERROR: couldn't allocate mixer tables");
+			return -1;
+		}
+
+		// Volume tables, for 17 levels (0, 7, 15, 23, ..., 127)
+		int level = 0;
+		for (int i = 0; i < 17; i++) {
+			for (int j = 0; j < 256; j++)
+				_softLTable[DEMO_VOLTABLES8_POS + 256 * i + j] = (int16)((-2048 * level + 16 * level * j) / 127);
+
+			for (int j = 0; j < 4096; j++)
+				_softLTable[DEMO_VOLTABLES16_POS + 4096 * i + j] = (int16)((-2048 * level + level * j) / 127);
+
+			level += 8;
+			if (level == 8)
+				level = 7;
+		}
+
+		// Soft clipping table (the 32 bit arithmetic is meant to wrap here)
+		int16 *softTable = &_softLTable[DEMO_SOFTTABLE_POS];
+		uint32 accumulator = 0;
+		int divisor = 16376;
+		for (int i = 0; divisor < 131064; i++) {
+			int quotient = (int32)accumulator / divisor;
+			accumulator += 524272;
+			divisor += 7;
+
+			int value = (quotient + 1) / 2;
+			softTable[i] = (int16)value;
+			softTable[-1 - i] = (int16)(-1 - value);
+		}
+	} else {
+		_mixBufSize = 2 * mixBufSize;
+		_mixBuf = (int32 *)malloc(_mixBufSize);
 
-	for (int i = 0; i < (mixChannelsNum << 15); i++) {
-		_softLTable[i] = (int16)(int)(((double)i * 524272.0 / (262136.0 + (double)i * 7.0) + 1.0) * 0.5);
+		_softLTable = (int16 *)malloc(mixChannelsNum << 16);
+		if (!_softLTable) {
+			debug(5, "IMuseInternalMixer::init(): ERROR: couldn't allocate mixer tables");
+			return -1;
+		}
+
+		for (int i = 0; i < (mixChannelsNum << 15); i++) {
+			_softLTable[i] = (int16)(int)(((double)i * 524272.0 / (262136.0 + (double)i * 7.0) + 1.0) * 0.5);
+		}
 	}
 
 	if (!_lowLatencyMode) {
@@ -102,6 +155,73 @@ int IMuseInternalMixer::clearMixerBuffer() {
 }
 
 void IMuseInternalMixer::mix16ToStereo(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int leftAmp, int rightAmp) {
+	if (_demo) {
+		// In the demo the "amplitudes" are the positions of the volume tables to use, each
+		// sample is mapped to 12 bits and the result is accumulated in a 16 bit buffer
+		int16 *mixBufCell = &((int16 *)_mixBuf)[2 * mixBufStartIndex];
+		const int16 *leftTable = &_softLTable[leftAmp + 2048];
+		const int16 *rightTable = &_softLTable[rightAmp + 2048];
+		int32 sample, nextSample;
+
+		if ((uint32)inFrameCount == feedSize) {
+			for (uint32 i = 0; i < feedSize; i++) {
+				sample = READ_LE_INT16(srcBuf) >> 4;
+
+				mixBufCell[0] += leftTable[sample];
+				mixBufCell[1] += rightTable[sample];
+
+				srcBuf++;
+				mixBufCell += 2;
+			}
+		} else if (feedSize == (uint32)(2 * inFrameCount)) {
+			for (int i = 0; i < inFrameCount - 1; i++) {
+				sample = READ_LE_INT16(&srcBuf[0]) >> 4;
+				nextSample = READ_LE_INT16(&srcBuf[1]) >> 4;
+
+				mixBufCell[0] += leftTable[sample];
+				mixBufCell[1] += rightTable[sample];
+				mixBufCell[2] += (leftTable[sample] + leftTable[nextSample]) >> 1;
+				mixBufCell[3] += (rightTable[sample] + rightTable[nextSample]) >> 1;
+
+				srcBuf++;
+				mixBufCell += 4;
+			}
+
+			sample = READ_LE_INT16(srcBuf) >> 4;
+			mixBufCell[0] += leftTable[sample];
+			mixBufCell[1] += rightTable[sample];
+			mixBufCell[2] += leftTable[sample];
+			mixBufCell[3] += rightTable[sample];
+		} else if (2 * feedSize == (uint32)inFrameCount) {
+			for (uint32 i = 0; i < feedSize; i++) {
+				sample = READ_LE_INT16(srcBuf) >> 4;
+
+				mixBufCell[0] += leftTable[sample];
+				mixBufCell[1] += rightTable[sample];
+
+				srcBuf += 2;
+				mixBufCell += 2;
+			}
+		} else {
+			int32 position = -inFrameCount;
+			for (uint32 i = 0; i < feedSize; i++) {
+				sample = READ_LE_INT16(srcBuf) >> 4;
+				position += inFrameCount;
+
+				mixBufCell[0] += leftTable[sample];
+				mixBufCell[1] += rightTable[sample];
+				mixBufCell += 2;
+
+				while (position > 0) {
+					position -= feedSize;
+					srcBuf++;
+				}
+			}
+		}
+
+		return;
+	}
+
 	int32 *mixBufCurCell = &_mixBuf[2 * mixBufStartIndex];
 	uint32 ratio = ((uint32)inFrameCount << 16) / feedSize;
 	uint32 position = 0;
@@ -221,6 +341,75 @@ void IMuseInternalMixer::mix16ToStereoSwap(const int16 *srcBuf, int32 inFrameCou
 }
 
 void IMuseInternalMixer::mix16(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int volume) {
+	if (_demo) {
+		// Same as above, but for sources which already have two channels ("volume" is the position of the table)
+		int16 *mixBufCell = &((int16 *)_mixBuf)[2 * mixBufStartIndex];
+		const int16 *table = &_softLTable[volume + 2048];
+		int32 left, right, nextLeft, nextRight;
+
+		if ((uint32)inFrameCount == feedSize) {
+			for (uint32 i = 0; i < feedSize; i++) {
+				left = READ_LE_INT16(&srcBuf[0]) >> 4;
+				right = READ_LE_INT16(&srcBuf[1]) >> 4;
+
+				mixBufCell[0] += table[left];
+				mixBufCell[1] += table[right];
+
+				srcBuf += 2;
+				mixBufCell += 2;
+			}
+		} else if (feedSize == (uint32)(2 * inFrameCount)) {
+			for (int i = 0; i < inFrameCount - 1; i++) {
+				left = READ_LE_INT16(&srcBuf[0]) >> 4;
+				right = READ_LE_INT16(&srcBuf[1]) >> 4;
+				nextLeft = READ_LE_INT16(&srcBuf[2]) >> 4;
+				nextRight = READ_LE_INT16(&srcBuf[3]) >> 4;
+
+				mixBufCell[0] += table[left];
+				mixBufCell[1] += table[right];
+				mixBufCell[2] += (table[left] + table[nextLeft]) >> 1;
+				mixBufCell[3] += (table[right] + table[nextRight]) >> 1;
+
+				srcBuf += 2;
+				mixBufCell += 4;
+			}
+
+			left = READ_LE_INT16(&srcBuf[0]) >> 4;
+			right = READ_LE_INT16(&srcBuf[1]) >> 4;
+			mixBufCell[0] += table[left];
+			mixBufCell[1] += table[right];
+			mixBufCell[2] += table[left];
+			mixBufCell[3] += table[right];
+		} else if (2 * feedSize == (uint32)inFrameCount) {
+			for (uint32 i = 0; i < feedSize; i++) {
+				left = READ_LE_INT16(&srcBuf[0]) >> 4;
+				right = READ_LE_INT16(&srcBuf[1]) >> 4;
+
+				mixBufCell[0] += table[left];
+				mixBufCell[1] += table[right];
+
+				srcBuf += 4;
+				mixBufCell += 2;
+			}
+		} else {
+			int32 position = -inFrameCount;
+			for (uint32 i = 0; i < feedSize; i++) {
+				left = READ_LE_INT16(&srcBuf[0]) >> 4;
+				right = READ_LE_INT16(&srcBuf[1]) >> 4;
+
+				mixBufCell[0] += table[left];
+				mixBufCell[1] += table[right];
+				mixBufCell += 2;
+
+				// (Unlike the mono version, this one doesn't stop at zero)
+				for (position += inFrameCount; position >= 0; srcBuf += 2)
+					position -= feedSize;
+			}
+		}
+
+		return;
+	}
+
 	int32 *mixBufCurCell = &_mixBuf[2 * mixBufStartIndex];
 	uint32 ratio = ((uint32)inFrameCount << 16) / feedSize;
 	uint32 position = 0;
@@ -329,6 +518,48 @@ void IMuseInternalMixer::mix16Swap(const int16 *srcBuf, int32 inFrameCount, uint
 void IMuseInternalMixer::mix(uint8 *srcBuf, int32 inFrameCount, int wordSize, int channelCount, int swapEndiannessFlag, int feedSize, int32 mixBufStartIndex, int volume, int pan) {
 	int channelVolume, channelPan, leftAmp, rightAmp;
 
+	if (_demo) {
+		// The demo handles 8 bit sources too (with its own volume tables), has no byte swapping
+		// and allows a volume of zero; the volume tables are selected by their positions
+		if (!_mixBuf || !srcBuf || !inFrameCount)
+			return;
+
+		channelVolume = volume >> 3;
+		if (volume)
+			++channelVolume;
+
+		if (channelVolume >= 17)
+			channelVolume = 16;
+
+		if (channelCount == 1 && _outChannelCount == 2) {
+			channelPan = (pan >> 3) - 8;
+			if (pan > 64)
+				++channelPan;
+
+			leftAmp = _mixerTable[17 * channelVolume + 8 - channelPan];
+			rightAmp = _mixerTable[17 * channelVolume + 8 + channelPan];
+
+			if (wordSize == 8) {
+				leftAmp = DEMO_VOLTABLES8_POS + 256 * leftAmp;
+				rightAmp = DEMO_VOLTABLES8_POS + 256 * rightAmp;
+			} else {
+				leftAmp = DEMO_VOLTABLES16_POS + 4096 * leftAmp;
+				rightAmp = DEMO_VOLTABLES16_POS + 4096 * rightAmp;
+			}
+
+			mix16ToStereo((const int16 *)srcBuf, inFrameCount, feedSize, mixBufStartIndex, leftAmp, rightAmp);
+		} else {
+			if (wordSize == 8)
+				volume = DEMO_VOLTABLES8_POS + 256 * channelVolume;
+			else
+				volume = DEMO_VOLTABLES16_POS + 4096 * channelVolume;
+
+			mix16((const int16 *)srcBuf, inFrameCount, feedSize, mixBufStartIndex, volume);
+		}
+
+		return;
+	}
+
 	// The original could divide by zero here, let's avoid that...
 	if (!_mixBuf || !srcBuf || !inFrameCount || wordSize != 16 || volume < 1 || feedSize < 1)
 		return;
@@ -366,6 +597,18 @@ int IMuseInternalMixer::loop(uint8 **destBuffer, int len) {
 	if (_outChannelCount == 2)
 		len *= 2;
 
+	if (_demo) {
+		// (The table covers the values from -16384 to 16383; in the original anything
+		// outside of this range reads memory which doesn't belong to the table)
+		const int16 *mixBuf16 = (const int16 *)_mixBuf;
+		const int16 *softTable = &_softLTable[DEMO_SOFTTABLE_POS];
+
+		for (int i = 0; i < len; i++)
+			destBuffer_tmp[i] = softTable[CLIP<int32>(mixBuf16[i], -16384, 16383)];
+
+		return 0;
+	}
+
 	for (int i = 0; i < len; i++) {
 		value = _mixBuf[i] >> 7;
 		if (value >= 0)
diff --git a/engines/grim/imuse/imuse_internalmixer.h b/engines/grim/imuse/imuse_internalmixer.h
index 97145baaca8..79d252df43e 100644
--- a/engines/grim/imuse/imuse_internalmixer.h
+++ b/engines/grim/imuse/imuse_internalmixer.h
@@ -54,6 +54,7 @@ private:
 	int _outChannelCount = 0;
 	int _sampleRate = 0;
 	bool _lowLatencyMode = false;
+	bool _demo = false;
 
 	void mix16(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int volume);
 	void mix16Swap(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int volume);
@@ -61,7 +62,7 @@ private:
 	void mix16ToStereoSwap(const int16 *srcBuf, int32 inFrameCount, uint32 feedSize, int32 mixBufStartIndex, int leftAmp, int rightAmp);
 
 public:
-	IMuseInternalMixer(Audio::Mixer *mixer, int sampleRate, bool lowLatencyMode = false);
+	IMuseInternalMixer(Audio::Mixer *mixer, int sampleRate, bool lowLatencyMode = false, bool demo = false);
 	~IMuseInternalMixer();
 	int  init(int numChannels, int mixBufSize, int mixChannelsNum);
 	int  terminate();
diff --git a/engines/grim/imuse/imuse_scripts.cpp b/engines/grim/imuse/imuse_scripts.cpp
index 2ab3bd7c9b6..ac4967e0d5d 100644
--- a/engines/grim/imuse/imuse_scripts.cpp
+++ b/engines/grim/imuse/imuse_scripts.cpp
@@ -27,6 +27,10 @@ namespace Grim {
 #define GRIM_SEQ_OFFSET     185
 #define GRIM_STOP_SEQ_ATTR  227
 
+#define GRIM_DEMO_NUM_ATTRIBUTES  31
+#define GRIM_DEMO_SEQ_OFFSET      27
+#define GRIM_DEMO_STOP_SEQ_ATTR   30
+
 int IMuse::scriptParse(int cmd, int a, int b) {
 	if (_scriptInitializedFlag || !cmd) {
 		switch (cmd) {
@@ -48,9 +52,15 @@ int IMuse::scriptParse(int cmd, int a, int b) {
 			scriptRefresh();
 			return 0;
 		case IMUSE_C_SCRIPT_SET_STATE:
+			if (_demo)
+				return scriptSetState(a);
+
 			scriptSetState(a);
 			return 0;
 		case IMUSE_C_SCRIPT_SET_SEQUENCE:
+			if (_demo)
+				return scriptSetSequence(a);
+
 			scriptSetSequence(a);
 			return 0;
 		case IMUSE_C_SCRIPT_CUE_POINT:
@@ -76,7 +86,7 @@ int IMuse::scriptInit() {
 	_curMusicState = 0;
 	_curMusicSeq = 0;
 	_nextSeqToPlay = 0;
-	memset(_attributes, 0, sizeof(_attributes));
+	memset(_attributes, 0, _demo ? GRIM_DEMO_NUM_ATTRIBUTES * sizeof(int32) : sizeof(_attributes));
 	return 0;
 }
 
@@ -86,16 +96,17 @@ int IMuse::scriptTerminate() {
 	_curMusicState = 0;
 	_curMusicSeq = 0;
 	_nextSeqToPlay = 0;
-	memset(_attributes, 0, sizeof(_attributes));
+	memset(_attributes, 0, _demo ? GRIM_DEMO_NUM_ATTRIBUTES * sizeof(int32) : sizeof(_attributes));
 	return 0;
 }
 
 void IMuse::scriptRefresh() {
 	int soundId;
+	int stopSeqAttr = _demo ? GRIM_DEMO_STOP_SEQ_ATTR : GRIM_STOP_SEQ_ATTR;
 
-	if (_attributes[GRIM_STOP_SEQ_ATTR]) {
+	if (_attributes[stopSeqAttr]) {
 		scriptSetSequence(0);
-		_attributes[GRIM_STOP_SEQ_ATTR] = 0;
+		_attributes[stopSeqAttr] = 0;
 	}
 
 	soundId = imGetNextSound(0);
@@ -114,107 +125,133 @@ void IMuse::scriptRefresh() {
 	imFlushSounds();
 }
 
-void IMuse::scriptSetState(int stateId) {
+// The demo returns the current state/sequence/attribute value from these functions
+int IMuse::scriptSetState(int stateId) {
+	const IMuseStateTable *stateTable = _demo ? _grimDemoStateMusicTable : _grimStateMusicTable;
+	int stateTableSize = _demo ? ARRAYSIZE(_grimDemoStateMusicTable) : ARRAYSIZE(_grimStateMusicTable);
 	int num;
 
 	if (stateId == -1)
-		return;
+		return stateTable[_curMusicState].soundId;
 
-	for (num = 0; num < ARRAYSIZE(_grimStateMusicTable); num++) {
-		if (_grimStateMusicTable[num].soundId == stateId)
+	for (num = 0; num < stateTableSize; num++) {
+		if (stateTable[num].soundId == stateId)
 			break;
 	}
 
-	if (num == ARRAYSIZE(_grimStateMusicTable))
-		return;
+	// (The demo returns the address past the end of the table here)
+	if (num == stateTableSize)
+		return 0;
 
-	debug(5, "IMuse::scriptSetState(): Set music state: %s", _grimStateMusicTable[num].internalName);
+	debug(5, "IMuse::scriptSetState(): Set music state: %s", stateTable[num].internalName);
 
 	if (num != _curMusicState) {
 		if (!_curMusicSeq)
-			scriptPlayMusic(num ? &_grimStateMusicTable[num] : nullptr, num, false);
+			scriptPlayMusic(num ? &stateTable[num] : nullptr, num, false);
 
 		_curMusicState = num;
 	}
+
+	return stateTable[_curMusicState].soundId;
 }
 
-void IMuse::scriptSetSequence(int seqId) {
+int IMuse::scriptSetSequence(int seqId) {
+	const IMuseStateTable *seqTable = _demo ? _grimDemoSeqMusicTable : _grimSeqMusicTable;
+	const IMuseStateTable *stateTable = _demo ? _grimDemoStateMusicTable : _grimStateMusicTable;
+	int seqTableSize = _demo ? ARRAYSIZE(_grimDemoSeqMusicTable) : ARRAYSIZE(_grimSeqMusicTable);
+	int seqOffset = _demo ? GRIM_DEMO_SEQ_OFFSET : GRIM_SEQ_OFFSET;
 	int num;
 
 	if (seqId == -1)
-		return;
+		return seqTable[_curMusicSeq].soundId;
 
 	if (seqId == 0)
 		seqId = 2000;
 
-	for (num = 0; num < ARRAYSIZE(_grimSeqMusicTable); num++) {
-		if (_grimSeqMusicTable[num].soundId == seqId)
+	for (num = 0; num < seqTableSize; num++) {
+		if (seqTable[num].soundId == seqId)
 			break;
 	}
 
-	if (num == ARRAYSIZE(_grimSeqMusicTable)) {
+	if (num == seqTableSize) {
 		debug(5, "IMuse::scriptSetSequence(): bogus sequence");
-		return;
+		return -1;
 	}
 
-	debug(5, "IMuse::scriptSetSequence(): Set music sequence: %s", _grimSeqMusicTable[num].internalName);
+	debug(5, "IMuse::scriptSetSequence(): Set music sequence: %s", seqTable[num].internalName);
 
 	if (num == _curMusicSeq)
-		return;
+		return seqTable[_curMusicSeq].soundId;
 
 	if (num) {
-		if (_curMusicSeq && (_grimSeqMusicTable[_curMusicSeq].transitionId == 4 || _grimSeqMusicTable[_curMusicSeq].transitionId == 6)) {
+		if (_curMusicSeq && (seqTable[_curMusicSeq].transitionId == 4 || seqTable[_curMusicSeq].transitionId == 6)) {
 			_nextSeqToPlay = num;
-			return;
+			return seqTable[_curMusicSeq].soundId;
 		}
 
-		scriptPlayMusic(&_grimSeqMusicTable[num], 0, true);
+		scriptPlayMusic(&seqTable[num], 0, true);
 		_nextSeqToPlay = 0;
-		_attributes[GRIM_SEQ_OFFSET + num] = 1;
+		_attributes[seqOffset + num] = 1;
 		_curMusicSeq = num;
 	} else {
 		if (_nextSeqToPlay) {
-			scriptPlayMusic(&_grimSeqMusicTable[_nextSeqToPlay], 0, true);
+			scriptPlayMusic(&seqTable[_nextSeqToPlay], 0, true);
 			_curMusicSeq = _nextSeqToPlay;
 			_nextSeqToPlay = 0;
-			_attributes[GRIM_SEQ_OFFSET + _curMusicSeq] = 1;
-			return;
+			_attributes[seqOffset + _curMusicSeq] = 1;
+			return seqTable[_curMusicSeq].soundId;
 		}
 
-		scriptPlayMusic(_curMusicState ? &_grimStateMusicTable[_curMusicState] : nullptr, _curMusicState, true);
+		scriptPlayMusic(_curMusicState ? &stateTable[_curMusicState] : nullptr, _curMusicState, true);
 		_curMusicSeq = 0;
 	}
+
+	return seqTable[_curMusicSeq].soundId;
 }
 
 void IMuse::scriptSetCuePoint(int cueId) {
 }
 
 int IMuse::scriptSetAttribute(int attrIndex, int attrVal) {
+	const IMuseStateTable *stateTable = _demo ? _grimDemoStateMusicTable : _grimStateMusicTable;
+	const IMuseStateTable *seqTable = _demo ? _grimDemoSeqMusicTable : _grimSeqMusicTable;
+	int stateTableSize = _demo ? ARRAYSIZE(_grimDemoStateMusicTable) : ARRAYSIZE(_grimStateMusicTable);
+	int seqTableSize = _demo ? ARRAYSIZE(_grimDemoSeqMusicTable) : ARRAYSIZE(_grimSeqMusicTable);
+	int numAttributes = _demo ? GRIM_DEMO_NUM_ATTRIBUTES : ARRAYSIZE(_attributes);
+
 	if (attrIndex == -1) {
 		if (attrVal == 0) {
 			imPause();
 		} else if (attrVal == 1) {
 			imResume();
 		} else if (attrVal == -1) {
-			memset(_attributes, 0, sizeof(_attributes));
+			memset(_attributes, 0, numAttributes * sizeof(int32));
 		}
 	} else if (attrIndex == 10000) {
 		char *dest = (char *)(intptr)attrVal;
 
-		for (int i = 0; i < ARRAYSIZE(_grimStateMusicTable); i++) {
-			memcpy(dest, _grimStateMusicTable[i].name, strlen(_grimStateMusicTable[i].name) + 1);
-			dest += strlen(_grimStateMusicTable[i].name) + 1;
+		for (int i = 0; i < stateTableSize; i++) {
+			memcpy(dest, stateTable[i].name, strlen(stateTable[i].name) + 1);
+			dest += strlen(stateTable[i].name) + 1;
 		}
 
-		for (int i = 0; i < ARRAYSIZE(_grimSeqMusicTable); i++) {
-			memcpy(dest, _grimSeqMusicTable[i].name, strlen(_grimSeqMusicTable[i].name) + 1);
-			dest += strlen(_grimSeqMusicTable[i].name) + 1;
+		for (int i = 0; i < seqTableSize; i++) {
+			memcpy(dest, seqTable[i].name, strlen(seqTable[i].name) + 1);
+			dest += strlen(seqTable[i].name) + 1;
 		}
-	} else if ((uint32)attrIndex >= ARRAYSIZE(_attributes)) {
+
+		if (_demo)
+			return 25;
+	} else if ((uint32)attrIndex >= (uint32)numAttributes) {
 		debug(5, "IMuse::scriptSetAttribute(): bogus attribute");
-	} else if (attrVal != -1) {
-		debug(5, "IMuse::scriptSetAttribute(): Set attr %u to %u", attrIndex, attrVal);
-		_attributes[attrIndex] = attrVal;
+	} else {
+		if (attrVal != -1) {
+			debug(5, "IMuse::scriptSetAttribute(): Set attr %u to %u", attrIndex, attrVal);
+			_attributes[attrIndex] = attrVal;
+		}
+
+		if (_demo)
+			return _attributes[attrIndex];
 	}
 
 	return 0;
@@ -244,7 +281,7 @@ int IMuse::scriptTriggerCallback(char *marker) {
 		debug(5, "IMuse::scriptTriggerCallback(): got marker != '_end', callback ignored");
 		return -1;
 	}
-	_attributes[GRIM_STOP_SEQ_ATTR] = 1;
+	_attributes[_demo ? GRIM_DEMO_STOP_SEQ_ATTR : GRIM_STOP_SEQ_ATTR] = 1;
 	return 0;
 }
 
@@ -256,6 +293,11 @@ void IMuse::scriptPlayMusic(const IMuseStateTable *tableEntry, int curSongEntryI
 
 	Common::StackLock lock(*_mutex);
 
+	if (_demo) {
+		scriptPlayMusicDemo(tableEntry, curSongEntryId, isSequence);
+		return;
+	}
+
 	if (tableEntry) {
 		attribPos = curSongEntryId;
 		if (curSongEntryId) {
@@ -430,4 +472,177 @@ void IMuse::scriptPlayMusic(const IMuseStateTable *tableEntry, int curSongEntryI
 	}
 }
 
+void IMuse::scriptPlayMusicDemo(const IMuseStateTable *tableEntry, int curSongEntryId, int isSequence) {
+	int hookId = 0;
+	int oldSoundId, newSoundId, soundId;
+	int fadeTime, fadeDelay;
+	char fileName[64];
+
+	fileName[0] = '\0';
+	if (tableEntry) {
+		Common::strlcpy(fileName, tableEntry->name, sizeof(fileName));
+		for (int i = 0; i < ARRAYSIZE(_grimDemoMusicFileTable); i++) {
+			if (!strcmp(fileName, _grimDemoMusicFileTable[i].name)) {
+				Common::strlcpy(fileName, _grimDemoMusicFileTable[i].fileName, sizeof(fileName));
+				break;
+			}
+		}
+	}
+
+	if (tableEntry && curSongEntryId) {
+		int attribPos = curSongEntryId;
+		if (tableEntry->attribPos)
+			attribPos = tableEntry->attribPos;
+
+		hookId = _attributes[GRIM_STATE_OFFSET + attribPos];
+
+		if (tableEntry->hookId) {
+			if (hookId || tableEntry->hookId <= 1) {
+				_attributes[GRIM_STATE_OFFSET + attribPos] = hookId + 1;
+				if (hookId + 1 > tableEntry->hookId)
+					_attributes[GRIM_STATE_OFFSET + attribPos] = 1;
+			} else {
+				_attributes[GRIM_STATE_OFFSET + attribPos] = 2;
+			}
+		}
+	}
+
+	// Fade out any music track which is not streamed
+	for (soundId = imGetNextSound(0); soundId; soundId = imGetNextSound(soundId)) {
+		if (imGetParam(soundId, IMUSE_P_GROUP) == IMUSE_GROUP_MUSICEFF && !imGetParam(soundId, IMUSE_P_SND_HAS_STREAM))
+			imFadeParam(soundId, IMUSE_P_VOLUME, 0, 120);
+	}
+
+	oldSoundId = 0;
+	for (soundId = imGetNextSound(0); soundId; soundId = imGetNextSound(soundId)) {
+		if (imGetParam(soundId, IMUSE_P_SND_HAS_STREAM) && imGetParam(soundId, IMUSE_P_STREAM_BUFID) == IMUSE_BUFFER_MUSIC) {
+			oldSoundId = soundId;
+			break;
+		}
+	}
+
+	if (!tableEntry) {
+		if (oldSoundId)
+			imFadeParam(oldSoundId, IMUSE_P_VOLUME, 0, 120);
+		return;
+	}
+
+	switch (tableEntry->transitionId) {
+	case 0:
+		debug(5, "IMuse::scriptPlayMusicDemo(): NULL transition, ignored");
+		break;
+	case 1:
+		debug(5, "IMuse::scriptPlayMusicDemo(): loading %s", fileName);
+		newSoundId = imLoadSound(fileName, 0);
+		if (!newSoundId) {
+			debug(5, "IMuse::scriptPlayMusicDemo(): unable to load %s", fileName);
+			return;
+		}
+
+		if (imStartSound(newSoundId, 126))
+			debug(5, "IMuse::scriptPlayMusicDemo(): failed to start sound %d", newSoundId);
+
+		imSetParam(newSoundId, IMUSE_P_VOLUME, 1);
+		imFadeParam(newSoundId, IMUSE_P_VOLUME, 127, 120);
+		imUnloadSound(newSoundId);
+		imSetParam(newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+		break;
+	case 2:
+	case 3:
+	case 4:
+	case 10:
+	case 11:
+	case 12:
+		debug(5, "IMuse::scriptPlayMusicDemo(): opening %s", fileName);
+		newSoundId = imOpenSound(fileName, 0);
+
+		if (!newSoundId) {
+			debug(5, "IMuse::scriptPlayMusicDemo(): unable to open %s", fileName);
+			if (oldSoundId)
+				imFadeParam(oldSoundId, IMUSE_P_VOLUME, 0, 60);
+			return;
+		}
+
+		if (tableEntry->transitionId == 4) {
+			_attributes[GRIM_DEMO_STOP_SEQ_ATTR] = 0;
+			imSetTrigger(newSoundId, "_end", IMUSE_C_SCRIPT_CALLBACK);
+		}
+
+		fadeTime = tableEntry->fadeTime;
+		fadeDelay = fadeTime ? fadeTime : 1000;
+
+		if (!oldSoundId) {
+			if (imStartStream(newSoundId, 126, IMUSE_BUFFER_MUSIC))
+				debug(5, "IMuse::scriptPlayMusicDemo(): failed to start the stream for sound %d", newSoundId);
+
+			imSetParam(newSoundId, IMUSE_P_VOLUME, tableEntry->volume);
+			imSetParam(newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+			imSetHook(newSoundId, hookId);
+		} else if (tableEntry->transitionId == 2) {
+			imSwitchStream(oldSoundId, newSoundId, fadeDelay, 0, 0);
+			imSetParam(newSoundId, IMUSE_P_VOLUME, tableEntry->volume);
+			imSetParam(newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+			imSetHook(newSoundId, tableEntry->hookId);
+			imProcessStreams();
+		} else if (oldSoundId == newSoundId) {
+			imFadeParam(newSoundId, IMUSE_P_VOLUME, tableEntry->volume, fadeTime);
+			debug(5, "IMuse::scriptPlayMusicDemo(): now VOL=%d", tableEntry->volume);
+		} else if (!isSequence && tableEntry->attribPos && tableEntry->attribPos == _grimDemoStateMusicTable[_curMusicState].attribPos) {
+			imSwitchStream(oldSoundId, newSoundId, fadeDelay, 0, 1);
+			imSetParam(newSoundId, IMUSE_P_VOLUME, tableEntry->volume);
+			imSetParam(newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+			imProcessStreams();
+		} else if (tableEntry->transitionId == 10 || tableEntry->transitionId == 12) {
+			if (tableEntry->transitionId == 12)
+				imSetHook(oldSoundId, tableEntry->hookId);
+
+			imSetTrigger(oldSoundId, "exit", IMUSE_C_SWITCH_STREAM, oldSoundId, newSoundId, fadeDelay, 1, 0);
+			imSetTrigger(oldSoundId, "exit", IMUSE_C_SET_PARAM, newSoundId, IMUSE_P_VOLUME, tableEntry->volume);
+			imSetTrigger(oldSoundId, "exit", IMUSE_C_SET_PARAM, newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+			imSetTrigger(oldSoundId, "exit", IMUSE_C_SET_HOOK, newSoundId, hookId);
+			imProcessStreams();
+		} else if (tableEntry->transitionId == 11) {
+			imSetTrigger(oldSoundId, "exit2", IMUSE_C_SWITCH_STREAM, oldSoundId, newSoundId, fadeDelay, 1, 0);
+			imSetTrigger(oldSoundId, "exit2", IMUSE_C_SET_PARAM, newSoundId, IMUSE_P_VOLUME, tableEntry->volume);
+			imSetTrigger(oldSoundId, "exit2", IMUSE_C_SET_PARAM, newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+			imSetTrigger(oldSoundId, "exit2", IMUSE_C_SET_HOOK, newSoundId, hookId);
+			imProcessStreams();
+		} else {
+			imSwitchStream(oldSoundId, newSoundId, fadeDelay, 0, 0);
+			imSetParam(newSoundId, IMUSE_P_VOLUME, tableEntry->volume);
+			imSetParam(newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+			imSetHook(newSoundId, 9);
+			imProcessStreams();
+		}
+
+		imCloseSound(newSoundId);
+		imSetParam(newSoundId, IMUSE_P_GROUP, IMUSE_GROUP_MUSICEFF);
+		break;
+	case 5:
+		break;
+	case 6:
+		_attributes[GRIM_DEMO_STOP_SEQ_ATTR] = 0;
+		imSetTrigger(IMUSE_SMUSH_SOUNDID + IMUSE_BUFFER_MUSIC, "_end", IMUSE_C_SCRIPT_CALLBACK);
+		break;
+	case 7:
+		if (oldSoundId)
+			imFadeParam(oldSoundId, IMUSE_P_VOLUME, 0, 60);
+		break;
+	case 8:
+		if (oldSoundId)
+			imSetHook(oldSoundId, tableEntry->hookId);
+		break;
+	case 9:
+		if (oldSoundId)
+			imSetHook(oldSoundId, tableEntry->hookId);
+
+		_attributes[GRIM_DEMO_STOP_SEQ_ATTR] = 0;
+		imSetTrigger(oldSoundId, "_end", IMUSE_C_SCRIPT_CALLBACK);
+		break;
+	default:
+		debug(5, "IMuse::scriptPlayMusicDemo(): bogus transition type, ignored");
+		break;
+	}
+}
+
 } // End of namespace Grim
diff --git a/engines/grim/imuse/imuse_tables.cpp b/engines/grim/imuse/imuse_tables.cpp
index cfbd6444edc..f36800d6546 100644
--- a/engines/grim/imuse/imuse_tables.cpp
+++ b/engines/grim/imuse/imuse_tables.cpp
@@ -253,6 +253,53 @@ const IMuseStateTable _grimSeqMusicTable[41] = {
 	{"2399 - End Credits",      2, 2399, "seqEndCredits",        0,  0, 200, 127, 0 }, /* 040 */
 };
 
+// The demo's tables have no pan field
+const IMuseStateTable _grimDemoStateMusicTable[23] = {
+	{"",                        0,    0, "STATE_NULL",           0,  0,   0, 127, 0}, /* 000 */
+	{"",                        0, 1000, "stateNoChange",        0,  0,   0, 127, 0}, /* 001 */
+	{"MO - Manny's Office",     3, 1001, "stateMO",              0,  0,   0, 127, 0}, /* 002 */
+	{"MO - Manny's Office",     3, 1002, "stateHA_INTLS",        0,  0,   0, 127, 0}, /* 003 */
+	{"MO - Manny's Office",     3, 1003, "stateHA",              0,  0,   0, 127, 0}, /* 004 */
+	{"DO - Domino's Office",    3, 1004, "stateDO",              0,  0,   0, 127, 0}, /* 005 */
+	{"CO - Copal's Office",     3, 1005, "stateCO",              0,  0,   0, 127, 0}, /* 006 */
+	{"LE - Ledge",              3, 1010, "stateLE",              0,  0,   0, 127, 0}, /* 007 */
+	{"RF - Roof",               3, 1011, "stateRF",              0,  0,   0, 127, 0}, /* 008 */
+	{"TU - Tube Room",          3, 1020, "stateTU",              0,  0,   0, 127, 0}, /* 009 */
+	{"LO - Lobby",              3, 1021, "stateLO",              0,  0,   0, 127, 0}, /* 010 */
+	{"PK - Packing Room",       3, 1022, "statePK",              0,  0,   0, 127, 0}, /* 011 */
+	{"PK - Packing Room",       3, 1030, "stateGA",              0,  0,   0, 127, 0}, /* 012 */
+	{"PK - Packing Room",       3, 1031, "stateGS",              0,  0,   0, 127, 0}, /* 013 */
+	{"Festival Wet",            3, 1040, "stateAL",              1,  0,  80,  60, 0}, /* 014 */
+	{"Festival Dry",            3, 1041, "stateFE",              1,  0,   0, 127, 0}, /* 015 */
+	{"Festival Dry",            3, 1042, "stateST",              1,  0,  80,  50, 0}, /* 016 */
+	{"Festival Dry",            3, 1043, "stateOS",              1,  0,  80,  64, 0}, /* 017 */
+	{"Festival Wet",            3, 1044, "stateRP",              1,  0,  80,  75, 0}, /* 018 */
+	{"HQ - Headquarters",       3, 1050, "stateHQ",              0,  0,   0, 127, 0}, /* 019 */
+	{"",                        3, 1060, "stateLR",              0,  0,   0, 127, 0}, /* 020 */
+	{"",                        0, 5000, "stateCredits",         0,  0,   0, 127, 0}, /* 021 */
+	{"",                        0,    1, "stateMenu",            0,  0,   0, 127, 0}, /* 022 */
+};
+
+const IMuseStateTable _grimDemoSeqMusicTable[2] = {
+	{"",                        0, 2000, "SEQ_NULL",             0,  0,   0, 127, 0}, /* 000 */
+	{"Rope Climb",              3, 2100, "seqClimbRope",         0,  0,   0, 127, 0}, /* 001 */
+};
+
+const IMuseDemoFileTable _grimDemoMusicFileTable[12] = {
+	{"CO - Copal's Office",  "CO - Copal's Office.IMC"},
+	{"DO - Domino's Office", "DO - Domino's Office.IMC"},
+	{"Festival Dry",         "Festival Dry.IMC"},
+	{"Festival Wet",         "Festival Wet.IMC"},
+	{"HQ - Headquarters",    "HQ - Headquarters.IMC"},
+	{"LE - Ledge",           "LE - Ledge.IMC"},
+	{"LO - Lobby",           "LO - Lobby.IMC"},
+	{"MO - Manny's Office",  "MO - Manny's Office.IMC"},
+	{"PK - Packing Room",    "PK - Packing Room.IMC"},
+	{"RF - Roof",            "RF - Roof.IMC"},
+	{"Rope Climb",           "Rope Climb.IMC"},
+	{"TU - Tube Room",       "TU - Tube Room.IMC"},
+};
+
 // The state table of the previous iMUSE implementation had some entries in a different order, so
 // we have to account for that when reloading older savegames...
 static const struct {
diff --git a/engines/grim/imuse/imuse_tables.h b/engines/grim/imuse/imuse_tables.h
index 94401d243e8..7632b4ce41f 100644
--- a/engines/grim/imuse/imuse_tables.h
+++ b/engines/grim/imuse/imuse_tables.h
@@ -38,8 +38,16 @@ struct IMuseStateTable {
 	int pan;
 };
 
+struct IMuseDemoFileTable {
+	char name[32];
+	char fileName[32];
+};
+
 extern const IMuseStateTable _grimStateMusicTable[181];
 extern const IMuseStateTable _grimSeqMusicTable[41];
+extern const IMuseStateTable _grimDemoStateMusicTable[23];
+extern const IMuseStateTable _grimDemoSeqMusicTable[2];
+extern const IMuseDemoFileTable _grimDemoMusicFileTable[12];
 
 // Sound id of a state, given its position in the table of the old iMUSE
 int grimLegacyStateSoundId(int tableIndex);
diff --git a/engines/grim/imuse/imuse_tracks.cpp b/engines/grim/imuse/imuse_tracks.cpp
index 922b5f44172..c793bd4856f 100644
--- a/engines/grim/imuse/imuse_tracks.cpp
+++ b/engines/grim/imuse/imuse_tracks.cpp
@@ -24,7 +24,7 @@
 namespace Grim {
 
 int IMuse::tracksInit() {
-	_trackCount = IMUSE_MAX_TRACKS;
+	_trackCount = _demo ? 8 : IMUSE_MAX_TRACKS;
 	_tracksPauseTimer = 0;
 	_trackList = nullptr;
 
diff --git a/engines/grim/lua_v1_sound.cpp b/engines/grim/lua_v1_sound.cpp
index 1e1b02960be..6142188f79f 100644
--- a/engines/grim/lua_v1_sound.cpp
+++ b/engines/grim/lua_v1_sound.cpp
@@ -55,7 +55,11 @@ void Lua_V1::ImStartSound() {
 	int priority = (int)lua_getnumber(priorityObj);
 	int group = (int)lua_getnumber(groupObj);
 
-	lua_pushnumber(g_imuse->soundsLoadStartSound(soundName, priority, group));
+	int result = g_imuse->soundsLoadStartSound(soundName, priority, group);
+
+	// The demo doesn't return anything
+	if (!(g_grim->getGameFlags() & ADGF_DEMO))
+		lua_pushnumber(result);
 }
 
 void Lua_V1::ImStopSound() {
@@ -165,7 +169,7 @@ void Lua_V1::ImSetParam() {
 
 	int param = (int)lua_getnumber(paramObj);
 	int value = (int)lua_getnumber(valueObj);
-	if (value < 0)
+	if (value < 0 && !(g_grim->getGameFlags() & ADGF_DEMO))
 		value = 0;
 
 	g_imuse->soundsSetParam(getSoundKey(nameObj), param, value);
@@ -190,8 +194,11 @@ void Lua_V1::ImFadeParam() {
 	lua_Object valueObj = lua_getparam(3);
 	lua_Object durationObj = lua_getparam(4);
 
+	bool demo = g_grim->getGameFlags() & ADGF_DEMO;
+
 	if (!lua_isstring(nameObj) && !lua_isnumber(nameObj)) {
-		lua_pushnumber(0);
+		if (!demo)
+			lua_pushnumber(0);
 		return;
 	}
 	if (!lua_isnumber(opcodeObj) || !lua_isnumber(valueObj) || !lua_isnumber(durationObj))
@@ -199,7 +206,7 @@ void Lua_V1::ImFadeParam() {
 
 	int opcode = (int)lua_getnumber(opcodeObj);
 	int value = (int)lua_getnumber(valueObj);
-	if (value < 0)
+	if (value < 0 && !demo)
 		value = 0;
 	int duration = (int)lua_getnumber(durationObj);
 
@@ -211,6 +218,12 @@ void Lua_V1::ImSetState() {
 	if (!lua_isnumber(stateObj))
 		return;
 
+	// The demo sets the state right away and returns the new one
+	if (g_grim->getGameFlags() & ADGF_DEMO) {
+		lua_pushnumber(g_imuse->imSetState((int)lua_getnumber(stateObj)));
+		return;
+	}
+
 	g_imuseState = (int)lua_getnumber(stateObj);
 }
 
diff --git a/engines/grim/sound.cpp b/engines/grim/sound.cpp
index 4d4e9e0198a..78946bb79d2 100644
--- a/engines/grim/sound.cpp
+++ b/engines/grim/sound.cpp
@@ -33,7 +33,8 @@ SoundPlayer *g_sound = nullptr;
 
 bool SoundPlayer::startVoice(const char *soundName, int volume, int pan, bool background, int *soundId) {
 	if (g_grim->getGameType() == GType_GRIM) {
-		if (background) {
+		// The demo has no background voices
+		if (background && !(g_grim->getGameFlags() & ADGF_DEMO)) {
 			int luaSoundId = g_imuse->soundsLoadProcessStartSound(soundName, 127, IMUSE_GROUP_SPEECH);
 			if (!luaSoundId)
 				return false;


Commit: 369f3f5afb7fd253900db2e62605f25aa68b12cd
    https://github.com/scummvm/scummvm/commit/369f3f5afb7fd253900db2e62605f25aa68b12cd
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: IMUSE: Add support for remastered

Changed paths:
    engines/grim/grim.cpp
    engines/grim/imuse/imuse_defs.h
    engines/grim/imuse/imuse_dispatch.cpp
    engines/grim/imuse/imuse_engine.cpp
    engines/grim/imuse/imuse_engine.h
    engines/grim/imuse/imuse_files.cpp


diff --git a/engines/grim/grim.cpp b/engines/grim/grim.cpp
index 05e7c5a7b0f..c84f3cc2a3e 100644
--- a/engines/grim/grim.cpp
+++ b/engines/grim/grim.cpp
@@ -384,14 +384,16 @@ Common::Error GrimEngine::run() {
 			g_movie = CreateBinkPlayer(demo);
 	}
 	if (getGameType() == GType_GRIM) {
-		int sampleRate = IMUSE_BASE_SAMPLERATE;
-		ConfMan.registerDefault("imuse_sample_rate", IMUSE_BASE_SAMPLERATE);
+		// The remastered works at 48000Hz
+		int baseSampleRate = isRemastered() ? IMUSE_REMASTERED_SAMPLERATE : IMUSE_BASE_SAMPLERATE;
+		int sampleRate = baseSampleRate;
+		ConfMan.registerDefault("imuse_sample_rate", baseSampleRate);
 		if (ConfMan.hasKey("imuse_sample_rate", _targetName)) {
-			// Only accept sample rates which are a multiple or submultiple of 22050
+			// Only accept sample rates which are a multiple or submultiple of the base one
 			int configSampleRate = ConfMan.getInt("imuse_sample_rate");
-			if ((configSampleRate % (IMUSE_BASE_SAMPLERATE / 2)) == 0 &&
-				configSampleRate >= IMUSE_BASE_SAMPLERATE / 2 &&
-				configSampleRate <= IMUSE_BASE_SAMPLERATE * 4) {
+			if ((configSampleRate % (baseSampleRate / 2)) == 0 &&
+				configSampleRate >= baseSampleRate / 2 &&
+				configSampleRate <= baseSampleRate * 4) {
 				sampleRate = configSampleRate;
 			}
 		}
@@ -401,7 +403,7 @@ Common::Error GrimEngine::run() {
 		if (ConfMan.hasKey("imuse_low_latency_mode", _targetName))
 			lowLatencyMode = ConfMan.getBool("imuse_low_latency_mode");
 
-		g_imuse = new IMuse(sampleRate, _mixer, &_imuseMutex, lowLatencyMode, demo);
+		g_imuse = new IMuse(sampleRate, _mixer, &_imuseMutex, lowLatencyMode, demo, isRemastered());
 		g_emiSound = nullptr;
 		if (g_grim->isRemastered()) {
 			// This must happen here, since we need the resource loader set up.
diff --git a/engines/grim/imuse/imuse_defs.h b/engines/grim/imuse/imuse_defs.h
index 617145ed182..6b45cbac792 100644
--- a/engines/grim/imuse/imuse_defs.h
+++ b/engines/grim/imuse/imuse_defs.h
@@ -28,35 +28,39 @@ class SeekableReadStream;
 
 namespace Grim {
 
-#define IMUSE_MAX_GROUPS      16
-#define IMUSE_MAX_FADES       16
-#define IMUSE_MAX_TRIGGERS    8
-#define IMUSE_MAX_DEFERS      8
-#define IMUSE_MAX_TRACKS      9
-#define IMUSE_MAX_MAP_SIZE    512
-#define IMUSE_MAX_DISPATCHES  9
-#define IMUSE_MAX_STREAMZONES 50
-#define IMUSE_MAX_FADE_VOLUME 8323072
-#define IMUSE_MAX_STREAMS     3
-#define IMUSE_MAX_SOUND_LIST  10
-#define IMUSE_MAX_OPEN_FILES  5
-#define IMUSE_MAX_CACHED_SOUNDS 32
+#define IMUSE_MAX_GROUPS          16
+#define IMUSE_MAX_FADES           16
+#define IMUSE_MAX_TRIGGERS        8
+#define IMUSE_MAX_DEFERS          8
+#define IMUSE_MAX_TRACKS          9
+#define IMUSE_MAX_MAP_SIZE        512
+#define IMUSE_MAX_DISPATCHES      9
+#define IMUSE_MAX_STREAMZONES     50
+#define IMUSE_MAX_FADE_VOLUME     8323072
+#define IMUSE_MAX_STREAMS         3
+#define IMUSE_MAX_SOUND_LIST      10
+#define IMUSE_MAX_OPEN_FILES      5
+#define IMUSE_MAX_CACHED_SOUNDS   32
 #define IMUSE_SOUNDS_MEMORY_LIMIT 300000
-#define IMUSE_MAX_LIPSYNCS    4
-#define IMUSE_LIPSYNC_MAX_SIZE 2000
-#define IMUSE_PHONEME_NONE    95
-#define IMUSE_HMI_HEAP_SIZE   150000
-#define IMUSE_HMI_TAIL_SIZE   18000
+#define IMUSE_MAX_LIPSYNCS        4
+#define IMUSE_LIPSYNC_MAX_SIZE    2000
+#define IMUSE_PHONEME_NONE        95
+#define IMUSE_HMI_HEAP_SIZE       150000
+#define IMUSE_HMI_TAIL_SIZE       18000
 
 #define IMUSE_LARGE_FADES    1
 #define IMUSE_SMALL_FADES    2
 #define IMUSE_LARGE_FADE_DIM 100000
 #define IMUSE_SMALL_FADE_DIM 44100
 
-#define IMUSE_BASE_SAMPLERATE 22050
-#define IMUSE_BASE_FEEDSIZE   512
-#define IMUSE_NUM_WAVE_BUFS   8
-#define IMUSE_SMUSH_SOUNDID   12345678
+#define IMUSE_REMASTERED_LARGE_FADE_DIM 200000
+#define IMUSE_REMASTERED_SMALL_FADE_DIM 48000
+
+#define IMUSE_BASE_SAMPLERATE       22050
+#define IMUSE_REMASTERED_SAMPLERATE 48000
+#define IMUSE_BASE_FEEDSIZE         512
+#define IMUSE_NUM_WAVE_BUFS         8
+#define IMUSE_SMUSH_SOUNDID         12345678
 
 enum {
 	kTalkSoundID = 10000
@@ -72,10 +76,11 @@ enum {
 #define IMUSE_BUFFER_MUSIC    2
 #define IMUSE_BUFFER_SFX      3
 
-#define IMUSE_TIMER_BASE_RATE_HZ       50
-#define IMUSE_TIMER_BASE_RATE_USEC     20000  // 1000000 / 50Hz
-#define IMUSE_TIMER_GAIN_RED_RATE_USEC 200000 // 1000000 / 5Hz
-#define IMUSE_TIMER_FADES_RATE_USEC    20000  // 1000000 / 50Hz
+#define IMUSE_TIMER_BASE_RATE_HZ           50
+#define IMUSE_TIMER_BASE_RATE_USEC         20000  // 1000000 / 50Hz
+#define IMUSE_TIMER_GAIN_RED_RATE_USEC     200000 // 1000000 / 5Hz
+#define IMUSE_TIMER_FADES_RATE_USEC        20000  // 1000000 / 50Hz
+#define IMUSE_REMASTERED_TIMER_PERIOD_USEC 16000
 
 // Parameters IDs
 #define IMUSE_P_BOGUS_ID       0x0
diff --git a/engines/grim/imuse/imuse_dispatch.cpp b/engines/grim/imuse/imuse_dispatch.cpp
index e449e4e6780..39907c6a565 100644
--- a/engines/grim/imuse/imuse_dispatch.cpp
+++ b/engines/grim/imuse/imuse_dispatch.cpp
@@ -25,11 +25,14 @@
 namespace Grim {
 
 int IMuse::dispatchInit() {
-	_dispatchBuffer = (uint8 *)malloc(IMUSE_SMALL_FADES * IMUSE_SMALL_FADE_DIM + IMUSE_LARGE_FADE_DIM * IMUSE_LARGE_FADES);
+	int largeFadeDim = _remastered ? IMUSE_REMASTERED_LARGE_FADE_DIM : IMUSE_LARGE_FADE_DIM;
+	int smallFadeDim = _remastered ? IMUSE_REMASTERED_SMALL_FADE_DIM : IMUSE_SMALL_FADE_DIM;
+
+	_dispatchBuffer = (uint8 *)malloc(IMUSE_SMALL_FADES * smallFadeDim + largeFadeDim * IMUSE_LARGE_FADES);
 
 	if (_dispatchBuffer) {
 		_dispatchLargeFadeBufs = _dispatchBuffer;
-		_dispatchSmallFadeBufs = _dispatchBuffer + (IMUSE_LARGE_FADE_DIM * IMUSE_LARGE_FADES);
+		_dispatchSmallFadeBufs = _dispatchBuffer + (largeFadeDim * IMUSE_LARGE_FADES);
 
 		for (int i = 0; i < IMUSE_LARGE_FADES; i++) {
 			_dispatchLargeFadeFlags[i] = 0;
@@ -1246,13 +1249,15 @@ IMuseStreamZone *IMuse::dispatchAllocateStreamZone() {
 }
 
 uint8 *IMuse::dispatchAllocateFade(int32 &fadeSize, const char *function) {
+	int largeFadeDim = _remastered ? IMUSE_REMASTERED_LARGE_FADE_DIM : IMUSE_LARGE_FADE_DIM;
+	int smallFadeDim = _remastered ? IMUSE_REMASTERED_SMALL_FADE_DIM : IMUSE_SMALL_FADE_DIM;
 	uint8 *allocatedFadeBuf = nullptr;
-	if (fadeSize > IMUSE_LARGE_FADE_DIM) {
+	if (fadeSize > largeFadeDim) {
 		debug(5, "IMuse::dispatchAllocateFade(): WARNING: requested fade too large (%d) in %s()", fadeSize, function);
-		fadeSize = IMUSE_LARGE_FADE_DIM;
+		fadeSize = largeFadeDim;
 	}
 
-	if (fadeSize <= IMUSE_SMALL_FADE_DIM) { // Small fade
+	if (fadeSize <= smallFadeDim) { // Small fade
 		for (int i = 0; i <= IMUSE_SMALL_FADES; i++) {
 			if (i == IMUSE_SMALL_FADES) {
 				debug(5, "IMuse::dispatchAllocateFade(): couldn't allocate small fade buffer in %s()", function);
@@ -1262,7 +1267,7 @@ uint8 *IMuse::dispatchAllocateFade(int32 &fadeSize, const char *function) {
 
 			if (!_dispatchSmallFadeFlags[i]) {
 				_dispatchSmallFadeFlags[i] = 1;
-				allocatedFadeBuf = &_dispatchSmallFadeBufs[IMUSE_SMALL_FADE_DIM * i];
+				allocatedFadeBuf = &_dispatchSmallFadeBufs[smallFadeDim * i];
 				break;
 			}
 		}
@@ -1276,14 +1281,14 @@ uint8 *IMuse::dispatchAllocateFade(int32 &fadeSize, const char *function) {
 
 			if (!_dispatchLargeFadeFlags[i]) {
 				_dispatchLargeFadeFlags[i] = 1;
-				allocatedFadeBuf = &_dispatchLargeFadeBufs[IMUSE_LARGE_FADE_DIM * i];
+				allocatedFadeBuf = &_dispatchLargeFadeBufs[largeFadeDim * i];
 				break;
 			}
 		}
 
 		// Fallback to a small fade if large fades are unavailable
 		if (!allocatedFadeBuf) {
-			fadeSize = IMUSE_SMALL_FADE_DIM;
+			fadeSize = smallFadeDim;
 			for (int i = 0; i <= IMUSE_SMALL_FADES; i++) {
 				if (i == IMUSE_SMALL_FADES) {
 					debug(5, "IMuse::dispatchAllocateFade(): couldn't allocate small fade buffer in %s()", function);
@@ -1293,7 +1298,7 @@ uint8 *IMuse::dispatchAllocateFade(int32 &fadeSize, const char *function) {
 
 				if (!_dispatchSmallFadeFlags[i]) {
 					_dispatchSmallFadeFlags[i] = 1;
-					allocatedFadeBuf = &_dispatchSmallFadeBufs[IMUSE_SMALL_FADE_DIM * i];
+					allocatedFadeBuf = &_dispatchSmallFadeBufs[smallFadeDim * i];
 					break;
 				}
 			}
@@ -1306,9 +1311,12 @@ uint8 *IMuse::dispatchAllocateFade(int32 &fadeSize, const char *function) {
 void IMuse::dispatchDeallocateFade(IMuseDispatch *dispatchPtr, const char *function) {
 	// This function flags the fade corresponding to our fadeBuf as unused
 
+	int largeFadeDim = _remastered ? IMUSE_REMASTERED_LARGE_FADE_DIM : IMUSE_LARGE_FADE_DIM;
+	int smallFadeDim = _remastered ? IMUSE_REMASTERED_SMALL_FADE_DIM : IMUSE_SMALL_FADE_DIM;
+
 	// First, check if our fade buffer is one of the large fade buffers
 	for (int i = 0; i < IMUSE_LARGE_FADES; i++) {
-		if (_dispatchLargeFadeBufs + (IMUSE_LARGE_FADE_DIM * i) == dispatchPtr->fadeBuf) { // Found it!
+		if (_dispatchLargeFadeBufs + (largeFadeDim * i) == dispatchPtr->fadeBuf) { // Found it!
 			if (_dispatchLargeFadeFlags[i] == 0) {
 				debug(5, "IMuse::dispatchDeallocateFade(): redundant large fade buf de-allocation in %s()", function);
 			}
@@ -1319,7 +1327,7 @@ void IMuse::dispatchDeallocateFade(IMuseDispatch *dispatchPtr, const char *funct
 
 	// If not, check between the small fade buffers
 	for (int j = 0; j < IMUSE_SMALL_FADES; j++) {
-		if (_dispatchSmallFadeBufs + (IMUSE_SMALL_FADE_DIM * j) == dispatchPtr->fadeBuf) { // Found it!
+		if (_dispatchSmallFadeBufs + (smallFadeDim * j) == dispatchPtr->fadeBuf) { // Found it!
 			if (_dispatchSmallFadeFlags[j] == 0) {
 				debug(5, "IMuse::dispatchDeallocateFade(): redundant small fade buf de-allocation in %s()", function);
 			}
diff --git a/engines/grim/imuse/imuse_engine.cpp b/engines/grim/imuse/imuse_engine.cpp
index 67f022f87ad..701c398c072 100644
--- a/engines/grim/imuse/imuse_engine.cpp
+++ b/engines/grim/imuse/imuse_engine.cpp
@@ -42,11 +42,12 @@ void IMuse::timer_handler(void *refCon) {
 	imuse->imHeartbeat();
 }
 
-IMuse::IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode, bool demo)
+IMuse::IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode, bool demo, bool remastered)
 	: _mixer(mixer), _mutex(mutex) {
 	assert(mixer);
 
 	_demo = demo;
+	_remastered = remastered;
 
 	// 50 Hz rate for the callback
 	_callbackFps = IMUSE_TIMER_BASE_RATE_HZ;
@@ -115,7 +116,9 @@ IMuse::IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool low
 	_voiceRemainderSize = 0;
 	_voiceRemainderCapacity = 0;
 	_voiceRemainderPos = 0;
-	setupHMI(IMUSE_HMI_HEAP_SIZE);
+	// The remastered has no HMI effects
+	if (!_remastered)
+		setupHMI(IMUSE_HMI_HEAP_SIZE);
 
 	imInitialize();
 	if (_demo) {
@@ -153,7 +156,9 @@ IMuse::IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool low
 	_nominalBufferCount = _maxQueuedStreams;
 	_underrunCooldown = _maxQueuedStreams;
 
-	g_system->getTimerManager()->installTimerProc(timer_handler, 1000000 / _callbackFps, this, "IMuse");
+	// The remastered calls the heartbeat every 16 ms, but its counters still advance by 20 ms each time
+	int timerPeriodUsec = _remastered ? IMUSE_REMASTERED_TIMER_PERIOD_USEC : 1000000 / _callbackFps;
+	g_system->getTimerManager()->installTimerProc(timer_handler, timerPeriodUsec, this, "IMuse");
 }
 
 IMuse::~IMuse() {
diff --git a/engines/grim/imuse/imuse_engine.h b/engines/grim/imuse/imuse_engine.h
index 48fbda4be23..f9b362b054e 100644
--- a/engines/grim/imuse/imuse_engine.h
+++ b/engines/grim/imuse/imuse_engine.h
@@ -88,6 +88,7 @@ private:
 	int _curMixerMusicVolume, _curMixerSpeechVolume, _curMixerSFXVolume;
 
 	bool _demo;
+	bool _remastered;
 
 	int32 _attributes[228];	// internal attributes for each music file to store and check later
 	int32 _nextSeqToPlay;
@@ -339,7 +340,7 @@ private:
 	uint8 *_waveOutLowLatencyOutputBuffer;
 
 public:
-	IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode = false, bool demo = false);
+	IMuse(int sampleRate, Audio::Mixer *mixer, Common::Mutex *mutex, bool lowLatencyMode = false, bool demo = false, bool remastered = false);
 	~IMuse();
 
 	// Wrapper functions used by the main engine
diff --git a/engines/grim/imuse/imuse_files.cpp b/engines/grim/imuse/imuse_files.cpp
index 690bcbee8c2..b78af1f6830 100644
--- a/engines/grim/imuse/imuse_files.cpp
+++ b/engines/grim/imuse/imuse_files.cpp
@@ -1527,7 +1527,12 @@ int IMuse::soundsRegisterVoice(const char *filename) {
 	soundsFileSeek(res, 0, SEEK_END);
 	int dataSamplesInFile = soundsFileTell(res) - 44;
 	soundsFileSeek(res, 0, SEEK_SET);
-	_millisecsInCurSpeechFile = 10 * dataSamplesInFile / 441;
+
+	if (_remastered)
+		_millisecsInCurSpeechFile = 10 * dataSamplesInFile / 480;
+	else
+		_millisecsInCurSpeechFile = 10 * dataSamplesInFile / 441;
+
 	return 1;
 }
 
@@ -1542,7 +1547,9 @@ void IMuse::soundsCloseVoiceFile() {
 
 void IMuse::soundsReOpenVoiceFile() {
 	soundsCloseVoiceFile();
-	if (_curSpeechFile[0])
+
+	// The remastered checks the address of the name, which is always true
+	if (_remastered || _curSpeechFile[0])
 		soundsRegisterVoice(_curSpeechFile);
 }
 
@@ -1576,6 +1583,14 @@ int IMuse::loadLip(const char *lipsyncFilename, int soundId) {
 	lowerName.toLowercase();
 
 	Common::SeekableReadStream *lipsyncFile = g_resourceloader->openNewStreamFile(lowerName.c_str());
+
+	// The remastered falls back on the english file if the one with the language prefix doesn't exist
+	if (!lipsyncFile && _remastered && lowerName.size() >= 3 && lowerName[2] == '_') {
+		lowerName.setChar('e', 0);
+		lowerName.setChar('n', 1);
+		lipsyncFile = g_resourceloader->openNewStreamFile(lowerName.c_str());
+	}
+
 	if (!lipsyncFile) {
 		soundsResetLipsyncState(soundId);
 		return 0;


Commit: bcc06b7299d772d810d83ac3f459227866267153
    https://github.com/scummvm/scummvm/commit/bcc06b7299d772d810d83ac3f459227866267153
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: Remove mistakenly added opcodes

These do not appear in the LUA scripts for any
of the versions...

Changed paths:
    engines/grim/lua_v1.cpp
    engines/grim/lua_v1.h
    engines/grim/lua_v1_sound.cpp


diff --git a/engines/grim/lua_v1.cpp b/engines/grim/lua_v1.cpp
index b9ec13e4053..24af3a32a01 100644
--- a/engines/grim/lua_v1.cpp
+++ b/engines/grim/lua_v1.cpp
@@ -948,20 +948,9 @@ struct luaL_reg grimMainOpcodes[] = {
 	{ "ImSetMusicVol", LUA_OPCODE(Lua_V1, ImSetMusicVol) },
 	{ "ImSetState", LUA_OPCODE(Lua_V1, ImSetState) },
 	{ "ImSetSequence", LUA_OPCODE(Lua_V1, ImSetSequence) },
-	{ "ImSetAttribute", LUA_OPCODE(Lua_V1, ImSetAttribute) },
-	{ "ImSetCuePoint", LUA_OPCODE(Lua_V1, ImSetCuePoint) },
 	{ "ImPause", LUA_OPCODE(Lua_V1, ImPause) },
 	{ "ImResume", LUA_OPCODE(Lua_V1, ImResume) },
 	{ "ImSetVoiceEffect", LUA_OPCODE(Lua_V1, ImSetVoiceEffect) },
-	{ "ImStartVoice", LUA_OPCODE(Lua_V1, ImStartVoice) },
-	{ "ImStopVoice", LUA_OPCODE(Lua_V1, ImStopVoice) },
-	{ "ImGetMemoryFootprint", LUA_OPCODE(Lua_V1, ImGetMemoryFootprint) },
-	{ "ImGetSoundCacheSize", LUA_OPCODE(Lua_V1, ImGetSoundCacheSize) },
-	{ "ImSetMasterVol", LUA_OPCODE(Lua_V1, ImSetMasterVol) },
-	{ "ImGetMasterVol", LUA_OPCODE(Lua_V1, ImGetMasterVol) },
-	{ "play", LUA_OPCODE(Lua_V1, ImStartSound) },
-	{ "quiet", LUA_OPCODE(Lua_V1, ImStopAllSounds) },
-	{ "vfx", LUA_OPCODE(Lua_V1, ImSetVoiceEffect) },
 	{ "LoadBundle", LUA_OPCODE(Lua_V1, LoadBundle) },
 	{ "SetGamma", LUA_OPCODE(Lua_V1, SetGamma) },
 	{ "SetActorWalkDominate", LUA_OPCODE(Lua_V1, SetActorWalkDominate) },
diff --git a/engines/grim/lua_v1.h b/engines/grim/lua_v1.h
index 10adb5ab771..e4d89b88070 100644
--- a/engines/grim/lua_v1.h
+++ b/engines/grim/lua_v1.h
@@ -164,12 +164,6 @@ protected:
 	DECLARE_LUA_OPCODE(ImPause);
 	DECLARE_LUA_OPCODE(ImResume);
 	DECLARE_LUA_OPCODE(ImSetVoiceEffect);
-	DECLARE_LUA_OPCODE(ImStartVoice);
-	DECLARE_LUA_OPCODE(ImStopVoice);
-	DECLARE_LUA_OPCODE(ImGetMemoryFootprint);
-	DECLARE_LUA_OPCODE(ImGetSoundCacheSize);
-	DECLARE_LUA_OPCODE(ImSetMasterVol);
-	DECLARE_LUA_OPCODE(ImGetMasterVol);
 	DECLARE_LUA_OPCODE(ImSetMusicVol);
 	DECLARE_LUA_OPCODE(ImGetMusicVol);
 	DECLARE_LUA_OPCODE(ImSetVoiceVol);
@@ -181,8 +175,6 @@ protected:
 	DECLARE_LUA_OPCODE(ImFadeParam);
 	DECLARE_LUA_OPCODE(ImSetState);
 	DECLARE_LUA_OPCODE(ImSetSequence);
-	DECLARE_LUA_OPCODE(ImSetAttribute);
-	DECLARE_LUA_OPCODE(ImSetCuePoint);
 	DECLARE_LUA_OPCODE(SaveIMuse);
 	DECLARE_LUA_OPCODE(RestoreIMuse);
 	DECLARE_LUA_OPCODE(SetSoundPosition);
diff --git a/engines/grim/lua_v1_sound.cpp b/engines/grim/lua_v1_sound.cpp
index 6142188f79f..13df4ba05c5 100644
--- a/engines/grim/lua_v1_sound.cpp
+++ b/engines/grim/lua_v1_sound.cpp
@@ -86,44 +86,6 @@ void Lua_V1::ImSetVoiceEffect() {
 	g_imuse->iMUSESetVoiceEffect(effectName);
 }
 
-void Lua_V1::ImStartVoice() {
-	lua_Object nameObj = lua_getparam(1);
-	lua_Object volObj = lua_getparam(2);
-	lua_Object panObj = lua_getparam(3);
-
-	// The original accepts nil too, but it would crash in iMUSE
-	if (!lua_isstring(nameObj))
-		return;
-
-	if (!lua_isnumber(volObj) || !lua_isnumber(panObj))
-		return;
-
-	g_imuse->soundStartVoiceStream(lua_getstring(nameObj), (int)lua_getnumber(volObj), (int)lua_getnumber(panObj));
-}
-
-void Lua_V1::ImStopVoice() {
-	g_imuse->soundStopVoiceStream();
-}
-
-void Lua_V1::ImGetMemoryFootprint() {
-	lua_pushnumber(g_imuse->iMUSEGetMemoryFootprint());
-}
-
-void Lua_V1::ImGetSoundCacheSize() {
-	lua_pushnumber(g_imuse->iMUSEGetSoundCacheSize());
-}
-
-void Lua_V1::ImSetMasterVol() {
-	lua_Object volObj = lua_getparam(1);
-	if (!lua_isnumber(volObj))
-		return;
-	g_imuse->imSetGroupVol(IMUSE_GROUP_MASTER, (int)lua_getnumber(volObj));
-}
-
-void Lua_V1::ImGetMasterVol() {
-	lua_pushnumber(g_imuse->imSetGroupVol(IMUSE_GROUP_MASTER, -1));
-}
-
 void Lua_V1::ImSetMusicVol() {
 	lua_Object volObj = lua_getparam(1);
 	if (!lua_isnumber(volObj))
@@ -236,25 +198,6 @@ void Lua_V1::ImSetSequence() {
 	lua_pushnumber(g_imuse->imSetSequence(state));
 }
 
-void Lua_V1::ImSetAttribute() {
-	lua_Object attrIndexObj = lua_getparam(1);
-	lua_Object attrValObj = lua_getparam(2);
-	if (!lua_isnumber(attrIndexObj) || !lua_isnumber(attrValObj))
-		return;
-
-	int attrIndex = (int)lua_getnumber(attrIndexObj);
-	int attrVal = (int)lua_getnumber(attrValObj);
-	lua_pushnumber(g_imuse->imSetAttribute(attrIndex, attrVal));
-}
-
-void Lua_V1::ImSetCuePoint() {
-	lua_Object cueObj = lua_getparam(1);
-	if (!lua_isnumber(cueObj))
-		return;
-
-	g_imuse->imSetCuePoint((int)lua_getnumber(cueObj));
-}
-
 void Lua_V1::SaveIMuse() {
 	SaveGame *savedIMuse = SaveGame::openForSaving("grim.tmp");
 	if (!savedIMuse)


Commit: ba528657de0c7e6859f7a41291251125255a8b80
    https://github.com/scummvm/scummvm/commit/ba528657de0c7e6859f7a41291251125255a8b80
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-10-31T20:02:21+01:00

Commit Message:
GRIM: Remove mistakenly added opcodes pt.2

Changed paths:
    engines/grim/actor.cpp
    engines/grim/actor.h
    engines/grim/lua_v1.cpp
    engines/grim/lua_v1.h
    engines/grim/lua_v1_actor.cpp
    engines/grim/lua_v1_sound.cpp


diff --git a/engines/grim/actor.cpp b/engines/grim/actor.cpp
index 4ead2c187f8..a9b764aa67f 100644
--- a/engines/grim/actor.cpp
+++ b/engines/grim/actor.cpp
@@ -93,7 +93,7 @@ Actor::Actor() :
 		_globalAlpha(1.f), _alphaMode(AlphaOff),
 		 _mustPlaceText(false),
 		_puckOrient(false), _talking(false),
-		_inOverworld(false), _drawnToClean(false), _backgroundTalk(false), _voiceIs3D(false), _talkSoundId(0),
+		_inOverworld(false), _drawnToClean(false), _backgroundTalk(false), _talkSoundId(0),
 		_sortOrder(0), _useParentSortOrder(false),
 		_sectorSortOrder(0), _hasSectorSortOrder(false), _fakeUnbound(false), _lightMode(LightFastDyn),
 		_hasFollowedBoxes(false), _lookAtActor(0) {
@@ -146,7 +146,6 @@ void Actor::saveState(SaveGame *savedState) const {
 	savedState->writeString(_talkSoundName);
 	savedState->writeBool(_talking);
 	savedState->writeBool(_backgroundTalk);
-	savedState->writeBool(_voiceIs3D);
 	savedState->writeLESint32(_talkSoundId);
 
 	savedState->writeLEUint32((uint32)_collisionMode);
@@ -306,10 +305,8 @@ bool Actor::restoreState(SaveGame *savedState) {
 	_talkSoundName      = savedState->readString();
 	_talking = savedState->readBool();
 	_backgroundTalk = savedState->readBool();
-	if (savedState->saveMinorVersion() >= 30) {
-		_voiceIs3D = savedState->readBool();
+	if (savedState->saveMinorVersion() >= 30)
 		_talkSoundId = savedState->readLESint32();
-	}
 
 	if (isTalking()) {
 		g_grim->addTalkingActor(this);
@@ -1196,18 +1193,9 @@ void Actor::sayLine(const char *msgId, bool background, float x, float y) {
 	bool started = false;
 	_talkSoundId = 0;
 
-	if (g_grim->getSpeechMode() != GrimEngine::TextOnly) {
+	if (g_grim->getSpeechMode() != GrimEngine::TextOnly)
 		started = g_sound->startVoice(_talkSoundName.c_str(), 127, 64, background, &_talkSoundId);
 
-		// The voice can be positioned in the set, like the original does
-		if (started && _voiceIs3D && currSet && g_grim->getGameType() == GType_GRIM) {
-			if (background)
-				currSet->setSoundPosition(_talkSoundName.c_str(), getPos(), 20, 127, kSoundDefaultMaxDist, kSoundDefaultRadius);
-			else
-				currSet->setSoundPosition(kTalkSoundID, getPos(), 20, 127, kSoundDefaultMaxDist, kSoundDefaultRadius);
-		}
-	}
-
 	// If the actor is clearly not visible then don't try to play the lip sync
 	if (_visible && (!g_movie->isPlaying() || g_grim->getMode() == GrimEngine::NormalMode)) {
 		Common::String soundLip = id;
diff --git a/engines/grim/actor.h b/engines/grim/actor.h
index 7abd1f65202..37c93795c88 100644
--- a/engines/grim/actor.h
+++ b/engines/grim/actor.h
@@ -134,7 +134,6 @@ public:
 	 * @see getTalkColor
 	 */
 	void setTalkColor(const Color &color) { _talkColor = color; }
-	void setVoiceIs3D(bool is3D) { _voiceIs3D = is3D; }
 	/**
 	 * Returns the color of the subtitles of the actor.
 	 *
@@ -615,7 +614,6 @@ private:
 	Common::String _talkSoundName;
 	bool _talking;
 	bool _backgroundTalk;
-	bool _voiceIs3D;
 	int _talkSoundId;
 	ObjectPtr<LipSync> _lipSync;
 	Common::List<Costume *> _costumeStack;
diff --git a/engines/grim/lua_v1.cpp b/engines/grim/lua_v1.cpp
index 24af3a32a01..8b80aa1f47e 100644
--- a/engines/grim/lua_v1.cpp
+++ b/engines/grim/lua_v1.cpp
@@ -896,9 +896,6 @@ struct luaL_reg grimMainOpcodes[] = {
 	{ "PlaySoundAt", LUA_OPCODE(Lua_V1, PlaySoundAt) },
 	{ "IsSoundPlaying", LUA_OPCODE(Lua_V1, IsSoundPlaying) },
 	{ "SetSoundPosition", LUA_OPCODE(Lua_V1, SetSoundPosition) },
-	{ "SetSoundParameters", LUA_OPCODE(Lua_V1, SetSoundParameters) },
-	{ "GetSoundParameters", LUA_OPCODE(Lua_V1, GetSoundParameters) },
-	{ "ActorVoiceIs3D", LUA_OPCODE(Lua_V1, ActorVoiceIs3D) },
 	{ "FileFindFirst", LUA_OPCODE(Lua_V1, FileFindFirst) },
 	{ "FileFindNext", LUA_OPCODE(Lua_V1, FileFindNext) },
 	{ "FileFindDispose", LUA_OPCODE(Lua_V1, FileFindDispose) },
diff --git a/engines/grim/lua_v1.h b/engines/grim/lua_v1.h
index e4d89b88070..5524be0fc32 100644
--- a/engines/grim/lua_v1.h
+++ b/engines/grim/lua_v1.h
@@ -178,9 +178,6 @@ protected:
 	DECLARE_LUA_OPCODE(SaveIMuse);
 	DECLARE_LUA_OPCODE(RestoreIMuse);
 	DECLARE_LUA_OPCODE(SetSoundPosition);
-	DECLARE_LUA_OPCODE(SetSoundParameters);
-	DECLARE_LUA_OPCODE(GetSoundParameters);
-	DECLARE_LUA_OPCODE(ActorVoiceIs3D);
 	DECLARE_LUA_OPCODE(IsSoundPlaying);
 	DECLARE_LUA_OPCODE(PlaySoundAt);
 	DECLARE_LUA_OPCODE(FileFindDispose);
diff --git a/engines/grim/lua_v1_actor.cpp b/engines/grim/lua_v1_actor.cpp
index c20e4bb8856..e7a045ab678 100644
--- a/engines/grim/lua_v1_actor.cpp
+++ b/engines/grim/lua_v1_actor.cpp
@@ -82,17 +82,6 @@ void Lua_V1::SetActorTalkColor() {
 	actor->setTalkColor(getcolor(colorObj));
 }
 
-void Lua_V1::ActorVoiceIs3D() {
-	lua_Object actorObj = lua_getparam(1);
-	lua_Object is3DObj = lua_getparam(2);
-
-	if (!lua_isuserdata(actorObj) || lua_tag(actorObj) != MKTAG('A','C','T','R'))
-		return;
-
-	Actor *actor = getactor(actorObj);
-	actor->setVoiceIs3D(!lua_isnil(is3DObj));
-}
-
 void Lua_V1::GetActorTalkColor() {
 	lua_Object actorObj = lua_getparam(1);
 	if (!lua_isuserdata(actorObj) || lua_tag(actorObj) != MKTAG('A','C','T','R')) {
diff --git a/engines/grim/lua_v1_sound.cpp b/engines/grim/lua_v1_sound.cpp
index 13df4ba05c5..26456457e84 100644
--- a/engines/grim/lua_v1_sound.cpp
+++ b/engines/grim/lua_v1_sound.cpp
@@ -275,62 +275,6 @@ void Lua_V1::SetSoundPosition() {
 	}
 }
 
-void Lua_V1::SetSoundParameters() {
-	lua_Object maxDistObj = lua_getparam(1);
-	lua_Object minVolObj = lua_getparam(2);
-	lua_Object maxVolObj = lua_getparam(3);
-	lua_Object panFactorObj = lua_getparam(4);
-	lua_Object maxRadiusObj = lua_getparam(5);
-
-	Set *currSet = g_grim->getCurrSet();
-	if (!currSet) {
-		warning("SetSoundParameters: No current room!");
-		return;
-	}
-
-	if (lua_isnil(maxDistObj) && lua_isnil(minVolObj) && lua_isnil(maxVolObj) &&
-		lua_isnil(panFactorObj) && lua_isnil(maxRadiusObj)) {
-		// Reset all parameters
-		currSet->setSoundParameters();
-		return;
-	}
-
-	// The current values are kept for the parameters which aren't specified
-	float maxDist, panFactor, maxRadius;
-	int minVol, maxVol;
-	currSet->getSoundParameters(&maxDist, &minVol, &maxVol, &panFactor, &maxRadius);
-
-	if (!lua_isnil(maxDistObj))
-		maxDist = lua_getnumber(maxDistObj);
-	// The volumes are bytes in the original
-	if (!lua_isnil(minVolObj))
-		minVol = (uint8)(int)lua_getnumber(minVolObj);
-	if (!lua_isnil(maxVolObj))
-		maxVol = (uint8)(int)lua_getnumber(maxVolObj);
-	if (!lua_isnil(panFactorObj))
-		panFactor = lua_getnumber(panFactorObj);
-	if (!lua_isnil(maxRadiusObj))
-		maxRadius = lua_getnumber(maxRadiusObj);
-
-	currSet->setSoundParameters(maxDist, minVol, maxVol, panFactor, maxRadius);
-}
-
-void Lua_V1::GetSoundParameters() {
-	Set *currSet = g_grim->getCurrSet();
-	if (!currSet)
-		return;
-
-	float maxDist, panFactor, maxRadius;
-	int minVol, maxVol;
-	currSet->getSoundParameters(&maxDist, &minVol, &maxVol, &panFactor, &maxRadius);
-
-	lua_pushnumber(maxDist);
-	lua_pushnumber(minVol);
-	lua_pushnumber(maxVol);
-	lua_pushnumber(panFactor);
-	lua_pushnumber(maxRadius);
-}
-
 void Lua_V1::IsSoundPlaying() {
 	// dummy
 }




More information about the Scummvm-git-logs mailing list