1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
|
/*
* Load_dtm.cpp
* ------------
* Purpose: Digital Tracker / Digital Home Studio module Loader (DTM)
* Notes : (currently none)
* Authors: OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "Loaders.h"
OPENMPT_NAMESPACE_BEGIN
enum PatternFormats : uint32
{
DTM_PT_PATTERN_FORMAT = 0,
DTM_204_PATTERN_FORMAT = MagicBE("2.04"),
DTM_206_PATTERN_FORMAT = MagicBE("2.06"),
};
struct DTMFileHeader
{
char magic[4];
uint32be headerSize;
uint16be type; // 0 = module
uint8be stereoMode; // FF = panoramic stereo, 00 = old stereo
uint8be bitDepth; // Typically 8, sometimes 16, but is not actually used anywhere?
uint16be reserved; // Usually 0, but not in unknown title 1.dtm and unknown title 2.dtm
uint16be speed;
uint16be tempo;
uint32be forcedSampleRate; // Seems to be ignored in newer files
};
MPT_BINARY_STRUCT(DTMFileHeader, 22)
// IFF-style Chunk
struct DTMChunk
{
// 32-Bit chunk identifiers
enum ChunkIdentifiers
{
idS_Q_ = MagicBE("S.Q."),
idPATT = MagicBE("PATT"),
idINST = MagicBE("INST"),
idIENV = MagicBE("IENV"),
idDAPT = MagicBE("DAPT"),
idDAIT = MagicBE("DAIT"),
idTEXT = MagicBE("TEXT"),
idPATN = MagicBE("PATN"),
idTRKN = MagicBE("TRKN"),
idVERS = MagicBE("VERS"),
idSV19 = MagicBE("SV19"),
};
uint32be id;
uint32be length;
size_t GetLength() const
{
return length;
}
ChunkIdentifiers GetID() const
{
return static_cast<ChunkIdentifiers>(id.get());
}
};
MPT_BINARY_STRUCT(DTMChunk, 8)
struct DTMSample
{
uint32be reserved; // 0x204 for first sample, 0x208 for second, etc...
uint32be length; // in bytes
uint8be finetune; // -8....7
uint8be volume; // 0...64
uint32be loopStart; // in bytes
uint32be loopLength; // ditto
char name[22];
uint8be stereo;
uint8be bitDepth;
uint16be transpose;
uint16be unknown;
uint32be sampleRate;
void ConvertToMPT(ModSample &mptSmp, uint32 forcedSampleRate, uint32 formatVersion) const
{
mptSmp.Initialize(MOD_TYPE_IT);
mptSmp.nLength = length;
mptSmp.nLoopStart = loopStart;
mptSmp.nLoopEnd = mptSmp.nLoopStart + loopLength;
// In revolution to come.dtm, the file header says samples rate is 24512 Hz, but samples say it's 50000 Hz
// Digital Home Studio ignores the header setting in 2.04-/2.06-style modules
mptSmp.nC5Speed = (formatVersion == DTM_PT_PATTERN_FORMAT && forcedSampleRate > 0) ? forcedSampleRate : sampleRate;
int32 transposeAmount = 0;
#ifdef MODPLUG_TRACKER
transposeAmount = MOD2XMFineTune(finetune);
#else
mptSmp.nFineTune = MOD2XMFineTune(finetune);
#endif
if(formatVersion == DTM_206_PATTERN_FORMAT && transpose > 0 && transpose != 48)
{
// Digital Home Studio applies this unconditionally, but some old songs sound wrong then (delirium.dtm).
// Digital Tracker 2.03 ignores the setting.
// Maybe this should not be applied for "real" Digital Tracker modules?
transposeAmount += (48 - transpose) * 128;
}
mptSmp.Transpose(transposeAmount * (1.0 / (12.0 * 128.0)));
mptSmp.nVolume = std::min(volume.get(), uint8(64)) * 4u;
if(stereo & 1)
{
mptSmp.uFlags.set(CHN_STEREO);
mptSmp.nLength /= 2u;
mptSmp.nLoopStart /= 2u;
mptSmp.nLoopEnd /= 2u;
}
if(bitDepth > 8)
{
mptSmp.uFlags.set(CHN_16BIT);
mptSmp.nLength /= 2u;
mptSmp.nLoopStart /= 2u;
mptSmp.nLoopEnd /= 2u;
}
if(mptSmp.nLoopEnd > mptSmp.nLoopStart + 1)
{
mptSmp.uFlags.set(CHN_LOOP);
} else
{
mptSmp.nLoopStart = mptSmp.nLoopEnd = 0;
}
}
};
MPT_BINARY_STRUCT(DTMSample, 50)
struct DTMInstrument
{
uint16be insNum;
uint8be unknown1;
uint8be envelope; // 0xFF = none
uint8be sustain; // 0xFF = no sustain point
uint16be fadeout;
uint8be vibRate;
uint8be vibDepth;
uint8be modulationRate;
uint8be modulationDepth;
uint8be breathRate;
uint8be breathDepth;
uint8be volumeRate;
uint8be volumeDepth;
};
MPT_BINARY_STRUCT(DTMInstrument, 15)
struct DTMEnvelope
{
struct DTMEnvPoint
{
uint8be value;
uint8be tick;
};
uint16be numPoints;
DTMEnvPoint points[16];
};
MPT_BINARY_STRUCT(DTMEnvelope::DTMEnvPoint, 2)
MPT_BINARY_STRUCT(DTMEnvelope, 34)
struct DTMText
{
uint16be textType; // 0 = pattern, 1 = free, 2 = song
uint32be textLength;
uint16be tabWidth;
uint16be reserved;
uint16be oddLength;
};
MPT_BINARY_STRUCT(DTMText, 12)
static bool ValidateHeader(const DTMFileHeader &fileHeader)
{
if(std::memcmp(fileHeader.magic, "D.T.", 4)
|| fileHeader.headerSize < sizeof(fileHeader) - 8u
|| fileHeader.headerSize > 256 // Excessively long song title?
|| fileHeader.type != 0)
{
return false;
}
return true;
}
CSoundFile::ProbeResult CSoundFile::ProbeFileHeaderDTM(MemoryFileReader file, const uint64 *pfilesize)
{
DTMFileHeader fileHeader;
if(!file.ReadStruct(fileHeader))
{
return ProbeWantMoreData;
}
if(!ValidateHeader(fileHeader))
{
return ProbeFailure;
}
MPT_UNREFERENCED_PARAMETER(pfilesize);
return ProbeSuccess;
}
bool CSoundFile::ReadDTM(FileReader &file, ModLoadingFlags loadFlags)
{
file.Rewind();
DTMFileHeader fileHeader;
if(!file.ReadStruct(fileHeader))
{
return false;
}
if(!ValidateHeader(fileHeader))
{
return false;
}
if(loadFlags == onlyVerifyHeader)
{
return true;
}
std::string songName;
file.ReadString<mpt::String::maybeNullTerminated>(songName, fileHeader.headerSize - (sizeof(fileHeader) - 8u));
auto chunks = ChunkReader(file).ReadChunks<DTMChunk>(1);
// Read pattern properties
uint32 patternFormat;
if(FileReader chunk = chunks.GetChunk(DTMChunk::idPATT))
{
const uint16 numChannels = chunk.ReadUint16BE();
if(numChannels < 1 || numChannels > 32)
return false;
InitializeGlobals(MOD_TYPE_DTM, numChannels);
Patterns.ResizeArray(chunk.ReadUint16BE()); // Number of stored patterns, may be lower than highest pattern number
patternFormat = chunk.ReadUint32BE();
if(patternFormat != DTM_PT_PATTERN_FORMAT && patternFormat != DTM_204_PATTERN_FORMAT && patternFormat != DTM_206_PATTERN_FORMAT)
return false;
} else
{
return false;
}
m_SongFlags.set(SONG_ITCOMPATGXX | SONG_ITOLDEFFECTS | SONG_FASTPORTAS);
m_playBehaviour.reset(kPeriodsAreHertz);
m_playBehaviour.reset(kITVibratoTremoloPanbrello);
// Various files have a default speed or tempo of 0
if(fileHeader.tempo)
Order().SetDefaultTempoInt(fileHeader.tempo);
if(fileHeader.speed)
Order().SetDefaultSpeed(fileHeader.speed);
if(fileHeader.stereoMode == 0)
SetupMODPanning(true);
m_songName = std::move(songName);
// Read order list
if(FileReader chunk = chunks.GetChunk(DTMChunk::idS_Q_))
{
uint16 ordLen = chunk.ReadUint16BE();
uint16 restartPos = chunk.ReadUint16BE();
chunk.Skip(4); // Reserved
ReadOrderFromFile<uint8>(Order(), chunk, ordLen);
Order().SetRestartPos(restartPos);
} else
{
return false;
}
// Read global info
if(FileReader chunk = chunks.GetChunk(DTMChunk::idSV19))
{
chunk.Skip(2); // Ticks per quarter note, typically 24
uint32 fractionalTempo = chunk.ReadUint32BE();
Order().SetDefaultTempo(TEMPO(Order().GetDefaultTempo().GetInt() + fractionalTempo / 4294967296.0));
uint16be panning[32];
chunk.ReadArray(panning);
for(CHANNELINDEX chn = 0; chn < 32 && chn < GetNumChannels(); chn++)
{
// Panning is in range 0...180, 90 = center
ChnSettings[chn].nPan = static_cast<uint16>(128 + Util::muldivr(std::min(static_cast<int>(panning[chn]), int(180)) - 90, 128, 90));
}
chunk.Skip(16);
// Chunk ends here for old DTM modules
if(chunk.CanRead(2))
{
m_nDefaultGlobalVolume = std::min(chunk.ReadUint16BE(), static_cast<uint16>(MAX_GLOBAL_VOLUME));
}
chunk.Skip(128);
uint16be volume[32];
if(chunk.ReadArray(volume))
{
for(CHANNELINDEX chn = 0; chn < 32 && chn < GetNumChannels(); chn++)
{
// Volume is in range 0...128, 64 = normal
ChnSettings[chn].nVolume = static_cast<uint8>(std::min(static_cast<int>(volume[chn]), int(128)) / 2);
}
m_nSamplePreAmp *= 2; // Compensate for channel volume range
}
}
// Read song message
if(FileReader chunk = chunks.GetChunk(DTMChunk::idTEXT))
{
DTMText text;
chunk.ReadStruct(text);
if(text.oddLength == 0xFFFF)
{
chunk.Skip(1);
}
m_songMessage.Read(chunk, chunk.BytesLeft(), SongMessage::leCRLF);
}
// Read sample headers
if(FileReader chunk = chunks.GetChunk(DTMChunk::idINST))
{
uint16 numSamples = chunk.ReadUint16BE();
bool newSamples = (numSamples >= 0x8000);
numSamples &= 0x7FFF;
if(numSamples >= MAX_SAMPLES || !chunk.CanRead(numSamples * (sizeof(DTMSample) + (newSamples ? 2u : 0u))))
{
return false;
}
m_nSamples = numSamples;
for(SAMPLEINDEX smp = 1; smp <= numSamples; smp++)
{
SAMPLEINDEX realSample = newSamples ? (chunk.ReadUint16BE() + 1u) : smp;
DTMSample dtmSample;
chunk.ReadStruct(dtmSample);
if(realSample < 1 || realSample >= MAX_SAMPLES)
{
continue;
}
m_nSamples = std::max(m_nSamples, realSample);
ModSample &mptSmp = Samples[realSample];
dtmSample.ConvertToMPT(mptSmp, fileHeader.forcedSampleRate, patternFormat);
m_szNames[realSample] = mpt::String::ReadBuf(mpt::String::maybeNullTerminated, dtmSample.name);
}
if(chunk.ReadUint16BE() == 0x0004)
{
// Digital Home Studio instruments
m_nInstruments = std::min(static_cast<INSTRUMENTINDEX>(m_nSamples), static_cast<INSTRUMENTINDEX>(MAX_INSTRUMENTS - 1));
FileReader envChunk = chunks.GetChunk(DTMChunk::idIENV);
while(chunk.CanRead(sizeof(DTMInstrument)))
{
DTMInstrument instr;
chunk.ReadStruct(instr);
if(instr.insNum < GetNumInstruments())
{
ModSample &sample = Samples[instr.insNum + 1];
sample.nVibDepth = instr.vibDepth;
sample.nVibRate = instr.vibRate;
sample.nVibSweep = 255;
ModInstrument *mptIns = AllocateInstrument(instr.insNum + 1, instr.insNum + 1);
if(mptIns != nullptr)
{
InstrumentEnvelope &mptEnv = mptIns->VolEnv;
mptIns->nFadeOut = std::min(static_cast<uint16>(instr.fadeout), uint16(0xFFF));
if(instr.envelope != 0xFF && envChunk.Seek(2 + sizeof(DTMEnvelope) * instr.envelope))
{
DTMEnvelope env;
envChunk.ReadStruct(env);
mptEnv.dwFlags.set(ENV_ENABLED);
mptEnv.resize(std::min({ static_cast<std::size_t>(env.numPoints), std::size(env.points), static_cast<std::size_t>(MAX_ENVPOINTS) }));
for(size_t i = 0; i < mptEnv.size(); i++)
{
mptEnv[i].value = std::min(uint8(64), static_cast<uint8>(env.points[i].value));
mptEnv[i].tick = env.points[i].tick;
}
if(instr.sustain != 0xFF)
{
mptEnv.dwFlags.set(ENV_SUSTAIN);
mptEnv.nSustainStart = mptEnv.nSustainEnd = instr.sustain;
}
if(!mptEnv.empty())
{
mptEnv.dwFlags.set(ENV_LOOP);
mptEnv.nLoopStart = mptEnv.nLoopEnd = static_cast<uint8>(mptEnv.size() - 1);
}
}
}
}
}
}
}
// Read pattern data
for(auto &chunk : chunks.GetAllChunks(DTMChunk::idDAPT))
{
chunk.Skip(4); // FF FF FF FF
PATTERNINDEX patNum = chunk.ReadUint16BE();
ROWINDEX numRows = chunk.ReadUint16BE();
if(patternFormat == DTM_206_PATTERN_FORMAT)
{
// The stored data is actually not row-based, but tick-based.
numRows /= Order().GetDefaultSpeed();
}
if(!(loadFlags & loadPatternData) || patNum > 255 || !Patterns.Insert(patNum, numRows))
{
continue;
}
if(patternFormat == DTM_206_PATTERN_FORMAT)
{
chunk.Skip(4);
for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)
{
uint16 length = chunk.ReadUint16BE();
if(length % 2u) length++;
FileReader rowChunk = chunk.ReadChunk(length);
int tick = 0;
std::div_t position = { 0, 0 };
while(rowChunk.CanRead(6) && static_cast<ROWINDEX>(position.quot) < numRows)
{
ModCommand *m = Patterns[patNum].GetpModCommand(position.quot, chn);
const auto [note, volume, instr, command, param, delay] = rowChunk.ReadArray<uint8, 6>();
if(note > 0 && note <= 96)
{
m->note = note + NOTE_MIN + 12;
if(position.rem)
m->SetEffectCommand(CMD_MODCMDEX, static_cast<ModCommand::PARAM>(0xD0 | std::min(position.rem, 15)));
} else if(note & 0x80)
{
// Lower 7 bits contain note, probably intended for MIDI-like note-on/note-off events
if(position.rem)
m->SetEffectCommand(CMD_MODCMDEX, static_cast<ModCommand::PARAM>(0xC0 |std::min(position.rem, 15)));
else
m->note = NOTE_NOTECUT;
}
if(volume)
{
m->SetVolumeCommand(VOLCMD_VOLUME, std::min(volume, uint8(64))); // Volume can go up to 255, but we do not support over-amplification at the moment.
}
if(instr)
{
m->instr = instr;
}
if(command || param)
{
ConvertModCommand(*m, command, param);
#ifdef MODPLUG_TRACKER
m->Convert(MOD_TYPE_MOD, MOD_TYPE_IT, *this);
#endif
// G is 8-bit volume
// P is tremor (need to disable oldfx)
}
if(delay & 0x80)
tick += (delay & 0x7F) * 0x100 + rowChunk.ReadUint8();
else
tick += delay;
position = std::div(tick, Order().GetDefaultSpeed());
}
}
} else
{
for(ModCommand &m : Patterns[patNum])
{
const auto data = chunk.ReadArray<uint8, 4>();
uint8 command = 0;
if(patternFormat == DTM_204_PATTERN_FORMAT)
{
const auto [note, instrVol, instrCmd, param] = data;
if(note > 0 && note < 0x80)
{
m.note = static_cast<ModCommand::NOTE>((note >> 4) * 12 + (note & 0x0F) + NOTE_MIN + 11);
}
uint8 vol = instrVol >> 2;
if(vol)
{
m.SetVolumeCommand(VOLCMD_VOLUME, static_cast<ModCommand::VOL>(vol - 1u));
}
m.instr = ((instrVol & 0x03) << 4) | (instrCmd >> 4);
command = instrCmd & 0x0F;
m.param = param;
} else
{
std::tie(command, m.param) = ReadMODPatternEntry(data, m);
m.instr |= static_cast<ModCommand::INSTR>(data[0] & 0x30u); // Allow more than 31 instruments
}
ConvertModCommand(m, command, m.param);
// Fix commands without memory and slide nibble precedence
switch(m.command)
{
case CMD_PORTAMENTOUP:
case CMD_PORTAMENTODOWN:
if(!m.param)
m.command = CMD_NONE;
break;
case CMD_VOLUMESLIDE:
case CMD_TONEPORTAVOL:
case CMD_VIBRATOVOL:
if(m.param & 0xF0)
m.param &= 0xF0;
else if(!m.param)
m.command = CMD_NONE;
break;
default:
break;
}
#ifdef MODPLUG_TRACKER
m.Convert(MOD_TYPE_MOD, MOD_TYPE_IT, *this);
#endif
}
}
}
// Read pattern names
if(FileReader chunk = chunks.GetChunk(DTMChunk::idPATN))
{
PATTERNINDEX pat = 0;
std::string name;
while(chunk.CanRead(1) && pat < Patterns.Size())
{
chunk.ReadNullString(name, 32);
Patterns[pat].SetName(name);
pat++;
}
}
// Read channel names
if(FileReader chunk = chunks.GetChunk(DTMChunk::idTRKN))
{
CHANNELINDEX chn = 0;
std::string name;
while(chunk.CanRead(1) && chn < GetNumChannels())
{
chunk.ReadNullString(name, 32);
ChnSettings[chn].szName = name;
chn++;
}
}
// Read sample data
for(auto &chunk : chunks.GetAllChunks(DTMChunk::idDAIT))
{
SAMPLEINDEX smp = chunk.ReadUint16BE();
if(smp >= GetNumSamples() || !(loadFlags & loadSampleData))
{
continue;
}
ModSample &mptSmp = Samples[smp + 1];
SampleIO(
mptSmp.uFlags[CHN_16BIT] ? SampleIO::_16bit : SampleIO::_8bit,
mptSmp.uFlags[CHN_STEREO] ? SampleIO::stereoInterleaved: SampleIO::mono,
SampleIO::bigEndian,
SampleIO::signedPCM).ReadSample(mptSmp, chunk);
}
// Is this accurate?
mpt::ustring tracker;
if(patternFormat == DTM_206_PATTERN_FORMAT)
{
tracker = UL_("Digital Home Studio");
} else if(patternFormat == DTM_PT_PATTERN_FORMAT)
{
tracker = UL_("Digital Tracker 2.3");
} else if(FileReader chunk = chunks.GetChunk(DTMChunk::idVERS))
{
uint32 version = chunk.ReadUint32BE();
tracker = MPT_UFORMAT("Digital Tracker {}.{}")(version >> 4, version & 0x0F);
} else
{
tracker = UL_("Digital Tracker");
}
m_modFormat.formatName = UL_("Digital Tracker");
m_modFormat.type = UL_("dtm");
m_modFormat.madeWithTracker = std::move(tracker);
m_modFormat.charset = mpt::Charset::Amiga_no_C1;
return true;
}
OPENMPT_NAMESPACE_END
|