-
Notifications
You must be signed in to change notification settings - Fork 72
/
Load_mod.cpp
2408 lines (2160 loc) · 71.7 KB
/
Load_mod.cpp
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Load_mod.cpp
* ------------
* Purpose: MOD / NST (ProTracker / NoiseTracker), M15 / STK (Ultimate Soundtracker / Soundtracker) and ST26 (SoundTracker 2.6 / Ice Tracker) module loader / saver
* Notes : "2000 LOC for processing MOD files?!" you say? Well, this file also contains loaders for some formats that are almost identical to MOD, and extensive
* heuristics for more or less broken MOD files and files saved with tons of different trackers, to allow for the most optimal playback.
* Authors: Olivier Lapicque
* OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "Loaders.h"
#include "Tables.h"
#ifndef MODPLUG_NO_FILESAVE
#include "../common/mptFileIO.h"
#endif
#ifdef MPT_EXTERNAL_SAMPLES
// For loading external data in Startrekker files
#include "../common/mptPathString.h"
#endif // MPT_EXTERNAL_SAMPLES
OPENMPT_NAMESPACE_BEGIN
void CSoundFile::ConvertModCommand(ModCommand &m)
{
switch(m.command)
{
case 0x00: if(m.param) m.command = CMD_ARPEGGIO; break;
case 0x01: m.command = CMD_PORTAMENTOUP; break;
case 0x02: m.command = CMD_PORTAMENTODOWN; break;
case 0x03: m.command = CMD_TONEPORTAMENTO; break;
case 0x04: m.command = CMD_VIBRATO; break;
case 0x05: m.command = CMD_TONEPORTAVOL; break;
case 0x06: m.command = CMD_VIBRATOVOL; break;
case 0x07: m.command = CMD_TREMOLO; break;
case 0x08: m.command = CMD_PANNING8; break;
case 0x09: m.command = CMD_OFFSET; break;
case 0x0A: m.command = CMD_VOLUMESLIDE; break;
case 0x0B: m.command = CMD_POSITIONJUMP; break;
case 0x0C: m.command = CMD_VOLUME; break;
case 0x0D: m.command = CMD_PATTERNBREAK; m.param = ((m.param >> 4) * 10) + (m.param & 0x0F); break;
case 0x0E: m.command = CMD_MODCMDEX; break;
case 0x0F:
// For a very long time, this code imported 0x20 as CMD_SPEED for MOD files, but this seems to contradict
// pretty much the majority of other MOD player out there.
// 0x20 is Speed: Impulse Tracker, Scream Tracker, old ModPlug
// 0x20 is Tempo: ProTracker, XMPlay, Imago Orpheus, Cubic Player, ChibiTracker, BeRoTracker, DigiTrakker, DigiTrekker, Disorder Tracker 2, DMP, Extreme's Tracker, ...
if(m.param < 0x20)
m.command = CMD_SPEED;
else
m.command = CMD_TEMPO;
break;
// Extension for XM extended effects
case 'G' - 55: m.command = CMD_GLOBALVOLUME; break; //16
case 'H' - 55: m.command = CMD_GLOBALVOLSLIDE; break;
case 'K' - 55: m.command = CMD_KEYOFF; break;
case 'L' - 55: m.command = CMD_SETENVPOSITION; break;
case 'P' - 55: m.command = CMD_PANNINGSLIDE; break;
case 'R' - 55: m.command = CMD_RETRIG; break;
case 'T' - 55: m.command = CMD_TREMOR; break;
case 'X' - 55: m.command = CMD_XFINEPORTAUPDOWN; break;
case 'Y' - 55: m.command = CMD_PANBRELLO; break; //34
case 'Z' - 55: m.command = CMD_MIDI; break; //35
case '\\' - 56: m.command = CMD_SMOOTHMIDI; break; //rewbs.smoothVST: 36 - note: this is actually displayed as "-" in FT2, but seems to be doing nothing.
//case ':' - 21: m.command = CMD_DELAYCUT; break; //37
case '#' + 3: m.command = CMD_XPARAM; break; //rewbs.XMfixes - Xm.param is 38
default: m.command = CMD_NONE;
}
}
#ifndef MODPLUG_NO_FILESAVE
void CSoundFile::ModSaveCommand(uint8 &command, uint8 ¶m, bool toXM, bool compatibilityExport) const
{
switch(command)
{
case CMD_NONE: command = param = 0; break;
case CMD_ARPEGGIO: command = 0; break;
case CMD_PORTAMENTOUP:
if (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_STM|MOD_TYPE_MPT))
{
if ((param & 0xF0) == 0xE0) { command = 0x0E; param = ((param & 0x0F) >> 2) | 0x10; break; }
else if ((param & 0xF0) == 0xF0) { command = 0x0E; param &= 0x0F; param |= 0x10; break; }
}
command = 0x01;
break;
case CMD_PORTAMENTODOWN:
if(GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_STM|MOD_TYPE_MPT))
{
if ((param & 0xF0) == 0xE0) { command = 0x0E; param= ((param & 0x0F) >> 2) | 0x20; break; }
else if ((param & 0xF0) == 0xF0) { command = 0x0E; param &= 0x0F; param |= 0x20; break; }
}
command = 0x02;
break;
case CMD_TONEPORTAMENTO: command = 0x03; break;
case CMD_VIBRATO: command = 0x04; break;
case CMD_TONEPORTAVOL: command = 0x05; break;
case CMD_VIBRATOVOL: command = 0x06; break;
case CMD_TREMOLO: command = 0x07; break;
case CMD_PANNING8:
command = 0x08;
if(GetType() & MOD_TYPE_S3M)
{
if(param <= 0x80)
{
param = mpt::saturate_cast<uint8>(param * 2);
}
else if(param == 0xA4) // surround
{
if(compatibilityExport || !toXM)
{
command = param = 0;
}
else
{
command = 'X' - 55;
param = 91;
}
}
}
break;
case CMD_OFFSET: command = 0x09; break;
case CMD_VOLUMESLIDE: command = 0x0A; break;
case CMD_POSITIONJUMP: command = 0x0B; break;
case CMD_VOLUME: command = 0x0C; break;
case CMD_PATTERNBREAK: command = 0x0D; param = ((param / 10) << 4) | (param % 10); break;
case CMD_MODCMDEX: command = 0x0E; break;
case CMD_SPEED: command = 0x0F; param = std::min(param, uint8(0x1F)); break;
case CMD_TEMPO: command = 0x0F; param = std::max(param, uint8(0x20)); break;
case CMD_GLOBALVOLUME: command = 'G' - 55; break;
case CMD_GLOBALVOLSLIDE: command = 'H' - 55; break;
case CMD_KEYOFF: command = 'K' - 55; break;
case CMD_SETENVPOSITION: command = 'L' - 55; break;
case CMD_PANNINGSLIDE: command = 'P' - 55; break;
case CMD_RETRIG: command = 'R' - 55; break;
case CMD_TREMOR: command = 'T' - 55; break;
case CMD_XFINEPORTAUPDOWN: command = 'X' - 55;
if(compatibilityExport && param >= 0x30) // X1x and X2x are legit, everything above are MPT extensions, which don't belong here.
param = 0; // Don't set command to 0 to indicate that there *was* some X command here...
break;
case CMD_PANBRELLO:
if(compatibilityExport)
command = param = 0;
else
command = 'Y' - 55;
break;
case CMD_MIDI:
if(compatibilityExport)
command = param = 0;
else
command = 'Z' - 55;
break;
case CMD_SMOOTHMIDI: //rewbs.smoothVST: 36
if(compatibilityExport)
command = param = 0;
else
command = '\\' - 56;
break;
case CMD_XPARAM: //rewbs.XMfixes - XParam is 38
if(compatibilityExport)
command = param = 0;
else
command = '#' + 3;
break;
case CMD_S3MCMDEX:
switch(param & 0xF0)
{
case 0x10: command = 0x0E; param = (param & 0x0F) | 0x30; break;
case 0x20: command = 0x0E; param = (param & 0x0F) | 0x50; break;
case 0x30: command = 0x0E; param = (param & 0x0F) | 0x40; break;
case 0x40: command = 0x0E; param = (param & 0x0F) | 0x70; break;
case 0x90:
if(compatibilityExport)
command = param = 0;
else
command = 'X' - 55;
break;
case 0xB0: command = 0x0E; param = (param & 0x0F) | 0x60; break;
case 0xA0:
case 0x50:
case 0x70:
case 0x60: command = param = 0; break;
default: command = 0x0E; break;
}
break;
default:
command = param = 0;
}
// Don't even think about saving XM effects in MODs...
if(command > 0x0F && !toXM)
{
command = param = 0;
}
}
#endif // MODPLUG_NO_FILESAVE
// File Header
struct MODFileHeader
{
uint8be numOrders;
uint8be restartPos;
uint8be orderList[128];
};
MPT_BINARY_STRUCT(MODFileHeader, 130)
// Sample Header
struct MODSampleHeader
{
char name[22];
uint16be length;
uint8be finetune;
uint8be volume;
uint16be loopStart;
uint16be loopLength;
// Convert an MOD sample header to OpenMPT's internal sample header.
void ConvertToMPT(ModSample &mptSmp, bool is4Chn) const
{
mptSmp.Initialize(MOD_TYPE_MOD);
mptSmp.nLength = length * 2;
mptSmp.nFineTune = MOD2XMFineTune(finetune & 0x0F);
mptSmp.nVolume = 4u * std::min(volume.get(), uint8(64));
SmpLength lStart = loopStart * 2;
SmpLength lLength = loopLength * 2;
// See if loop start is incorrect as words, but correct as bytes (like in Soundtracker modules)
if(lLength > 2 && (lStart + lLength > mptSmp.nLength)
&& (lStart / 2 + lLength <= mptSmp.nLength))
{
lStart /= 2;
}
if(mptSmp.nLength == 2)
{
mptSmp.nLength = 0;
}
if(mptSmp.nLength)
{
mptSmp.nLoopStart = lStart;
mptSmp.nLoopEnd = lStart + lLength;
if(mptSmp.nLoopStart >= mptSmp.nLength)
{
mptSmp.nLoopStart = mptSmp.nLength - 1;
}
if(mptSmp.nLoopStart > mptSmp.nLoopEnd || mptSmp.nLoopEnd < 4 || mptSmp.nLoopEnd - mptSmp.nLoopStart < 4)
{
mptSmp.nLoopStart = 0;
mptSmp.nLoopEnd = 0;
}
// Fix for most likely broken sample loops. This fixes super_sufm_-_new_life.mod (M.K.) which has a long sample which is looped from 0 to 4.
// This module also has notes outside of the Amiga frequency range, so we cannot say that it should be played using ProTracker one-shot loops.
// On the other hand, "Crew Generation" by Necros (6CHN) has a sample with a similar loop, which is supposed to be played.
// To be able to correctly play both modules, we will draw a somewhat arbitrary line here and trust the loop points in MODs with more than
// 4 channels, even if they are tiny and at the very beginning of the sample.
if(mptSmp.nLoopEnd <= 8 && mptSmp.nLoopStart == 0 && mptSmp.nLength > mptSmp.nLoopEnd && is4Chn)
{
mptSmp.nLoopEnd = 0;
}
if(mptSmp.nLoopEnd > mptSmp.nLoopStart)
{
mptSmp.uFlags.set(CHN_LOOP);
}
}
}
// Convert OpenMPT's internal sample header to a MOD sample header.
SmpLength ConvertToMOD(const ModSample &mptSmp)
{
SmpLength writeLength = mptSmp.HasSampleData() ? mptSmp.nLength : 0;
// If the sample size is odd, we have to add a padding byte, as all sample sizes in MODs are even.
if((writeLength % 2u) != 0)
{
writeLength++;
}
LimitMax(writeLength, SmpLength(0x1FFFE));
length = static_cast<uint16>(writeLength / 2u);
if(mptSmp.RelativeTone < 0)
{
finetune = 0x08;
} else if(mptSmp.RelativeTone > 0)
{
finetune = 0x07;
} else
{
finetune = XM2MODFineTune(mptSmp.nFineTune);
}
volume = static_cast<uint8>(mptSmp.nVolume / 4u);
loopStart = 0;
loopLength = 1;
if(mptSmp.uFlags[CHN_LOOP] && (mptSmp.nLoopStart + 2u) < writeLength)
{
const SmpLength loopEnd = Clamp(mptSmp.nLoopEnd, (mptSmp.nLoopStart & ~1) + 2u, writeLength) & ~1;
loopStart = static_cast<uint16>(mptSmp.nLoopStart / 2u);
loopLength = static_cast<uint16>((loopEnd - (mptSmp.nLoopStart & ~1)) / 2u);
}
return writeLength;
}
// Compute a "rating" of this sample header by counting invalid header data to ultimately reject garbage files.
uint32 GetInvalidByteScore() const
{
return ((volume > 64) ? 1 : 0)
+ ((finetune > 15) ? 1 : 0)
+ ((loopStart > length * 2) ? 1 : 0);
}
// Suggested threshold for rejecting invalid files based on cumulated score returned by GetInvalidByteScore
static constexpr uint32 INVALID_BYTE_THRESHOLD = 40;
// This threshold is used for files where the file magic only gives a
// fragile result which alone would lead to too many false positives.
// In particular, the files from Inconexia demo by Iguana
// (https://www.pouet.net/prod.php?which=830) which have 3 \0 bytes in
// the file magic tend to cause misdetection of random files.
static constexpr uint32 INVALID_BYTE_FRAGILE_THRESHOLD = 1;
// Retrieve the internal sample format flags for this sample.
static SampleIO GetSampleFormat()
{
return SampleIO(
SampleIO::_8bit,
SampleIO::mono,
SampleIO::bigEndian,
SampleIO::signedPCM);
}
};
MPT_BINARY_STRUCT(MODSampleHeader, 30)
// Synthesized StarTrekker instruments
struct AMInstrument
{
char am[2]; // "AM"
char zero[4];
uint16be startLevel; // Start level
uint16be attack1Level; // Attack 1 level
uint16be attack1Speed; // Attack 1 speed
uint16be attack2Level; // Attack 2 level
uint16be attack2Speed; // Attack 2 speed
uint16be sustainLevel; // Sustain level
uint16be decaySpeed; // Decay speed
uint16be sustainTime; // Sustain time
uint16be nt; // ?
uint16be releaseSpeed; // Release speed
uint16be waveform; // Waveform
int16be pitchFall; // Pitch fall
uint16be vibAmp; // Vibrato amplitude
uint16be vibSpeed; // Vibrato speed
uint16be octave; // Base frequency
void ConvertToMPT(ModSample &sample, ModInstrument &ins, mpt::fast_prng &rng) const
{
sample.nLength = waveform == 3 ? 1024 : 32;
sample.nLoopStart = 0;
sample.nLoopEnd = sample.nLength;
sample.uFlags.set(CHN_LOOP);
sample.nVolume = 256; // prelude.mod has volume 0 in sample header
sample.nVibDepth = mpt::saturate_cast<uint8>(vibAmp * 2);
sample.nVibRate = static_cast<uint8>(vibSpeed);
sample.nVibType = VIB_SINE;
sample.RelativeTone = static_cast<int8>(-12 * octave);
if(sample.AllocateSample())
{
int8 *p = sample.sample8();
for(SmpLength i = 0; i < sample.nLength; i++)
{
switch(waveform)
{
default:
case 0: p[i] = ModSinusTable[i * 2]; break; // Sine
case 1: p[i] = static_cast<int8>(-128 + i * 8); break; // Saw
case 2: p[i] = i < 16 ? -128 : 127; break; // Square
case 3: p[i] = mpt::random<int8>(rng); break; // Noise
}
}
}
InstrumentEnvelope &volEnv = ins.VolEnv;
volEnv.dwFlags.set(ENV_ENABLED);
volEnv.reserve(6);
volEnv.push_back(0, static_cast<EnvelopeNode::value_t>(startLevel / 4));
const struct
{
uint16 level, speed;
} points[] = {{startLevel, 0}, {attack1Level, attack1Speed}, {attack2Level, attack2Speed}, {sustainLevel, decaySpeed}, {sustainLevel, sustainTime}, {0, releaseSpeed}};
for(uint8 i = 1; i < std::size(points); i++)
{
int duration = std::min(points[i].speed, uint16(256));
// Sustain time is already in ticks, no need to compute the segment duration.
if(i != 4)
{
if(duration == 0)
{
volEnv.dwFlags.set(ENV_LOOP);
volEnv.nLoopStart = volEnv.nLoopEnd = static_cast<uint8>(volEnv.size() - 1);
break;
}
// Startrekker increments / decrements the envelope level by the stage speed
// until it reaches the next stage level.
int a, b;
if(points[i].level > points[i - 1].level)
{
a = points[i].level - points[i - 1].level;
b = 256 - points[i - 1].level;
} else
{
a = points[i - 1].level - points[i].level;
b = points[i - 1].level;
}
// Release time is again special.
if(i == 5)
b = 256;
else if(b == 0)
b = 1;
duration = std::max((256 * a) / (duration * b), 1);
}
if(duration > 0)
{
volEnv.push_back(volEnv.back().tick + static_cast<EnvelopeNode::tick_t>(duration), static_cast<EnvelopeNode::value_t>(points[i].level / 4));
}
}
if(pitchFall)
{
InstrumentEnvelope &pitchEnv = ins.PitchEnv;
pitchEnv.dwFlags.set(ENV_ENABLED);
pitchEnv.reserve(2);
pitchEnv.push_back(0, ENVELOPE_MID);
pitchEnv.push_back(static_cast<EnvelopeNode::tick_t>(1024 / abs(pitchFall)), pitchFall > 0 ? ENVELOPE_MIN : ENVELOPE_MAX);
}
}
};
MPT_BINARY_STRUCT(AMInstrument, 36)
struct PT36IffChunk
{
// IFF chunk names
enum ChunkIdentifiers
{
idVERS = MagicBE("VERS"),
idINFO = MagicBE("INFO"),
idCMNT = MagicBE("CMNT"),
idPTDT = MagicBE("PTDT"),
};
uint32be signature; // IFF chunk name
uint32be chunksize; // chunk size without header
};
MPT_BINARY_STRUCT(PT36IffChunk, 8)
struct PT36InfoChunk
{
char name[32];
uint16be numSamples;
uint16be numOrders;
uint16be numPatterns;
uint16be volume;
uint16be tempo;
uint16be flags;
uint16be dateDay;
uint16be dateMonth;
uint16be dateYear;
uint16be dateHour;
uint16be dateMinute;
uint16be dateSecond;
uint16be playtimeHour;
uint16be playtimeMinute;
uint16be playtimeSecond;
uint16be playtimeMsecond;
};
MPT_BINARY_STRUCT(PT36InfoChunk, 64)
// Check if header magic equals a given string.
static bool IsMagic(const char *magic1, const char (&magic2)[5])
{
return std::memcmp(magic1, magic2, 4) == 0;
}
static uint32 ReadSample(FileReader &file, MODSampleHeader &sampleHeader, ModSample &sample, mpt::charbuf<MAX_SAMPLENAME> &sampleName, bool is4Chn)
{
file.ReadStruct(sampleHeader);
sampleHeader.ConvertToMPT(sample, is4Chn);
sampleName = mpt::String::ReadBuf(mpt::String::spacePadded, sampleHeader.name);
// Get rid of weird characters in sample names.
for(auto &c : sampleName.buf)
{
if(c > 0 && c < ' ')
{
c = ' ';
}
}
// Check for invalid values
return sampleHeader.GetInvalidByteScore();
}
// Parse the order list to determine how many patterns are used in the file.
static PATTERNINDEX GetNumPatterns(FileReader &file, ModSequence &Order, ORDERINDEX numOrders, SmpLength totalSampleLen, CHANNELINDEX &numChannels, bool checkForWOW)
{
PATTERNINDEX numPatterns = 0; // Total number of patterns in file (determined by going through the whole order list) with pattern number < 128
PATTERNINDEX officialPatterns = 0; // Number of patterns only found in the "official" part of the order list (i.e. order positions < claimed order length)
PATTERNINDEX numPatternsIllegal = 0; // Total number of patterns in file, also counting in "invalid" pattern indexes >= 128
for(ORDERINDEX ord = 0; ord < 128; ord++)
{
PATTERNINDEX pat = Order[ord];
if(pat < 128 && numPatterns <= pat)
{
numPatterns = pat + 1;
if(ord < numOrders)
{
officialPatterns = numPatterns;
}
}
if(pat >= numPatternsIllegal)
{
numPatternsIllegal = pat + 1;
}
}
// Remove the garbage patterns past the official order end now that we don't need them anymore.
Order.resize(numOrders);
const size_t patternStartOffset = file.GetPosition();
const size_t sizeWithoutPatterns = totalSampleLen + patternStartOffset;
if(checkForWOW && sizeWithoutPatterns + numPatterns * 8 * 256 == file.GetLength())
{
// Check if this is a Mod's Grave WOW file... Never seen one of those, but apparently they *do* exist.
// WOW files should use the M.K. magic but are actually 8CHN files.
numChannels = 8;
} else if(numPatterns != officialPatterns && numChannels == 4 && !checkForWOW)
{
// Fix SoundTracker modules where "hidden" patterns should be ignored.
// razor-1911.mod (MD5 b75f0f471b0ae400185585ca05bf7fe8, SHA1 4de31af234229faec00f1e85e1e8f78f405d454b)
// and captain_fizz.mod (MD5 55bd89fe5a8e345df65438dbfc2df94e, SHA1 9e0e8b7dc67939885435ea8d3ff4be7704207a43)
// seem to have the "correct" file size when only taking the "official" patterns into account,
// but they only play correctly when also loading the inofficial patterns.
// On the other hand, the SoundTracker module
// wolf1.mod (MD5 a4983d7a432d324ce8261b019257f4ed, SHA1 aa6b399d02546bcb6baf9ec56a8081730dea3f44),
// wolf3.mod (MD5 af60840815aa9eef43820a7a04417fa6, SHA1 24d6c2e38894f78f6c5c6a4b693a016af8fa037b)
// and jean_baudlot_-_bad_dudes_vs_dragonninja-dragonf.mod (MD5 fa48e0f805b36bdc1833f6b82d22d936, SHA1 39f2f8319f4847fe928b9d88eee19d79310b9f91)
// only play correctly if we ignore the hidden patterns.
// Hence, we have a peek at the first hidden pattern and check if it contains a lot of illegal data.
// If that is the case, we assume it's part of the sample data and only consider the "official" patterns.
file.Seek(patternStartOffset + officialPatterns * 1024);
int illegalBytes = 0;
for(int i = 0; i < 256; i++)
{
const auto data = file.ReadArray<uint8, 4>();
if(data[0] & 0xE0)
{
illegalBytes++;
if(illegalBytes > 64)
{
numPatterns = officialPatterns;
break;
}
}
}
file.Seek(patternStartOffset);
}
#ifdef MPT_BUILD_DEBUG
// Check if the "hidden" patterns in the order list are actually real, i.e. if they are saved in the file.
// OpenMPT did this check in the past, but no other tracker appears to do this.
// Interestingly, (broken) variants of the ProTracker modules
// "killing butterfly" (MD5 bd676358b1dbb40d40f25435e845cf6b, SHA1 9df4ae21214ff753802756b616a0cafaeced8021),
// "quartex" by Reflex (MD5 35526bef0fb21cb96394838d94c14bab, SHA1 116756c68c7b6598dcfbad75a043477fcc54c96c),
// seem to have the "correct" file size when only taking the "official" patterns into account, but they only play
// correctly when also loading the inofficial patterns.
// See also the above check for ambiguities with SoundTracker modules.
// Keep this assertion in the code to find potential other broken MODs.
if(numPatterns != officialPatterns && sizeWithoutPatterns + officialPatterns * numChannels * 256 == file.GetLength())
{
MPT_ASSERT(false);
//numPatterns = officialPatterns;
} else
#endif
if(numPatternsIllegal > numPatterns && sizeWithoutPatterns + numPatternsIllegal * numChannels * 256 == file.GetLength())
{
// Even those illegal pattern indexes (> 128) appear to be valid... What a weird file!
// e.g. NIETNU.MOD, where the end of the order list is filled with FF rather than 00, and the file actually contains 256 patterns.
numPatterns = numPatternsIllegal;
} else if(numPatternsIllegal >= 0xFF)
{
// Patterns FE and FF are used with S3M semantics (e.g. some MODs written with old OpenMPT versions)
Order.Replace(0xFE, Order.GetIgnoreIndex());
Order.Replace(0xFF, Order.GetInvalidPatIndex());
}
return numPatterns;
}
void CSoundFile::ReadMODPatternEntry(FileReader &file, ModCommand &m)
{
ReadMODPatternEntry(file.ReadArray<uint8, 4>(), m);
}
void CSoundFile::ReadMODPatternEntry(const std::array<uint8, 4> data, ModCommand &m)
{
// Read Period
uint16 period = (((static_cast<uint16>(data[0]) & 0x0F) << 8) | data[1]);
size_t note = NOTE_NONE;
if(period > 0 && period != 0xFFF)
{
note = std::size(ProTrackerPeriodTable) + 23 + NOTE_MIN;
for(size_t i = 0; i < std::size(ProTrackerPeriodTable); i++)
{
if(period >= ProTrackerPeriodTable[i])
{
if(period != ProTrackerPeriodTable[i] && i != 0)
{
uint16 p1 = ProTrackerPeriodTable[i - 1];
uint16 p2 = ProTrackerPeriodTable[i];
if(p1 - period < (period - p2))
{
note = i + 23 + NOTE_MIN;
break;
}
}
note = i + 24 + NOTE_MIN;
break;
}
}
}
m.note = static_cast<ModCommand::NOTE>(note);
// Read Instrument
m.instr = (data[2] >> 4) | (data[0] & 0x10);
// Read Effect
m.command = data[2] & 0x0F;
m.param = data[3];
}
struct MODMagicResult
{
const mpt::uchar *madeWithTracker = nullptr;
uint32 invalidByteThreshold = MODSampleHeader::INVALID_BYTE_THRESHOLD;
CHANNELINDEX numChannels = 0;
bool isNoiseTracker = false;
bool isStartrekker = false;
bool isGenericMultiChannel = false;
bool setMODVBlankTiming = false;
};
static bool CheckMODMagic(const char magic[4], MODMagicResult &result)
{
if(IsMagic(magic, "M.K.") // ProTracker and compatible
|| IsMagic(magic, "M!K!") // ProTracker (>64 patterns)
|| IsMagic(magic, "PATT") // ProTracker 3.6
|| IsMagic(magic, "NSMS") // kingdomofpleasure.mod by bee hunter
|| IsMagic(magic, "LARD")) // judgement_day_gvine.mod by 4-mat
{
result.madeWithTracker = UL_("Generic ProTracker or compatible");
result.numChannels = 4;
} else if(IsMagic(magic, "M&K!") // "His Master's Noise" musicdisk
|| IsMagic(magic, "FEST") // "His Master's Noise" musicdisk
|| IsMagic(magic, "N.T."))
{
result.madeWithTracker = UL_("NoiseTracker");
result.isNoiseTracker = true;
result.numChannels = 4;
} else if(IsMagic(magic, "OKTA")
|| IsMagic(magic, "OCTA"))
{
// Oktalyzer
result.madeWithTracker = UL_("Oktalyzer");
result.numChannels = 8;
} else if(IsMagic(magic, "CD81")
|| IsMagic(magic, "CD61"))
{
// Octalyser on Atari STe/Falcon
result.madeWithTracker = UL_("Octalyser (Atari)");
result.numChannels = magic[2] - '0';
} else if(IsMagic(magic, "M\0\0\0") || IsMagic(magic, "8\0\0\0"))
{
// Inconexia demo by Iguana, delta samples (https://www.pouet.net/prod.php?which=830)
result.madeWithTracker = UL_("Inconexia demo (delta samples)");
result.invalidByteThreshold = MODSampleHeader::INVALID_BYTE_FRAGILE_THRESHOLD;
result.numChannels = (magic[0] == '8') ? 8 : 4;
} else if(!memcmp(magic, "FA0", 3) && magic[3] >= '4' && magic[3] <= '8')
{
// Digital Tracker on Atari Falcon
result.madeWithTracker = UL_("Digital Tracker");
result.numChannels = magic[3] - '0';
} else if((!memcmp(magic, "FLT", 3) || !memcmp(magic, "EXO", 3)) && magic[3] >= '4' && magic[3] <= '9')
{
// FLTx / EXOx - Startrekker by Exolon / Fairlight
result.madeWithTracker = UL_("Startrekker");
result.isStartrekker = true;
result.setMODVBlankTiming = true;
result.numChannels = magic[3] - '0';
} else if(magic[0] >= '1' && magic[0] <= '9' && !memcmp(magic + 1, "CHN", 3))
{
// xCHN - Many trackers
result.madeWithTracker = UL_("Generic MOD-compatible Tracker");
result.isGenericMultiChannel = true;
result.numChannels = magic[0] - '0';
} else if(magic[0] >= '1' && magic[0] <= '9' && magic[1]>='0' && magic[1] <= '9'
&& (!memcmp(magic + 2, "CH", 2) || !memcmp(magic + 2, "CN", 2)))
{
// xxCN / xxCH - Many trackers
result.madeWithTracker = UL_("Generic MOD-compatible Tracker");
result.isGenericMultiChannel = true;
result.numChannels = (magic[0] - '0') * 10 + magic[1] - '0';
} else if(!memcmp(magic, "TDZ", 3) && magic[3] >= '4' && magic[3] <= '9')
{
// TDZx - TakeTracker
result.madeWithTracker = UL_("TakeTracker");
result.numChannels = magic[3] - '0';
} else
{
return false;
}
return true;
}
CSoundFile::ProbeResult CSoundFile::ProbeFileHeaderMOD(MemoryFileReader file, const uint64 *pfilesize)
{
if(!file.CanRead(1080 + 4))
{
return ProbeWantMoreData;
}
file.Seek(1080);
char magic[4];
file.ReadArray(magic);
MODMagicResult modMagicResult;
if(!CheckMODMagic(magic, modMagicResult))
{
return ProbeFailure;
}
file.Seek(20);
uint32 invalidBytes = 0;
for(SAMPLEINDEX smp = 1; smp <= 31; smp++)
{
MODSampleHeader sampleHeader;
file.ReadStruct(sampleHeader);
invalidBytes += sampleHeader.GetInvalidByteScore();
}
if(invalidBytes > modMagicResult.invalidByteThreshold)
{
return ProbeFailure;
}
MPT_UNREFERENCED_PARAMETER(pfilesize);
return ProbeSuccess;
}
bool CSoundFile::ReadMOD(FileReader &file, ModLoadingFlags loadFlags)
{
char magic[4];
if(!file.Seek(1080) || !file.ReadArray(magic))
{
return false;
}
InitializeGlobals(MOD_TYPE_MOD);
MODMagicResult modMagicResult;
if(!CheckMODMagic(magic, modMagicResult)
|| modMagicResult.numChannels < 1
|| modMagicResult.numChannels > MAX_BASECHANNELS)
{
return false;
}
if(loadFlags == onlyVerifyHeader)
{
return true;
}
m_nChannels = modMagicResult.numChannels;
bool isNoiseTracker = modMagicResult.isNoiseTracker;
bool isStartrekker = modMagicResult.isStartrekker;
bool isGenericMultiChannel = modMagicResult.isGenericMultiChannel;
bool isInconexia = IsMagic(magic, "M\0\0\0") || IsMagic(magic, "8\0\0\0");
// A loop length of zero will freeze ProTracker, so assume that modules having such a value were not meant to be played on Amiga. Fixes LHS_MI.MOD
bool hasRepLen0 = false;
if(modMagicResult.setMODVBlankTiming)
{
m_playBehaviour.set(kMODVBlankTiming);
}
// Startrekker 8 channel mod (needs special treatment, see below)
const bool isFLT8 = isStartrekker && m_nChannels == 8;
// Only apply VBlank tests to M.K. (ProTracker) modules.
const bool isMdKd = IsMagic(magic, "M.K.");
// Adjust finetune values for modules saved with "His Master's Noisetracker"
const bool isHMNT = IsMagic(magic, "M&K!") || IsMagic(magic, "FEST");
// Reading song title
file.Seek(0);
file.ReadString<mpt::String::spacePadded>(m_songName, 20);
// Load Sample Headers
SmpLength totalSampleLen = 0;
m_nSamples = 31;
uint32 invalidBytes = 0;
for(SAMPLEINDEX smp = 1; smp <= 31; smp++)
{
MODSampleHeader sampleHeader;
invalidBytes += ReadSample(file, sampleHeader, Samples[smp], m_szNames[smp], m_nChannels == 4);
totalSampleLen += Samples[smp].nLength;
if(isHMNT)
{
Samples[smp].nFineTune = -static_cast<int8>(sampleHeader.finetune << 3);
} else if(Samples[smp].nLength > 65535)
{
isNoiseTracker = false;
}
if(sampleHeader.length && !sampleHeader.loopLength)
{
hasRepLen0 = true;
}
}
// If there is too much binary garbage in the sample headers, reject the file.
if(invalidBytes > modMagicResult.invalidByteThreshold)
{
return false;
}
// Read order information
MODFileHeader fileHeader;
file.ReadStruct(fileHeader);
file.Skip(4); // Magic bytes (we already parsed these)
ReadOrderFromArray(Order(), fileHeader.orderList);
ORDERINDEX realOrders = fileHeader.numOrders;
if(realOrders > 128)
{
// beatwave.mod by Sidewinder claims to have 129 orders. (MD5: 8a029ac498d453beb929db9a73c3c6b4, SHA1: f7b76fb9f477b07a2e78eb10d8624f0df262cde7 - the version from ModArchive, not ModLand)
realOrders = 128;
} else if(realOrders == 0)
{
// Is this necessary?
realOrders = 128;
while(realOrders > 1 && Order()[realOrders - 1] == 0)
{
realOrders--;
}
}
// Get number of patterns (including some order list sanity checks)
PATTERNINDEX numPatterns = GetNumPatterns(file, Order(), realOrders, totalSampleLen, m_nChannels, isMdKd);
if(isMdKd && GetNumChannels() == 8)
{
// M.K. with 8 channels = Grave Composer
modMagicResult.madeWithTracker = UL_("Mod's Grave");
}
if(isFLT8)
{
// FLT8 has only even order items, so divide by two.
for(auto &pat : Order())
{
pat /= 2u;
}
}
// Restart position sanity checks
realOrders--;
Order().SetRestartPos(fileHeader.restartPos);
// (Ultimate) Soundtracker didn't have a restart position, but instead stored a default tempo in this value.
// The default value for this is 0x78 (120 BPM). This is probably the reason why some M.K. modules
// have this weird restart position. I think I've read somewhere that NoiseTracker actually writes 0x78 there.
// M.K. files that have restart pos == 0x78: action's batman by DJ Uno, VALLEY.MOD, WormsTDC.MOD, ZWARTZ.MOD
// Files that have an order list longer than 0x78 with restart pos = 0x78: my_shoe_is_barking.mod, papermix.mod
// - in both cases it does not appear like the restart position should be used.
MPT_ASSERT(fileHeader.restartPos != 0x78 || fileHeader.restartPos + 1u >= realOrders);
if(fileHeader.restartPos > realOrders || (fileHeader.restartPos == 0x78 && m_nChannels == 4))
{
Order().SetRestartPos(0);
}
m_nDefaultSpeed = 6;
m_nDefaultTempo.Set(125);
m_nMinPeriod = 14 * 4;
m_nMaxPeriod = 3424 * 4;
// Prevent clipping based on number of channels... If all channels are playing at full volume, "256 / #channels"
// is the maximum possible sample pre-amp without getting distortion (Compatible mix levels given).
// The more channels we have, the less likely it is that all of them are used at the same time, though, so cap at 32...
m_nSamplePreAmp = Clamp(256 / m_nChannels, 32, 128);
m_SongFlags.reset(); // SONG_ISAMIGA will be set conditionally
// Setup channel pan positions and volume
SetupMODPanning();
// Before loading patterns, apply some heuristics:
// - Scan patterns to check if file could be a NoiseTracker file in disguise.
// In this case, the parameter of Dxx commands needs to be ignored.
// - Use the same code to find notes that would be out-of-range on Amiga.
// - Detect 7-bit panning.
bool onlyAmigaNotes = true;
bool fix7BitPanning = false;
uint8 maxPanning = 0; // For detecting 8xx-as-sync
if(!isNoiseTracker)
{
bool leftPanning = false, extendedPanning = false; // For detecting 800-880 panning
isNoiseTracker = isMdKd;
for(PATTERNINDEX pat = 0; pat < numPatterns; pat++)
{
uint16 patternBreaks = 0;
for(uint32 i = 0; i < 256; i++)
{
ModCommand m;
ReadMODPatternEntry(file, m);
if(!m.IsAmigaNote())
{
isNoiseTracker = onlyAmigaNotes = false;
}
if((m.command > 0x06 && m.command < 0x0A)
|| (m.command == 0x0E && m.param > 0x01)
|| (m.command == 0x0F && m.param > 0x1F)
|| (m.command == 0x0D && ++patternBreaks > 1))
{
isNoiseTracker = false;
}
if(m.command == 0x08)
{
maxPanning = std::max(maxPanning, m.param);
if(m.param < 0x80)
leftPanning = true;
else if(m.param > 0x8F && m.param != 0xA4)
extendedPanning = true;
} else if(m.command == 0x0E && (m.param & 0xF0) == 0x80)
{
maxPanning = std::max(maxPanning, static_cast<uint8>((m.param & 0x0F) << 4));
}
}
}
fix7BitPanning = leftPanning && !extendedPanning;
}
file.Seek(1084);
const CHANNELINDEX readChannels = (isFLT8 ? 4 : m_nChannels); // 4 channels per pattern in FLT8 format.
if(isFLT8) numPatterns++; // as one logical pattern consists of two real patterns in FLT8 format, the highest pattern number has to be increased by one.
bool hasTempoCommands = false, definitelyCIA = false; // for detecting VBlank MODs
// Heuristic for rejecting E0x commands that are most likely not intended to actually toggle the Amiga LED filter, like in naen_leijasi_ptk.mod by ilmarque
bool filterState = false;
int filterTransitions = 0;
// Reading patterns
Patterns.ResizeArray(numPatterns);
for(PATTERNINDEX pat = 0; pat < numPatterns; pat++)
{
ModCommand *rowBase = nullptr;
if(isFLT8)
{
// FLT8: Only create "even" patterns and either write to channel 1 to 4 (even patterns) or 5 to 8 (odd patterns).
PATTERNINDEX actualPattern = pat / 2u;
if((pat % 2u) == 0 && !Patterns.Insert(actualPattern, 64))
{
break;
}
rowBase = Patterns[actualPattern].GetpModCommand(0, (pat % 2u) == 0 ? 0 : 4);
} else
{
if(!Patterns.Insert(pat, 64))
{
break;
}
rowBase = Patterns[pat].GetpModCommand(0, 0);
}