GOB: Rewrite the AdLib players

This is a complete rewrite of the AdLib players for ADL and MDY/TBR
files in the Gob engine.

Major changes
1) The AdLib base class is now completely separated from all file
   format code and can theoretically be used by any OPL2-based
   format (within reason)
2) The new code is far better documented and more readable
3) The MDY player now actually works. The MDY/TBR format is
   in reality the MUS/SND format created by AdLib as a simpler
   alternative to the ROL format
4) Since the MAME emulator is quite buggy and leads to noticable
   wrong percussion in the Gobliins 2 title music, the new AdLib
   player will try to create a DOSBox OPL. If it's not compiled in,
   or if the user configured opl_driver to "mame", it will print
   out appropriate warnings.
This commit is contained in:
Sven Hesse 2012-06-09 10:38:55 +02:00
parent 49fafb48a7
commit 03ef6689c0
9 changed files with 1596 additions and 763 deletions

View file

@ -103,6 +103,8 @@ MODULE_OBJS := \
sound/sounddesc.o \
sound/pcspeaker.o \
sound/adlib.o \
sound/musplayer.o \
sound/adlplayer.o \
sound/infogrames.o \
sound/protracker.o \
sound/soundmixer.o \

File diff suppressed because it is too large Load diff

View file

@ -20,154 +20,287 @@
*
*/
#ifndef GOB_SOUND_ADLIB_H
#define GOB_SOUND_ADLIB_H
#ifndef GOB_SOUND_NEWADLIB_H
#define GOB_SOUND_NEWADLIB_H
#include "common/mutex.h"
#include "audio/audiostream.h"
#include "audio/mixer.h"
#include "audio/fmopl.h"
namespace OPL {
class OPL;
}
namespace Gob {
class GobEngine;
/** Base class for a player of an AdLib music format. */
class AdLib : public Audio::AudioStream {
public:
AdLib(Audio::Mixer &mixer);
virtual ~AdLib();
bool isPlaying() const;
int getIndex() const;
bool getRepeating() const;
bool isPlaying() const; ///< Are we currently playing?
int32 getRepeating() const; ///< Return number of times left to loop.
/** Set the loop counter.
*
* @param repCount Number of times to loop (i.e. number of additional
* paythroughs to the first one, not overall).
* A negative value means infinite looping.
*/
void setRepeating(int32 repCount);
void startPlay();
void stopPlay();
virtual void unload();
// AudioStream API
int readBuffer(int16 *buffer, const int numSamples);
bool isStereo() const { return false; }
bool endOfData() const { return !_playing; }
bool endOfStream() const { return false; }
int getRate() const { return _rate; }
bool isStereo() const;
bool endOfData() const;
bool endOfStream() const;
int getRate() const;
protected:
static const unsigned char _operators[];
static const unsigned char _volRegNums [];
enum kVoice {
kVoiceMelody0 = 0,
kVoiceMelody1 = 1,
kVoiceMelody2 = 2,
kVoiceMelody3 = 3,
kVoiceMelody4 = 4,
kVoiceMelody5 = 5,
kVoiceMelody6 = 6, // Only available in melody mode.
kVoiceMelody7 = 7, // Only available in melody mode.
kVoiceMelody8 = 8, // Only available in melody mode.
kVoiceBaseDrum = 6, // Only available in percussion mode.
kVoiceSnareDrum = 7, // Only available in percussion mode.
kVoiceTom = 8, // Only available in percussion mode.
kVoiceCymbal = 9, // Only available in percussion mode.
kVoiceHihat = 10 // Only available in percussion mode.
};
/** Operator parameters. */
enum kParam {
kParamKeyScaleLevel = 0,
kParamFreqMulti = 1,
kParamFeedback = 2,
kParamAttack = 3,
kParamSustain = 4,
kParamSustaining = 5,
kParamDecay = 6,
kParamRelease = 7,
kParamLevel = 8,
kParamAM = 9,
kParamVib = 10,
kParamKeyScaleRate = 11,
kParamFM = 12,
kParamWaveSelect = 13
};
static const int kOperatorCount = 18; ///< Number of operators.
static const int kParamCount = 14; ///< Number of operator parameters.
static const int kPitchStepCount = 25; ///< Number of pitch bend steps in a half tone.
static const int kOctaveCount = 8; ///< Number of octaves we can play.
static const int kHalfToneCount = 12; ///< Number of half tones in an octave.
static const int kOperatorsPerVoice = 2; ///< Number of operators per voice.
static const int kMelodyVoiceCount = 9; ///< Number of melody voices.
static const int kPercussionVoiceCount = 5; ///< Number of percussion voices.
static const int kMaxVoiceCount = 11; ///< Max number of voices.
/** Number of notes we can play. */
static const int kNoteCount = kHalfToneCount * kOctaveCount;
static const int kMaxVolume = 0x007F;
static const int kMaxPitch = 0x3FFF;
static const int kMidPitch = 0x2000;
static const int kStandardMidC = 60; ///< A mid C in standard MIDI.
static const int kOPLMidC = 48; ///< A mid C for the OPL.
/** Return the number of samples per second. */
uint32 getSamplesPerSecond() const;
/** Write a value into an OPL register. */
void writeOPL(byte reg, byte val);
/** Signal that the playback ended.
*
* @param killRepeat Explicitly request that the song is not to be looped.
*/
void end(bool killRepeat = false);
/** The callback function that's called for polling more AdLib commands.
*
* @param first Is this the first poll since the start of the song?
* @return The number of samples until the next poll.
*/
virtual uint32 pollMusic(bool first) = 0;
/** Rewind the song. */
virtual void rewind() = 0;
/** Return whether we're in percussion mode. */
bool isPercussionMode() const;
/** Set percussion or melody mode. */
void setPercussionMode(bool percussion);
/** Enable/Disable the wave select operator parameters.
*
* When disabled, all operators use the sine wave, regardless of the parameter.
*/
void enableWaveSelect(bool enable);
/** Change the pitch bend range.
*
* @param range The range in half tones from 1 to 12 inclusive.
* See bendVoicePitch() for how this works in practice.
*/
void setPitchRange(uint8 range);
/** Set the tremolo (amplitude vibrato) depth.
*
* @param tremoloDepth false: 1.0dB, true: 4.8dB.
*/
void setTremoloDepth(bool tremoloDepth);
/** Set the frequency vibrato depth.
*
* @param vibratoDepth false: 7 cent, true: 14 cent. 1 cent = 1/100 half tone.
*/
void setVibratoDepth(bool vibratoDepth);
/** Set the keyboard split point. */
void setKeySplit(bool keySplit);
/** Set the timbre of a voice.
*
* Layout of the operator parameters is as follows:
* - First 13 parameter for the first operator
* - First 13 parameter for the second operator
* - 14th parameter (wave select) for the first operator
* - 14th parameter (wave select) for the second operator
*/
void setVoiceTimbre(uint8 voice, const uint16 *params);
/** Set a voice's volume. */
void setVoiceVolume(uint8 voice, uint8 volume);
/** Bend a voice's pitch.
*
* The pitchBend parameter is a value between 0 (full down) and kMaxPitch (full up).
* The actual frequency depends on the pitch range set previously by setPitchRange(),
* with full down being -range half tones and full up range half tones.
*/
void bendVoicePitch(uint8 voice, uint16 pitchBend);
/** Switch a voice on.
*
* Plays one of the kNoteCount notes. However, the valid range of a note is between
* 0 and 127, of which only 12 to 107 are audible.
*/
void noteOn(uint8 voice, uint8 note);
/** Switch a voice off. */
void noteOff(uint8 voice);
private:
static const uint8 kOperatorType [kOperatorCount];
static const uint8 kOperatorOffset[kOperatorCount];
static const uint8 kOperatorVoice [kOperatorCount];
static const uint8 kVoiceMelodyOperator [kOperatorsPerVoice][kMelodyVoiceCount];
static const uint8 kVoicePercussionOperator[kOperatorsPerVoice][kPercussionVoiceCount];
static const byte kPercussionMasks[kPercussionVoiceCount];
static const uint16 kPianoParams [kOperatorsPerVoice][kParamCount];
static const uint16 kBaseDrumParams [kOperatorsPerVoice][kParamCount];
static const uint16 kSnareDrumParams[kParamCount];
static const uint16 kTomParams [kParamCount];
static const uint16 kCymbalParams [kParamCount];
static const uint16 kHihatParams [kParamCount];
Audio::Mixer *_mixer;
Audio::SoundHandle _handle;
FM_OPL *_opl;
OPL::OPL *_opl;
Common::Mutex _mutex;
uint32 _rate;
byte *_data;
byte *_playPos;
uint32 _dataSize;
uint32 _toPoll;
short _freqs[25][12];
byte _notes[11];
byte _notCol[11];
byte _notLin[11];
bool _notOn[11];
byte _pollNotes[16];
int _samplesTillPoll;
int32 _repCount;
bool _playing;
bool _first;
bool _playing;
bool _ended;
bool _freeData;
bool _tremoloDepth;
bool _vibratoDepth;
bool _keySplit;
int _index;
bool _enableWaveSelect;
unsigned char _wait;
uint8 _tickBeat;
uint8 _beatMeasure;
uint32 _totalTick;
uint32 _nrCommand;
uint16 _pitchBendRangeStep;
uint16 _basicTempo, _tempo;
bool _percussionMode;
byte _percussionBits;
void writeOPL(byte reg, byte val);
void setFreqs();
void setKey(byte voice, byte note, bool on, bool spec);
void setVolume(byte voice, byte volume);
void pollMusic();
uint8 _pitchRange;
uint16 _pitchRangeStep;
virtual void interpret() = 0;
uint8 _voiceNote[kMaxVoiceCount]; // Last note of each voice
uint8 _voiceOn [kMaxVoiceCount]; // Whether each voice is currently on
virtual void reset();
virtual void rewind() = 0;
virtual void setVoices() = 0;
uint8 _operatorVolume[kOperatorCount]; // Volume of each operator
private:
void init();
};
byte _operatorParams[kOperatorCount][kParamCount]; // All operator parameters
class ADLPlayer : public AdLib {
public:
ADLPlayer(Audio::Mixer &mixer);
~ADLPlayer();
uint16 _freqs[kPitchStepCount][kHalfToneCount];
uint16 *_freqPtr[kMaxVoiceCount];
bool load(const char *fileName);
bool load(byte *data, uint32 size, int index = -1);
int _halfToneOffset[kMaxVoiceCount];
void unload();
protected:
void interpret();
void createOPL();
void initOPL();
void reset();
void rewind();
void allOff();
void setVoices();
void setVoice(byte voice, byte instr, bool set);
};
// Write global parameters into the OPL
void writeTremoloVibratoDepthPercMode();
void writeKeySplit();
class MDYPlayer : public AdLib {
public:
MDYPlayer(Audio::Mixer &mixer);
~MDYPlayer();
// Write operator parameters into the OPL
void writeWaveSelect(uint8 oper);
void writeTremoloVibratoSustainingKeyScaleRateFreqMulti(uint8 oper);
void writeSustainRelease(uint8 oper);
void writeAttackDecay(uint8 oper);
void writeFeedbackFM(uint8 oper);
void writeKeyScaleLevelVolume(uint8 oper);
void writeAllParams(uint8 oper);
bool loadMDY(const char *fileName);
bool loadMDY(Common::SeekableReadStream &stream);
bool loadTBR(const char *fileName);
bool loadTBR(Common::SeekableReadStream &stream);
void initOperatorParams();
void initOperatorVolumes();
void setOperatorParams(uint8 oper, const uint16 *params, uint8 wave);
void unload();
void voiceOff(uint8 voice);
protected:
byte _soundMode;
void initFreqs();
void setFreqs(uint16 *freqs, int32 num, int32 denom);
int32 calcFreq(int32 deltaDemiToneNum, int32 deltaDemiToneDenom);
byte *_timbres;
uint16 _tbrCount;
uint16 _tbrStart;
uint32 _timbresSize;
void changePitch(uint8 voice, uint16 pitchBend);
void interpret();
void reset();
void rewind();
void setVoices();
void setVoice(byte voice, byte instr, bool set);
void unloadTBR();
void unloadMDY();
private:
void init();
void setFreq(uint8 voice, uint16 note, bool on);
};
} // End of namespace Gob
#endif // GOB_SOUND_ADLIB_H
#endif // GOB_SOUND_NEWADLIB_H

View file

@ -0,0 +1,257 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "common/stream.h"
#include "common/memstream.h"
#include "common/textconsole.h"
#include "gob/sound/adlplayer.h"
namespace Gob {
ADLPlayer::ADLPlayer(Audio::Mixer &mixer) : AdLib(mixer),
_songData(0), _songDataSize(0), _playPos(0) {
}
ADLPlayer::~ADLPlayer() {
unload();
}
void ADLPlayer::unload() {
stopPlay();
_timbres.clear();
delete[] _songData;
_songData = 0;
_songDataSize = 0;
_playPos = 0;
}
uint32 ADLPlayer::pollMusic(bool first) {
if (_timbres.empty() || !_songData || !_playPos || (_playPos >= (_songData + _songDataSize))) {
end();
return 0;
}
// We'll ignore the first delay
if (first)
_playPos += (*_playPos & 0x80) ? 2 : 1;
byte cmd = *_playPos++;
// Song end marker
if (cmd == 0xFF) {
end();
return 0;
}
// Set the instrument that should be modified
if (cmd == 0xFE)
_modifyInstrument = *_playPos++;
if (cmd >= 0xD0) {
// Modify an instrument
if (_modifyInstrument == 0xFF)
warning("ADLPlayer: No instrument to modify");
else if (_modifyInstrument >= _timbres.size())
warning("ADLPlayer: Can't modify invalid instrument %d (%d)", _modifyInstrument, _timbres.size());
else
_timbres[_modifyInstrument].params[_playPos[0]] = _playPos[1];
_playPos += 2;
// If we currently have that instrument loaded, reload it
for (int i = 0; i < kMaxVoiceCount; i++)
if (_currentInstruments[i] == _modifyInstrument)
setInstrument(i, _modifyInstrument);
} else {
// Voice command
uint8 voice = cmd & 0x0F;
uint8 note, volume;
switch (cmd & 0xF0) {
case 0x00: // Note on with volume
note = *_playPos++;
volume = *_playPos++;
setVoiceVolume(voice, volume);
noteOn(voice, note);
break;
case 0xA0: // Pitch bend
bendVoicePitch(voice, ((uint16)*_playPos++) << 7);
break;
case 0xB0: // Set volume
setVoiceVolume(voice, *_playPos++);
break;
case 0xC0: // Set instrument
setInstrument(voice, *_playPos++);
break;
case 0x90: // Note on
noteOn(voice, *_playPos++);
break;
case 0x80: // Note off
noteOff(voice);
break;
default:
warning("ADLPlayer: Unsupported command: 0x%02X. Stopping playback.", cmd);
end(true);
return 0;
}
}
uint16 delay = *_playPos++;
if (delay & 0x80)
delay = ((delay & 3) << 8) | *_playPos++;
return getSampleDelay(delay);
}
uint32 ADLPlayer::getSampleDelay(uint16 delay) const {
if (delay == 0)
return 0;
return ((uint32)delay * getSamplesPerSecond()) / 1000;
}
void ADLPlayer::rewind() {
// Reset song data
_playPos = _songData;
// Set melody/percussion mode
setPercussionMode(_soundMode != 0);
// Reset instruments
for (Common::Array<Timbre>::iterator t = _timbres.begin(); t != _timbres.end(); ++t)
memcpy(t->params, t->startParams, kOperatorsPerVoice * kParamCount * sizeof(uint16));
for (int i = 0; i < kMaxVoiceCount; i++)
_currentInstruments[i] = 0;
// Reset voices
int numVoice = MIN<int>(_timbres.size(), _soundMode ? (int)kMaxVoiceCount : (int)kMelodyVoiceCount);
for (int i = 0; i < numVoice; i++) {
setInstrument(i, _currentInstruments[i]);
setVoiceVolume(i, kMaxVolume);
}
_modifyInstrument = 0xFF;
}
bool ADLPlayer::load(Common::SeekableReadStream &adl) {
unload();
int timbreCount;
if (!readHeader(adl, timbreCount)) {
unload();
return false;
}
if (!readTimbres(adl, timbreCount) || !readSongData(adl) || adl.err()) {
unload();
return false;
}
rewind();
return true;
}
bool ADLPlayer::readHeader(Common::SeekableReadStream &adl, int &timbreCount) {
// Sanity check
if (adl.size() < 60) {
warning("ADLPlayer::readHeader(): File too small (%d)", adl.size());
return false;
}
_soundMode = adl.readByte();
timbreCount = adl.readByte() + 1;
adl.skip(1);
return true;
}
bool ADLPlayer::readTimbres(Common::SeekableReadStream &adl, int timbreCount) {
_timbres.resize(timbreCount);
for (Common::Array<Timbre>::iterator t = _timbres.begin(); t != _timbres.end(); ++t) {
for (int i = 0; i < (kOperatorsPerVoice * kParamCount); i++)
t->startParams[i] = adl.readUint16LE();
}
if (adl.err()) {
warning("ADLPlayer::readTimbres(): Read failed");
return false;
}
return true;
}
bool ADLPlayer::readSongData(Common::SeekableReadStream &adl) {
_songDataSize = adl.size() - adl.pos();
_songData = new byte[_songDataSize];
if (adl.read(_songData, _songDataSize) != _songDataSize) {
warning("ADLPlayer::readSongData(): Read failed");
return false;
}
return true;
}
bool ADLPlayer::load(const byte *data, uint32 dataSize, int index) {
unload();
Common::MemoryReadStream stream(data, dataSize);
if (!load(stream))
return false;
_index = index;
return true;
}
void ADLPlayer::setInstrument(int voice, int instrument) {
if ((voice >= kMaxVoiceCount) || ((uint)instrument >= _timbres.size()))
return;
_currentInstruments[voice] = instrument;
setVoiceTimbre(voice, _timbres[instrument].params);
}
int ADLPlayer::getIndex() const {
return _index;
}
} // End of namespace Gob

View file

@ -0,0 +1,85 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef GOB_SOUND_ADLPLAYER_H
#define GOB_SOUND_ADLPLAYER_H
#include "common/array.h"
#include "gob/sound/adlib.h"
namespace Common {
class SeekableReadStream;
}
namespace Gob {
/** A player for Coktel Vision's ADL music format. */
class ADLPlayer : public AdLib {
public:
ADLPlayer(Audio::Mixer &mixer);
~ADLPlayer();
bool load(Common::SeekableReadStream &adl);
bool load(const byte *data, uint32 dataSize, int index = -1);
void unload();
int getIndex() const;
protected:
// AdLib interface
uint32 pollMusic(bool first);
void rewind();
private:
struct Timbre {
uint16 startParams[kOperatorsPerVoice * kParamCount];
uint16 params[kOperatorsPerVoice * kParamCount];
};
uint8 _soundMode;
Common::Array<Timbre> _timbres;
byte *_songData;
uint32 _songDataSize;
const byte *_playPos;
int _index;
uint8 _modifyInstrument;
uint16 _currentInstruments[kMaxVoiceCount];
void setInstrument(int voice, int instrument);
bool readHeader (Common::SeekableReadStream &adl, int &timbreCount);
bool readTimbres (Common::SeekableReadStream &adl, int timbreCount);
bool readSongData(Common::SeekableReadStream &adl);
uint32 getSampleDelay(uint16 delay) const;
};
} // End of namespace Gob
#endif // GOB_SOUND_ADLPLAYER_H

View file

@ -0,0 +1,391 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "common/stream.h"
#include "common/textconsole.h"
#include "gob/sound/musplayer.h"
namespace Gob {
MUSPlayer::MUSPlayer(Audio::Mixer &mixer) : AdLib(mixer),
_songData(0), _songDataSize(0), _playPos(0), _songID(0) {
}
MUSPlayer::~MUSPlayer() {
unload();
}
void MUSPlayer::unload() {
stopPlay();
unloadSND();
unloadMUS();
}
uint32 MUSPlayer::getSampleDelay(uint16 delay) const {
if (delay == 0)
return 0;
uint32 freq = (_ticksPerBeat * _tempo) / 60;
return ((uint32)delay * getSamplesPerSecond()) / freq;
}
void MUSPlayer::skipToTiming() {
while (*_playPos < 0x80)
_playPos++;
if (*_playPos != 0xF8)
_playPos--;
}
uint32 MUSPlayer::pollMusic(bool first) {
if (_timbres.empty() || !_songData || !_playPos || (_playPos >= (_songData + _songDataSize))) {
end();
return 0;
}
if (first)
return getSampleDelay(*_playPos++);
uint16 delay = 0;
while (delay == 0) {
byte cmd = *_playPos;
// Delay overflow
if (cmd == 0xF8) {
_playPos++;
delay = 0xF8;
break;
}
// Song end marker
if (cmd == 0xFC) {
end();
return 0;
}
// Global command
if (cmd == 0xF0) {
_playPos++;
byte type1 = *_playPos++;
byte type2 = *_playPos++;
if ((type1 == 0x7F) && (type2 == 0)) {
// Tempo change, as a fraction of the base tempo
uint32 num = *_playPos++;
uint32 denom = *_playPos++;
_tempo = _baseTempo * num + ((_baseTempo * denom) >> 7);
_playPos++;
} else {
// Unsupported global command, skip it
_playPos -= 2;
while(*_playPos++ != 0xF7)
;
}
delay = *_playPos++;
break;
}
// Voice command
if (cmd >= 0x80) {
_playPos++;
_lastCommand = cmd;
} else
cmd = _lastCommand;
uint8 voice = cmd & 0x0F;
uint8 note, volume;
uint16 pitch;
switch (cmd & 0xF0) {
case 0x80: // Note off
_playPos += 2;
noteOff(voice);
break;
case 0x90: // Note on
note = *_playPos++;
volume = *_playPos++;
if (volume) {
setVoiceVolume(voice, volume);
noteOn(voice, note);
} else
noteOff(voice);
break;
case 0xA0: // Set volume
setVoiceVolume(voice, *_playPos++);
break;
case 0xB0:
_playPos += 2;
break;
case 0xC0: // Set instrument
setInstrument(voice, *_playPos++);
break;
case 0xD0:
_playPos++;
break;
case 0xE0: // Pitch bend
pitch = *_playPos++;
pitch += *_playPos++ << 7;
bendVoicePitch(voice, pitch);
break;
default:
warning("MUSPlayer: Unsupported command: 0x%02X", cmd);
skipToTiming();
break;
}
delay = *_playPos++;
}
if (delay == 0xF8) {
delay = 240;
if (*_playPos != 0xF8)
delay += *_playPos++;
}
return getSampleDelay(delay);
}
void MUSPlayer::rewind() {
_playPos = _songData;
_tempo = _baseTempo;
_lastCommand = 0;
setPercussionMode(_soundMode != 0);
setPitchRange(_pitchBendRange);
}
bool MUSPlayer::loadSND(Common::SeekableReadStream &snd) {
unloadSND();
int timbreCount, timbrePos;
if (!readSNDHeader(snd, timbreCount, timbrePos))
return false;
if (!readSNDTimbres(snd, timbreCount, timbrePos) || snd.err()) {
unloadSND();
return false;
}
return true;
}
bool MUSPlayer::readString(Common::SeekableReadStream &stream, Common::String &string, byte *buffer, uint size) {
if (stream.read(buffer, size) != size)
return false;
buffer[size] = '\0';
string = (char *) buffer;
return true;
}
bool MUSPlayer::readSNDHeader(Common::SeekableReadStream &snd, int &timbreCount, int &timbrePos) {
// Sanity check
if (snd.size() <= 6) {
warning("MUSPlayer::readSNDHeader(): File too small (%d)", snd.size());
return false;
}
// Version
const uint8 versionMajor = snd.readByte();
const uint8 versionMinor = snd.readByte();
if ((versionMajor != 1) && (versionMinor != 0)) {
warning("MUSPlayer::readSNDHeader(): Unsupported version %d.%d", versionMajor, versionMinor);
return false;
}
// Number of timbres and where they start
timbreCount = snd.readUint16LE();
timbrePos = snd.readUint16LE();
const uint16 minTimbrePos = 6 + timbreCount * 9;
// Sanity check
if (timbrePos < minTimbrePos) {
warning("MUSPlayer::readSNDHeader(): Timbre offset too small: %d < %d", timbrePos, minTimbrePos);
return false;
}
const uint32 timbreParametersSize = snd.size() - timbrePos;
const uint32 paramSize = kOperatorsPerVoice * kParamCount * sizeof(uint16);
// Sanity check
if (timbreParametersSize != (timbreCount * paramSize)) {
warning("MUSPlayer::loadSND(): Timbre parameters size mismatch: %d != %d",
timbreParametersSize, timbreCount * paramSize);
return false;
}
return true;
}
bool MUSPlayer::readSNDTimbres(Common::SeekableReadStream &snd, int timbreCount, int timbrePos) {
_timbres.resize(timbreCount);
// Read names
byte nameBuffer[10];
for (Common::Array<Timbre>::iterator t = _timbres.begin(); t != _timbres.end(); ++t) {
if (!readString(snd, t->name, nameBuffer, 9)) {
warning("MUSPlayer::readMUSTimbres(): Failed to read timbre name");
return false;
}
}
if (!snd.seek(timbrePos)) {
warning("MUSPlayer::readMUSTimbres(): Failed to seek to timbres");
return false;
}
// Read parameters
for (Common::Array<Timbre>::iterator t = _timbres.begin(); t != _timbres.end(); ++t) {
for (int i = 0; i < (kOperatorsPerVoice * kParamCount); i++)
t->params[i] = snd.readUint16LE();
}
return true;
}
bool MUSPlayer::loadMUS(Common::SeekableReadStream &mus) {
unloadMUS();
if (!readMUSHeader(mus) || !readMUSSong(mus) || mus.err()) {
unloadMUS();
return false;
}
rewind();
return true;
}
bool MUSPlayer::readMUSHeader(Common::SeekableReadStream &mus) {
// Sanity check
if (mus.size() <= 6)
return false;
// Version
const uint8 versionMajor = mus.readByte();
const uint8 versionMinor = mus.readByte();
if ((versionMajor != 1) && (versionMinor != 0)) {
warning("MUSPlayer::readMUSHeader(): Unsupported version %d.%d", versionMajor, versionMinor);
return false;
}
_songID = mus.readUint32LE();
byte nameBuffer[31];
if (!readString(mus, _songName, nameBuffer, 30)) {
warning("MUSPlayer::readMUSHeader(): Failed to read the song name");
return false;
}
_ticksPerBeat = mus.readByte();
_beatsPerMeasure = mus.readByte();
mus.skip(4); // Length of song in ticks
_songDataSize = mus.readUint32LE();
mus.skip(4); // Number of commands
mus.skip(8); // Unused
_soundMode = mus.readByte();
_pitchBendRange = mus.readByte();
_baseTempo = mus.readUint16LE();
mus.skip(8); // Unused
return true;
}
bool MUSPlayer::readMUSSong(Common::SeekableReadStream &mus) {
const uint32 realSongDataSize = mus.size() - mus.pos();
if (realSongDataSize < _songDataSize) {
warning("MUSPlayer::readMUSSong(): File too small for the song data: %d < %d", realSongDataSize, _songDataSize);
return false;
}
_songData = new byte[_songDataSize];
if (mus.read(_songData, _songDataSize) != _songDataSize) {
warning("MUSPlayer::readMUSSong(): Read failed");
return false;
}
return true;
}
void MUSPlayer::unloadSND() {
_timbres.clear();
}
void MUSPlayer::unloadMUS() {
delete[] _songData;
_songData = 0;
_songDataSize = 0;
_playPos = 0;
}
uint32 MUSPlayer::getSongID() const {
return _songID;
}
const Common::String &MUSPlayer::getSongName() const {
return _songName;
}
void MUSPlayer::setInstrument(uint8 voice, uint8 instrument) {
if (instrument >= _timbres.size())
return;
setVoiceTimbre(voice, _timbres[instrument].params);
}
} // End of namespace Gob

View file

@ -0,0 +1,109 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef GOB_SOUND_MUSPLAYER_H
#define GOB_SOUND_MUSPLAYER_H
#include "common/str.h"
#include "common/array.h"
#include "gob/sound/adlib.h"
namespace Common {
class SeekableReadStream;
}
namespace Gob {
/** A player for the AdLib MUS format, with the instrument information in SND files.
*
* In the Gob engine, those files are usually named .MDY and .TBR instead.
*/
class MUSPlayer : public AdLib {
public:
MUSPlayer(Audio::Mixer &mixer);
~MUSPlayer();
/** Load the instruments (.SND or .TBR) */
bool loadSND(Common::SeekableReadStream &snd);
/** Load the melody (.MUS or .MDY) */
bool loadMUS(Common::SeekableReadStream &mus);
void unload();
uint32 getSongID() const;
const Common::String &getSongName() const;
protected:
// AdLib interface
uint32 pollMusic(bool first);
void rewind();
private:
struct Timbre {
Common::String name;
uint16 params[kOperatorsPerVoice * kParamCount];
};
Common::Array<Timbre> _timbres;
byte *_songData;
uint32 _songDataSize;
const byte *_playPos;
uint32 _songID;
Common::String _songName;
uint8 _ticksPerBeat;
uint8 _beatsPerMeasure;
uint8 _soundMode;
uint8 _pitchBendRange;
uint16 _baseTempo;
uint16 _tempo;
byte _lastCommand;
void unloadSND();
void unloadMUS();
bool readSNDHeader (Common::SeekableReadStream &snd, int &timbreCount, int &timbrePos);
bool readSNDTimbres(Common::SeekableReadStream &snd, int timbreCount, int timbrePos);
bool readMUSHeader(Common::SeekableReadStream &mus);
bool readMUSSong (Common::SeekableReadStream &mus);
uint32 getSampleDelay(uint16 delay) const;
void setInstrument(uint8 voice, uint8 instrument);
void skipToTiming();
static bool readString(Common::SeekableReadStream &stream, Common::String &string, byte *buffer, uint size);
};
} // End of namespace Gob
#endif // GOB_SOUND_MUSPLAYER_H

View file

@ -30,7 +30,8 @@
#include "gob/sound/pcspeaker.h"
#include "gob/sound/soundblaster.h"
#include "gob/sound/adlib.h"
#include "gob/sound/adlplayer.h"
#include "gob/sound/musplayer.h"
#include "gob/sound/infogrames.h"
#include "gob/sound/protracker.h"
#include "gob/sound/cdrom.h"
@ -131,10 +132,7 @@ void Sound::sampleFree(SoundDesc *sndDesc, bool noteAdLib, int index) {
if (noteAdLib) {
if (_adlPlayer)
if ((index == -1) || (_adlPlayer->getIndex() == index))
_adlPlayer->stopPlay();
if (_mdyPlayer)
if ((index == -1) || (_mdyPlayer->getIndex() == index))
_mdyPlayer->stopPlay();
_adlPlayer->unload();
}
} else {
@ -235,7 +233,17 @@ bool Sound::adlibLoadADL(const char *fileName) {
debugC(1, kDebugSound, "AdLib: Loading ADL data (\"%s\")", fileName);
return _adlPlayer->load(fileName);
Common::SeekableReadStream *stream = _vm->_dataIO->getFile(fileName);
if (!stream) {
warning("Can't open ADL file \"%s\"", fileName);
return false;
}
bool loaded = _adlPlayer->load(*stream);
delete stream;
return loaded;
}
bool Sound::adlibLoadADL(byte *data, uint32 size, int index) {
@ -267,7 +275,7 @@ bool Sound::adlibLoadMDY(const char *fileName) {
return false;
if (!_mdyPlayer)
_mdyPlayer = new MDYPlayer(*_vm->_mixer);
_mdyPlayer = new MUSPlayer(*_vm->_mixer);
debugC(1, kDebugSound, "AdLib: Loading MDY data (\"%s\")", fileName);
@ -277,7 +285,7 @@ bool Sound::adlibLoadMDY(const char *fileName) {
return false;
}
bool loaded = _mdyPlayer->loadMDY(*stream);
bool loaded = _mdyPlayer->loadMUS(*stream);
delete stream;
@ -289,7 +297,7 @@ bool Sound::adlibLoadTBR(const char *fileName) {
return false;
if (!_mdyPlayer)
_mdyPlayer = new MDYPlayer(*_vm->_mixer);
_mdyPlayer = new MUSPlayer(*_vm->_mixer);
Common::SeekableReadStream *stream = _vm->_dataIO->getFile(fileName);
if (!stream) {
@ -299,7 +307,7 @@ bool Sound::adlibLoadTBR(const char *fileName) {
debugC(1, kDebugSound, "AdLib: Loading MDY instruments (\"%s\")", fileName);
bool loaded = _mdyPlayer->loadTBR(*stream);
bool loaded = _mdyPlayer->loadSND(*stream);
delete stream;
@ -316,11 +324,8 @@ void Sound::adlibPlayTrack(const char *trackname) {
if (_adlPlayer->isPlaying())
return;
debugC(1, kDebugSound, "AdLib: Playing ADL track \"%s\"", trackname);
_adlPlayer->unload();
_adlPlayer->load(trackname);
_adlPlayer->startPlay();
if (adlibLoadADL(trackname))
adlibPlay();
}
void Sound::adlibPlayBgMusic() {
@ -331,7 +336,7 @@ void Sound::adlibPlayBgMusic() {
_adlPlayer = new ADLPlayer(*_vm->_mixer);
static const char *const tracksMac[] = {
// "musmac1.adl", // TODO: This track isn't played correctly at all yet
// "musmac1.adl", // This track seems to be missing instruments...
"musmac2.adl",
"musmac3.adl",
"musmac4.adl",
@ -398,13 +403,11 @@ int Sound::adlibGetIndex() const {
if (_adlPlayer)
return _adlPlayer->getIndex();
if (_mdyPlayer)
return _mdyPlayer->getIndex();
return -1;
}
bool Sound::adlibGetRepeating() const {
int32 Sound::adlibGetRepeating() const {
if (!_hasAdLib)
return false;

View file

@ -32,7 +32,7 @@ class GobEngine;
class PCSpeaker;
class SoundBlaster;
class ADLPlayer;
class MDYPlayer;
class MUSPlayer;
class Infogrames;
class Protracker;
class CDROM;
@ -92,7 +92,7 @@ public:
bool adlibIsPlaying() const;
int adlibGetIndex() const;
bool adlibGetRepeating() const;
int32 adlibGetRepeating() const;
void adlibSetRepeating(int32 repCount);
@ -145,14 +145,23 @@ private:
SoundDesc _sounds[kSoundsCount];
// Speaker
PCSpeaker *_pcspeaker;
// PCM based
SoundBlaster *_blaster;
BackgroundAtmosphere *_bgatmos;
// AdLib
MUSPlayer *_mdyPlayer;
ADLPlayer *_adlPlayer;
MDYPlayer *_mdyPlayer;
// Amiga Paula
Infogrames *_infogrames;
Protracker *_protracker;
// Audio CD
CDROM *_cdrom;
BackgroundAtmosphere *_bgatmos;
};
} // End of namespace Gob