aboutsummaryrefslogtreecommitdiff
path: root/Src/external_dependencies/openmpt-trunk/soundlib/Load_med.cpp
blob: 1c4a30d895f8d7e9a694b0247084684804a7b7e0 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
/*
 * Load_med.cpp
 * ------------
 * Purpose: OctaMED / MED Soundstudio module loader
 * Notes  : Support for synthesized instruments is still missing.
 * Authors: OpenMPT Devs
 * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
 */

#include "stdafx.h"
#include "Loaders.h"

#ifdef MPT_WITH_VST
#include "../mptrack/Vstplug.h"
#include "plugins/PluginManager.h"
#endif  // MPT_WITH_VST
#include "mpt/io/base.hpp"
#include "mpt/io/io.hpp"
#include "mpt/io/io_span.hpp"
#include "mpt/io/io_stdstream.hpp"

#include <map>

OPENMPT_NAMESPACE_BEGIN

struct MMD0FileHeader
{
	char     mmd[3];               // "MMD" for the first song in file, "MCN" for the rest
	uint8be  version;              // '0'-'3'
	uint32be modLength;            // Size of file
	uint32be songOffset;           // Position in file for the first song
	uint16be playerSettings1[2];   // Internal variables for the play routine
	uint32be blockArrOffset;       // Position in file for blocks (patterns)
	uint8be  flags;
	uint8be  reserved1[3];
	uint32be sampleArrOffset;      // Position in file for samples (should be identical between songs)
	uint32be reserved2;
	uint32be expDataOffset;        // Absolute offset in file for ExpData (0 if not present)
	uint32be reserved3;
	char     playerSettings2[11];  // Internal variables for the play routine
	uint8be  extraSongs;           // Number of songs - 1
};

MPT_BINARY_STRUCT(MMD0FileHeader, 52)


struct MMD0Sample
{
	uint16be loopStart;
	uint16be loopLength;
	uint8be  midiChannel;
	uint8be  midiPreset;
	uint8be  sampleVolume;
	int8be   sampleTranspose;
};

MPT_BINARY_STRUCT(MMD0Sample, 8)


// Song header for MMD0/MMD1
struct MMD0Song
{
	uint8be sequence[256];
};

MPT_BINARY_STRUCT(MMD0Song, 256)


// Song header for MMD2/MMD3
struct MMD2Song
{
	enum Flags3
	{
		FLAG3_STEREO  = 0x01,  // Mixing in stereo
		FLAG3_FREEPAN = 0x02,  // Mixing flag: free pan
	};

	uint32be playSeqTableOffset;
	uint32be sectionTableOffset;
	uint32be trackVolsOffset;
	uint16be numTracks;
	uint16be numPlaySeqs;
	uint32be trackPanOffset;  // 0: all centered (according to docs, MED Soundstudio uses Amiga hard-panning instead)
	uint32be flags3;
	uint16be volAdjust;       // Volume adjust (%)
	uint16be mixChannels;     // Mixing channels, 0 means 4
	uint8be  mixEchoType;     // 0 = nothing, 1 = normal, 2 = cross
	uint8be  mixEchoDepth;    // 1 - 6, 0 = default
	uint16be mixEchoLength;   // Echo length in milliseconds
	int8be   mixStereoSep;    // Stereo separation
	char     pad0[223];
};

MPT_BINARY_STRUCT(MMD2Song, 256)


// Common song header
struct MMDSong
{
	enum Flags
	{
		FLAG_FILTERON   = 0x01,  // The hardware audio filter is on
		FLAG_JUMPINGON  = 0x02,  // Mouse pointer jumping on
		FLAG_JUMP8TH    = 0x04,  // ump every 8th line (not in OctaMED Pro)
		FLAG_INSTRSATT  = 0x08,  // sng+samples indicator (not useful in MMDs)
		FLAG_VOLHEX     = 0x10,  // volumes are HEX
		FLAG_STSLIDE    = 0x20,  // use ST/NT/PT compatible sliding
		FLAG_8CHANNEL   = 0x40,  // this is OctaMED 5-8 channel song
		FLAG_SLOWHQ     = 0x80,  // HQ V2-4 compatibility mode
	};

	enum Flags2
	{
		FLAG2_BMASK = 0x1F,  // (bits 0-4) BPM beat length (in lines)
		FLAG2_BPM   = 0x20,  // BPM mode on
		FLAG2_MIX   = 0x80,  // Module uses mixing
	};

	uint16be numBlocks;   // Number of blocks in current song
	uint16be songLength;  // MMD0: Number of sequence numbers in the play sequence list, MMD2: Number of sections
	char song[256];
	MMD0Song GetMMD0Song() const
	{
		static_assert(sizeof(MMD0Song) == sizeof(song));
		return mpt::bit_cast<MMD0Song>(song);
	}
	MMD2Song GetMMD2Song() const
	{
		static_assert(sizeof(MMD2Song) == sizeof(song));
		return mpt::bit_cast<MMD2Song>(song);
	}
	uint16be defaultTempo;
	int8be   playTranspose;  // The global play transpose value for current song
	uint8be  flags;
	uint8be  flags2;
	uint8be  tempo2;        // Timing pulses per line (ticks)
	uint8be  trackVol[16];  // 1...64 in MMD0/MMD1, reserved in MMD2
	uint8be  masterVol;     // 1...64
	uint8be  numSamples;
};

MPT_BINARY_STRUCT(MMDSong, 284)


struct MMD2PlaySeq
{
	char     name[32];
	uint32be commandTableOffset;
	uint32be reserved;
	uint16be length;  // Number of entries
};

MPT_BINARY_STRUCT(MMD2PlaySeq, 42)


struct MMD0PatternHeader
{
	uint8be numTracks;
	uint8be numRows;
};

MPT_BINARY_STRUCT(MMD0PatternHeader, 2)


struct MMD1PatternHeader
{
	uint16be numTracks;
	uint16be numRows;
	uint32be blockInfoOffset;
};

MPT_BINARY_STRUCT(MMD1PatternHeader, 8)


struct MMDPlaySeqCommand
{
	enum Command
	{
		kStop = 1,
		kJump = 2,
	};

	uint16be offset;   // Offset within current play sequence, 0xFFFF = end of list
	uint8be  command;  // Stop = 1, Jump = 2
	uint8be  extraSize;
};

MPT_BINARY_STRUCT(MMDPlaySeqCommand, 4)


struct MMDBlockInfo
{
	uint32be highlightMaskOffset;
	uint32be nameOffset;
	uint32be nameLength;
	uint32be pageTableOffset;    // File offset of command page table
	uint32be cmdExtTableOffset;  // File offset of command extension table (second parameter)
	uint32be reserved[4];
};

MPT_BINARY_STRUCT(MMDBlockInfo, 36)


struct MMDInstrHeader
{
	enum Types
	{
		VSTI      = -4,
		HIGHLIFE  = -3,
		HYBRID    = -2,
		SYNTHETIC = -1,
		SAMPLE    =  0,  // an ordinary 1-octave sample (or MIDI)
		IFF5OCT   =  1,  // 5 octaves
		IFF3OCT   =  2,  // 3 octaves
		// The following ones are recognized by OctaMED Pro only
		IFF2OCT   = 3,  // 2 octaves
		IFF4OCT   = 4,  // 4 octaves
		IFF6OCT   = 5,  // 6 octaves
		IFF7OCT   = 6,  // 7 octaves
		// OctaMED Pro V5 + later
		EXTSAMPLE = 7,  // two extra-low octaves

		TYPEMASK  = 0x0F,

		S_16          = 0x10,
		STEREO        = 0x20,
		DELTA         = 0x40,
		PACKED        = 0x80,  // MMDPackedSampleHeader follows
		OBSOLETE_MD16 = 0x18,
	};

	uint32be length;
	int16be  type;
};

MPT_BINARY_STRUCT(MMDInstrHeader, 6)


struct MMDPackedSampleHeader
{
	uint16be packType;    // Only 1 = ADPCM is supported
	uint16be subType;     // Packing subtype
	                      // ADPCM subtype
	                      // 1: g723_40
	                      // 2: g721
	                      // 3: g723_24
	uint8be commonFlags;  // flags common to all packtypes (none defined so far)
	uint8be packerFlags;  // flags for the specific packtype
	uint32be leftChLen;   // packed length of left channel in bytes
	uint32be rightChLen;  // packed length of right channel in bytes (ONLY PRESENT IN STEREO SAMPLES)
};

MPT_BINARY_STRUCT(MMDPackedSampleHeader, 14)


struct MMDInstrExt
{
	enum
	{
		SSFLG_LOOP     = 0x01, // Loop On / Off
		SSFLG_EXTPSET  = 0x02, // Ext.Preset
		SSFLG_DISABLED = 0x04, // Disabled
		SSFLG_PINGPONG = 0x08, // Ping-pong looping
	};

	uint8be  hold;   // 0...127
	uint8be  decay;  // 0...127
	uint8be  suppressMidiOff;
	int8be   finetune;
	// Below fields saved by >= V5
	uint8be  defaultPitch;
	uint8be  instrFlags;
	uint16be longMidiPreset;  // Legacy MIDI program mode that doesn't use banks but a combination of two program change commands
	// Below fields saved by >= V5.02
	uint8be  outputDevice;
	uint8be  reserved;
	// Below fields saved by >= V7
	uint32be loopStart;
	uint32be loopLength;
	// Not sure which version starts saving those but they are saved by MED Soundstudio for Windows
	uint8    volume;      // 0...127
	uint8    outputPort;  // Index into user-configurable device list (NOT WinAPI port index)
	uint16le midiBank;
};

MPT_BINARY_STRUCT(MMDInstrExt, 22)


struct MMDInstrInfo
{
	char name[40];
};

MPT_BINARY_STRUCT(MMDInstrInfo, 40)


struct MMD0Exp
{
	uint32be nextModOffset;
	uint32be instrExtOffset;
	uint16be instrExtEntries;
	uint16be instrExtEntrySize;
	uint32be annoText;
	uint32be annoLength;
	uint32be instrInfoOffset;
	uint16be instrInfoEntries;
	uint16be instrInfoEntrySize;
	uint32be jumpMask;
	uint32be rgbTable;
	uint8be  channelSplit[4];
	uint32be notationInfoOffset;
	uint32be songNameOffset;
	uint32be songNameLength;
	uint32be midiDumpOffset;
	uint32be mmdInfoOffset;
	uint32be arexxOffset;
	uint32be midiCmd3xOffset;
	uint32be trackInfoOffset;   // Pointer to song->numtracks pointers to tag lists
	uint32be effectInfoOffset;  // Pointers to group pointers
	uint32be tagEnd;
};

MPT_BINARY_STRUCT(MMD0Exp, 80)


struct MMDTag
{
	enum TagType
	{
		// Generic MMD tags
		MMDTAG_END      = 0x00000000,
		MMDTAG_PTR      = 0x80000000,  // Data needs relocation
		MMDTAG_MUSTKNOW = 0x40000000,  // Loader must fail if this isn't recognized
		MMDTAG_MUSTWARN = 0x20000000,  // Loader must warn if this isn't recognized
		MMDTAG_MASK     = 0x1FFFFFFF,

		// ExpData tags
		// # of effect groups, including the global group (will override settings in MMDSong struct), default = 1
		MMDTAG_EXP_NUMFXGROUPS = 1,
		MMDTAG_TRK_FXGROUP     = 3,

		MMDTAG_TRK_NAME    = 1,  // trackinfo tags
		MMDTAG_TRK_NAMELEN = 2,  // namelen includes zero term.

		// effectinfo tags
		MMDTAG_FX_ECHOTYPE   = 1,
		MMDTAG_FX_ECHOLEN    = 2,
		MMDTAG_FX_ECHODEPTH  = 3,
		MMDTAG_FX_STEREOSEP  = 4,
		MMDTAG_FX_GROUPNAME  = 5,  // the Global Effects group shouldn't have name saved!
		MMDTAG_FX_GRPNAMELEN = 6,  // namelen includes zero term.
	};

	uint32be type;
	uint32be data;
};

MPT_BINARY_STRUCT(MMDTag, 8)


struct MMDDump
{
	uint32be length;
	uint32be dataPointer;
	uint16be extLength;  // If >= 20: name follows as char[20]
};

MPT_BINARY_STRUCT(MMDDump, 10)


static TEMPO MMDTempoToBPM(uint32 tempo, bool is8Ch, bool bpmMode, uint8 rowsPerBeat)
{
	if(bpmMode && !is8Ch)
	{
		// You would have thought that we could use modern tempo mode here.
		// Alas, the number of ticks per row still influences the tempo. :(
		return TEMPO((tempo * rowsPerBeat) / 4.0);
	}
	if(is8Ch && tempo > 0)
	{
		LimitMax(tempo, 10u);
		// MED Soundstudio uses these tempos when importing old files
		static constexpr uint8 tempos[10] = {179, 164, 152, 141, 131, 123, 116, 110, 104, 99};
		return TEMPO(tempos[tempo - 1], 0);
	} else if(tempo > 0 && tempo <= 10)
	{
		// SoundTracker compatible tempo
		return TEMPO((6.0 * 1773447.0 / 14500.0) / tempo);
	}

	return TEMPO(tempo / 0.264);
}


static void ConvertMEDEffect(ModCommand &m, bool is8ch, bool bpmMode, uint8 rowsPerBeat, bool volHex)
{
	switch(m.command)
	{
	case 0x04:  // Vibrato (twice as deep as in ProTracker)
		m.command = CMD_VIBRATO;
		m.param = (std::min<uint8>(m.param >> 3, 0x0F) << 4) | std::min<uint8>((m.param & 0x0F) * 2, 0x0F);
		break;
	case 0x08:  // Hold and decay
		m.command = CMD_NONE;
		break;
	case 0x09:  // Set secondary speed
		if(m.param > 0 && m.param <= 20)
			m.command = CMD_SPEED;
		else
			m.command = CMD_NONE;
		break;
	case 0x0C:  // Set Volume
		m.command = CMD_VOLUME;
		if(!volHex && m.param < 0x99)
			m.param = (m.param >> 4) * 10 + (m.param & 0x0F);
		else if(volHex)
			m.param = ((m.param & 0x7F) + 1) / 2;
		else
			m.command = CMD_NONE;
		break;
	case 0x0D:
		m.command = CMD_VOLUMESLIDE;
		break;
	case 0x0E:  // Synth jump
		m.command = CMD_NONE;
		break;
	case 0x0F:  // Misc
		if(m.param == 0)
		{
			m.command = CMD_PATTERNBREAK;
		} else if(m.param <= 0xF0)
		{
			m.command = CMD_TEMPO;
			if(m.param < 0x03)  // This appears to be a bug in OctaMED which is not emulated in MED Soundstudio on Windows.
				m.param = 0x70;
			else
				m.param = mpt::saturate_round<ModCommand::PARAM>(MMDTempoToBPM(m.param, is8ch, bpmMode, rowsPerBeat).ToDouble());
#ifdef MODPLUG_TRACKER
			if(m.param < 0x20)
				m.param = 0x20;
#endif  // MODPLUG_TRACKER
		} else switch(m.command)
		{
			case 0xF1:  // Play note twice
				m.command = CMD_MODCMDEX;
				m.param = 0x93;
				break;
			case 0xF2:  // Delay note
				m.command = CMD_MODCMDEX;
				m.param = 0xD3;
				break;
			case 0xF3:  // Play note three times
				m.command = CMD_MODCMDEX;
				m.param = 0x92;
				break;
			case 0xF8:  // Turn filter off
			case 0xF9:  // Turn filter on
				m.command = CMD_MODCMDEX;
				m.param = 0xF9 - m.param;
				break;
			case 0xFA:  // MIDI pedal on
			case 0xFB:  // MIDI pedal off
			case 0xFD:  // Set pitch
			case 0xFE:  // End of song
				m.command = CMD_NONE;
				break;
			case 0xFF:  // Turn note off
				m.note = NOTE_NOTECUT;
				m.command = CMD_NONE;
				break;
			default:
				m.command = CMD_NONE;
				break;
		}
		break;
	case 0x10:  // MIDI message
		m.command = CMD_MIDI;
		m.param |= 0x80;
		break;
	case 0x11:  // Slide pitch up
		m.command = CMD_MODCMDEX;
		m.param = 0x10 | std::min<uint8>(m.param, 0x0F);
		break;
	case 0x12:  // Slide pitch down
		m.command = CMD_MODCMDEX;
		m.param = 0x20 | std::min<uint8>(m.param, 0x0F);
		break;
	case 0x14:  // Vibrato (ProTracker compatible depth, but faster)
		m.command = CMD_VIBRATO;
		m.param = (std::min<uint8>((m.param >> 4) + 1, 0x0F) << 4) | (m.param & 0x0F);
		break;
	case 0x15:  // Set finetune
		m.command = CMD_MODCMDEX;
		m.param = 0x50 | (m.param & 0x0F);
		break;
	case 0x16:  // Loop
		m.command = CMD_MODCMDEX;
		m.param = 0x60 | std::min<uint8>(m.param, 0x0F);
		break;
	case 0x18:  // Stop note
		m.command = CMD_MODCMDEX;
		m.param = 0xC0 | std::min<uint8>(m.param, 0x0F);
		break;
	case 0x19:  // Sample Offset
		m.command = CMD_OFFSET;
		break;
	case 0x1A:  // Slide volume up once
		m.command = CMD_MODCMDEX;
		m.param = 0xA0 | std::min<uint8>(m.param, 0x0F);
		break;
	case 0x1B:  // Slide volume down once
		m.command = CMD_MODCMDEX;
		m.param = 0xB0 | std::min<uint8>(m.param, 0x0F);
		break;
	case 0x1C:  // MIDI program
		if(m.param > 0 && m.param <= 128)
		{
			m.command = CMD_MIDI;
			m.param--;
		} else
		{
			m.command = CMD_NONE;
		}
		break;
	case 0x1D:  // Pattern break (in hex)
		m.command = CMD_PATTERNBREAK;
		break;
	case 0x1E:  // Repeat row
		m.command = CMD_MODCMDEX;
		m.param = 0xE0 | std::min<uint8>(m.param, 0x0F);
		break;
	case 0x1F:  // Note delay and retrigger
	{
		if(m.param & 0xF0)
		{
			m.command = CMD_MODCMDEX;
			m.param = 0xD0 | (m.param >> 4);
		} else if(m.param & 0x0F)
		{
			m.command = CMD_MODCMDEX;
			m.param = 0x90 | m.param;
		} else
		{
			m.command = CMD_NONE;
		}
		break;
	}
	case 0x20:  // Reverse sample + skip samples
		if(m.param == 0 && m.vol == 0)
		{
			if(m.IsNote())
			{
				m.command = CMD_S3MCMDEX;
				m.param = 0x9F;
			}
		} else
		{
			// Skip given number of samples
			m.command = CMD_NONE;
		}
		break;
	case 0x29:  // Relative sample offset
		if(m.vol > 0)
		{
			m.command = CMD_OFFSETPERCENTAGE;
			m.param = mpt::saturate_cast<ModCommand::PARAM>(Util::muldiv_unsigned(m.param, 0x100, m.vol));
		} else
		{
			m.command = CMD_NONE;
		}
		break;
	case 0x2E:  // Set panning
		if(m.param <= 0x10 || m.param >= 0xF0)
		{
			m.command = CMD_PANNING8;
			m.param = mpt::saturate_cast<ModCommand::PARAM>(((m.param ^ 0x80) - 0x70) * 8);
		} else
		{
			m.command = CMD_NONE;
		}
		break;
	default:
		if(m.command < 0x10)
			CSoundFile::ConvertModCommand(m);
		else
			m.command = CMD_NONE;
		break;
	}
}

#ifdef MPT_WITH_VST
static std::wstring ReadMEDStringUTF16BE(FileReader &file)
{
	FileReader chunk = file.ReadChunk(file.ReadUint32BE());
	std::wstring s(chunk.GetLength() / 2u, L'\0');
	for(auto &c : s)
	{
		c = chunk.ReadUint16BE();
	}
	return s;
}
#endif  // MPT_WITH_VST


static void MEDReadNextSong(FileReader &file, MMD0FileHeader &fileHeader, MMD0Exp &expData, MMDSong &songHeader)
{
	file.ReadStruct(fileHeader);
	file.Seek(fileHeader.songOffset + 63 * sizeof(MMD0Sample));
	file.ReadStruct(songHeader);
	if(fileHeader.expDataOffset && file.Seek(fileHeader.expDataOffset))
		file.ReadStruct(expData);
	else
		expData = {};
}


static std::pair<CHANNELINDEX, SEQUENCEINDEX> MEDScanNumChannels(FileReader &file, const uint8 version)
{
	MMD0FileHeader fileHeader;
	MMD0Exp expData;
	MMDSong songHeader;

	file.Rewind();
	uint32 songOffset = 0;
	MEDReadNextSong(file, fileHeader, expData, songHeader);

	SEQUENCEINDEX numSongs = std::min(MAX_SEQUENCES, mpt::saturate_cast<SEQUENCEINDEX>(fileHeader.expDataOffset ? fileHeader.extraSongs + 1 : 1));
	CHANNELINDEX numChannels = 4;
	// Scan patterns for max number of channels
	for(SEQUENCEINDEX song = 0; song < numSongs; song++)
	{
		const PATTERNINDEX numPatterns = songHeader.numBlocks;
		if(songHeader.numSamples > 63 || numPatterns > 0x7FFF)
			return {};

		for(PATTERNINDEX pat = 0; pat < numPatterns; pat++)
		{
			if(!file.Seek(fileHeader.blockArrOffset + pat * 4u)
			   || !file.Seek(file.ReadUint32BE()))
			{
				continue;
			}
			numChannels = std::max(numChannels, static_cast<CHANNELINDEX>(version < 1 ? file.ReadUint8() : file.ReadUint16BE()));
		}

		// If song offsets are going backwards, reject the file
		if(expData.nextModOffset <= songOffset || !file.Seek(expData.nextModOffset))
		{
			numSongs = song + 1;
			break;
		}
		songOffset = expData.nextModOffset;
		MEDReadNextSong(file, fileHeader, expData, songHeader);
	}
	return {numChannels, numSongs};
}


static bool ValidateHeader(const MMD0FileHeader &fileHeader)
{
	if(std::memcmp(fileHeader.mmd, "MMD", 3)
	   || fileHeader.version < '0' || fileHeader.version > '3'
	   || fileHeader.songOffset < sizeof(MMD0FileHeader)
	   || fileHeader.songOffset > uint32_max - 63 * sizeof(MMD0Sample) - sizeof(MMDSong)
	   || fileHeader.blockArrOffset < sizeof(MMD0FileHeader)
	   || (fileHeader.sampleArrOffset > 0 && fileHeader.sampleArrOffset < sizeof(MMD0FileHeader))
	   || fileHeader.expDataOffset > uint32_max - sizeof(MMD0Exp))
	{
		return false;
	}
	return true;
}


static uint64 GetHeaderMinimumAdditionalSize(const MMD0FileHeader &fileHeader)
{
	return std::max<uint64>({ fileHeader.songOffset + 63 * sizeof(MMD0Sample) + sizeof(MMDSong),
		fileHeader.blockArrOffset,
		fileHeader.sampleArrOffset ? fileHeader.sampleArrOffset : sizeof(MMD0FileHeader),
		fileHeader.expDataOffset + sizeof(MMD0Exp) }) - sizeof(MMD0FileHeader);
}


CSoundFile::ProbeResult CSoundFile::ProbeFileHeaderMED(MemoryFileReader file, const uint64 *pfilesize)
{
	MMD0FileHeader fileHeader;
	if(!file.ReadStruct(fileHeader))
		return ProbeWantMoreData;
	if(!ValidateHeader(fileHeader))
		return ProbeFailure;
	return ProbeAdditionalSize(file, pfilesize, GetHeaderMinimumAdditionalSize(fileHeader));
}


bool CSoundFile::ReadMED(FileReader &file, ModLoadingFlags loadFlags)
{
	file.Rewind();
	MMD0FileHeader fileHeader;
	if(!file.ReadStruct(fileHeader))
		return false;
	if(!ValidateHeader(fileHeader))
		return false;
	if(!file.CanRead(mpt::saturate_cast<FileReader::off_t>(GetHeaderMinimumAdditionalSize(fileHeader))))
		return false;
	if(loadFlags == onlyVerifyHeader)
		return true;
	
	InitializeGlobals(MOD_TYPE_MED);
	InitializeChannels();
	const uint8 version = fileHeader.version - '0';

	file.Seek(fileHeader.songOffset);
	FileReader sampleHeaderChunk = file.ReadChunk(63 * sizeof(MMD0Sample));

	MMDSong songHeader;
	file.ReadStruct(songHeader);

	if(songHeader.numSamples > 63 || songHeader.numBlocks > 0x7FFF)
		return false;

	MMD0Exp expData{};
	if(fileHeader.expDataOffset && file.Seek(fileHeader.expDataOffset))
	{
		file.ReadStruct(expData);
	}

	const auto [numChannels, numSongs] = MEDScanNumChannels(file, version);
	if(numChannels < 1 || numChannels > MAX_BASECHANNELS)
		return false;
	m_nChannels = numChannels;

	// Start with the instruments, as those are shared between songs

	std::vector<uint32be> instrOffsets;
	if(fileHeader.sampleArrOffset)
	{
		file.Seek(fileHeader.sampleArrOffset);
		file.ReadVector(instrOffsets, songHeader.numSamples);
	} else if(songHeader.numSamples > 0)
	{
		return false;
	}
	m_nInstruments = m_nSamples = songHeader.numSamples;

	// In MMD0 / MMD1, octave wrapping is not done for synth instruments
	// - It's required e.g. for automatic terminated to.mmd0 and you got to let the music.mmd1
	// - starkelsesirap.mmd0 (synth instruments) on the other hand don't need it
	// In MMD2 / MMD3, the mix flag is used instead.
	const bool hardwareMixSamples = (version < 2) || (version >= 2 && !(songHeader.flags2 & MMDSong::FLAG2_MIX));

	bool needInstruments = false;
	bool anySynthInstrs = false;
#ifdef MPT_WITH_VST
	PLUGINDEX numPlugins = 0;
#endif  // MPT_WITH_VST
	for(SAMPLEINDEX ins = 1, smp = 1; ins <= m_nInstruments; ins++)
	{
		if(!AllocateInstrument(ins, smp))
			return false;
		ModInstrument &instr = *Instruments[ins];

		MMDInstrHeader instrHeader{};
		FileReader sampleChunk;
		if(instrOffsets[ins - 1] != 0 && file.Seek(instrOffsets[ins - 1]))
		{
			file.ReadStruct(instrHeader);
			uint32 chunkLength = instrHeader.length;
			if(instrHeader.type > 0 && (instrHeader.type & MMDInstrHeader::STEREO))
				chunkLength *= 2u;
			sampleChunk = file.ReadChunk(chunkLength);
		}
		const bool isSynth = instrHeader.type < 0;
		const size_t maskedType = static_cast<size_t>(instrHeader.type & MMDInstrHeader::TYPEMASK);

#ifdef MPT_WITH_VST
		if(instrHeader.type == MMDInstrHeader::VSTI)
		{
			needInstruments = true;
			sampleChunk.Skip(6); // 00 00 <size of following data>
			const std::wstring type = ReadMEDStringUTF16BE(sampleChunk);
			const std::wstring name = ReadMEDStringUTF16BE(sampleChunk);
			if(type == L"VST")
			{
				auto &mixPlug = m_MixPlugins[numPlugins];
				mixPlug = {};
				mixPlug.Info.dwPluginId1 = Vst::kEffectMagic;
				mixPlug.Info.gain = 10;
				mixPlug.Info.szName = mpt::ToCharset(mpt::Charset::Locale, name);
				mixPlug.Info.szLibraryName = mpt::ToCharset(mpt::Charset::UTF8, name);
				instr.nMixPlug = numPlugins + 1;
				instr.nMidiChannel = MidiFirstChannel;
				instr.Transpose(-24);
				instr.AssignSample(0);
				// TODO: Figure out patch and routing data

				numPlugins++;
			}
		} else
#endif  // MPT_WITH_VST
		if(isSynth)
		{
			// TODO: Figure out synth instruments
			anySynthInstrs = true;
			instr.AssignSample(0);
		}

		uint8 numSamples = 1;
		static constexpr uint8 SamplesPerType[] = {1, 5, 3, 2, 4, 6, 7};
		if(!isSynth && maskedType < std::size(SamplesPerType))
			numSamples = SamplesPerType[maskedType];
		if(numSamples > 1)
		{
			static_assert(MAX_SAMPLES > 63 * 9, "Check IFFOCT multisample code");
			m_nSamples += numSamples - 1;
			needInstruments = true;
			static constexpr uint8 OctSampleMap[][8] =
			{
				{1, 1, 0, 0, 0, 0, 0, 0},  // 2
				{2, 2, 1, 1, 0, 0, 0, 0},  // 3
				{3, 3, 2, 2, 1, 0, 0, 0},  // 4
				{4, 3, 2, 1, 1, 0, 0, 0},  // 5
				{5, 4, 3, 2, 1, 0, 0, 0},  // 6
				{6, 5, 4, 3, 2, 1, 0, 0},  // 7
			};

			static constexpr int8 OctTransposeMap[][8] =
			{
				{ 0, 0, -12, -12, -24, -36, -48, -60},  // 2
				{ 0, 0, -12, -12, -24, -36, -48, -60},  // 3
				{ 0, 0, -12, -12, -24, -36, -48, -60},  // 4
				{12, 0, -12, -24, -24, -36, -48, -60},  // 5
				{12, 0, -12, -24, -36, -48, -48, -60},  // 6
				{12, 0, -12, -24, -36, -48, -60, -72},  // 7
			};

			// TODO: Move octaves so that they align better (C-4 = lowest, we don't have access to the highest four octaves)
			for(int octave = 4; octave < 10; octave++)
			{
				for(int note = 0; note < 12; note++)
				{
					instr.Keyboard[12 * octave + note] = smp + OctSampleMap[numSamples - 2][octave - 4];
					instr.NoteMap[12 * octave + note] += OctTransposeMap[numSamples - 2][octave - 4];
				}
			}
		} else if(maskedType == MMDInstrHeader::EXTSAMPLE)
		{
			needInstruments = true;
			instr.Transpose(-24);
		} else if(!isSynth && hardwareMixSamples)
		{
			for(int octave = 7; octave < 10; octave++)
			{
				for(int note = 0; note < 12; note++)
				{
					instr.NoteMap[12 * octave + note] -= static_cast<uint8>((octave - 6) * 12);
				}
			}
		}

		MMD0Sample sampleHeader;
		sampleHeaderChunk.ReadStruct(sampleHeader);

		// midiChannel = 0xFF == midi instrument but with invalid channel, midiChannel = 0x00 == sample-based instrument?
		if(sampleHeader.midiChannel > 0 && sampleHeader.midiChannel <= 16)
		{
			instr.nMidiChannel = sampleHeader.midiChannel - 1 + MidiFirstChannel;
			needInstruments = true;

#ifdef MPT_WITH_VST
			if(!isSynth)
			{
				auto &mixPlug = m_MixPlugins[numPlugins];
				mixPlug = {};
				mixPlug.Info.dwPluginId1 = PLUGMAGIC('V', 's', 't', 'P');
				mixPlug.Info.dwPluginId2 = PLUGMAGIC('M', 'M', 'I', 'D');
				mixPlug.Info.gain = 10;
				mixPlug.Info.szName = "MIDI Input Output";
				mixPlug.Info.szLibraryName = "MIDI Input Output";

				instr.nMixPlug = numPlugins + 1;
				instr.Transpose(-24);

				numPlugins++;
			}
#endif  // MPT_WITH_VST
		}
		if(sampleHeader.midiPreset > 0 && sampleHeader.midiPreset <= 128)
		{
			instr.nMidiProgram = sampleHeader.midiPreset;
		}

		for(SAMPLEINDEX i = 0; i < numSamples; i++)
		{
			ModSample &mptSmp = Samples[smp + i];
			mptSmp.Initialize(MOD_TYPE_MED);
			mptSmp.nVolume = 4u * std::min<uint8>(sampleHeader.sampleVolume, 64u);
			mptSmp.RelativeTone = sampleHeader.sampleTranspose;
		}

		if(isSynth || !(loadFlags & loadSampleData))
		{
			smp += numSamples;
			continue;
		}

		SampleIO sampleIO(
			SampleIO::_8bit,
			SampleIO::mono,
			SampleIO::bigEndian,
			SampleIO::signedPCM);

		const bool hasLoop = sampleHeader.loopLength > 1;
		SmpLength loopStart = sampleHeader.loopStart * 2;
		SmpLength loopEnd = loopStart + sampleHeader.loopLength * 2;

		SmpLength length = mpt::saturate_cast<SmpLength>(sampleChunk.GetLength());
		if(instrHeader.type & MMDInstrHeader::S_16)
		{
			sampleIO |= SampleIO::_16bit;
			length /= 2;
		}
		if(instrHeader.type & MMDInstrHeader::STEREO)
		{
			sampleIO |= SampleIO::stereoSplit;
			length /= 2;
		}
		if(instrHeader.type & MMDInstrHeader::DELTA)
		{
			sampleIO |= SampleIO::deltaPCM;
		}

		if(numSamples > 1)
			length = length / ((1u << numSamples) - 1);

		for(SAMPLEINDEX i = 0; i < numSamples; i++)
		{
			ModSample &mptSmp = Samples[smp + i];

			mptSmp.nLength = length;
			sampleIO.ReadSample(mptSmp, sampleChunk);

			if(hasLoop)
			{
				mptSmp.nLoopStart = loopStart;
				mptSmp.nLoopEnd = loopEnd;
				mptSmp.uFlags.set(CHN_LOOP);
			}

			length *= 2;
			loopStart *= 2;
			loopEnd *= 2;
		}

		smp += numSamples;
	}

	if(expData.instrExtOffset != 0 && expData.instrExtEntries != 0 && file.Seek(expData.instrExtOffset))
	{
		const uint16 entries = std::min<uint16>(expData.instrExtEntries, songHeader.numSamples);
		const uint16 size = expData.instrExtEntrySize;
		for(uint16 i = 0; i < entries; i++)
		{
			MMDInstrExt instrExt;
			file.ReadStructPartial(instrExt, size);

			ModInstrument &ins = *Instruments[i + 1];
			if(instrExt.hold)
			{
				ins.VolEnv.assign({
					EnvelopeNode{0u, ENVELOPE_MAX},
					EnvelopeNode{static_cast<EnvelopeNode::tick_t>(instrExt.hold - 1), ENVELOPE_MAX},
					EnvelopeNode{static_cast<EnvelopeNode::tick_t>(instrExt.hold + (instrExt.decay ? 64u / instrExt.decay : 0u)), ENVELOPE_MIN},
				});
				if(instrExt.hold == 1)
					ins.VolEnv.erase(ins.VolEnv.begin());
				ins.nFadeOut = instrExt.decay ? (instrExt.decay * 512) : 32767;
				ins.VolEnv.dwFlags.set(ENV_ENABLED);
				needInstruments = true;
			}
			if(size > offsetof(MMDInstrExt, volume))
				ins.nGlobalVol = (instrExt.volume + 1u) / 2u;
			if(size > offsetof(MMDInstrExt, midiBank))
				ins.wMidiBank = instrExt.midiBank;
#ifdef MPT_WITH_VST
			if(ins.nMixPlug > 0)
			{
				PLUGINDEX plug = ins.nMixPlug - 1;
				auto &mixPlug = m_MixPlugins[plug];
				if(mixPlug.Info.dwPluginId2 == PLUGMAGIC('M', 'M', 'I', 'D'))
				{
					float dev = (instrExt.outputDevice + 1) / 65536.0f;  // Magic code from MidiInOut.h :(
					mixPlug.pluginData.resize(3 * sizeof(uint32));
					auto memFile = std::make_pair(mpt::as_span(mixPlug.pluginData), mpt::IO::Offset(0));
					mpt::IO::WriteIntLE<uint32>(memFile, 0);          // Plugin data type
					mpt::IO::Write(memFile, IEEE754binary32LE{0});    // Input device
					mpt::IO::Write(memFile, IEEE754binary32LE{dev});  // Output device

					// Check if we already have another plugin referencing this output device
					for(PLUGINDEX p = 0; p < plug; p++)
					{
						const auto &otherPlug = m_MixPlugins[p];
						if(otherPlug.Info.dwPluginId1 == mixPlug.Info.dwPluginId1
							&& otherPlug.Info.dwPluginId2 == mixPlug.Info.dwPluginId2
							&& otherPlug.pluginData == mixPlug.pluginData)
						{
							ins.nMixPlug = p + 1;
							mixPlug = {};
							break;
						}
					}
				}
			}
#endif  // MPT_WITH_VST

			ModSample &sample = Samples[ins.Keyboard[NOTE_MIDDLEC]];
			sample.nFineTune = MOD2XMFineTune(instrExt.finetune);

			if(size > offsetof(MMDInstrExt, loopLength))
			{
				sample.nLoopStart = instrExt.loopStart;
				sample.nLoopEnd = instrExt.loopStart + instrExt.loopLength;
			}
			if(size > offsetof(MMDInstrExt, instrFlags))
			{
				sample.uFlags.set(CHN_LOOP, (instrExt.instrFlags & MMDInstrExt::SSFLG_LOOP) != 0);
				sample.uFlags.set(CHN_PINGPONGLOOP, (instrExt.instrFlags & MMDInstrExt::SSFLG_PINGPONG) != 0);
				if(instrExt.instrFlags & MMDInstrExt::SSFLG_DISABLED)
					sample.nGlobalVol = 0;
			}
		}
	}
	if(expData.instrInfoOffset != 0 && expData.instrInfoEntries != 0 && file.Seek(expData.instrInfoOffset))
	{
		const uint16 entries = std::min<uint16>(expData.instrInfoEntries, songHeader.numSamples);
		const uint16 size = expData.instrInfoEntrySize;
		for(uint16 i = 0; i < entries; i++)
		{
			MMDInstrInfo instrInfo;
			file.ReadStructPartial(instrInfo, size);
			Instruments[i + 1]->name = mpt::String::ReadBuf(mpt::String::maybeNullTerminated, instrInfo.name);
			for(auto smp : Instruments[i + 1]->GetSamples())
			{
				m_szNames[smp] = Instruments[i + 1]->name;
			}
		}
	}

	// Setup a program change macro for command 1C (even if MIDI plugin is disabled, as otherwise these commands may act as filter commands)
	m_MidiCfg.ClearZxxMacros();
	m_MidiCfg.SFx[0] = "Cc z";

	file.Rewind();
	PATTERNINDEX basePattern = 0;
	for(SEQUENCEINDEX song = 0; song < numSongs; song++)
	{
		MEDReadNextSong(file, fileHeader, expData, songHeader);

		if(song != 0)
		{
			if(Order.AddSequence() == SEQUENCEINDEX_INVALID)
				return false;
		}

		ModSequence &order = Order(song);

		std::map<ORDERINDEX, ORDERINDEX> jumpTargets;
		order.clear();
		uint32 preamp = 32;
		if(version < 2)
		{
			if(songHeader.songLength > 256 || m_nChannels > 16)
				return false;
			ReadOrderFromArray(order, songHeader.GetMMD0Song().sequence, songHeader.songLength);
			for(auto &ord : order)
			{
				ord += basePattern;
			}

			SetupMODPanning(true);
			for(CHANNELINDEX chn = 0; chn < m_nChannels; chn++)
			{
				ChnSettings[chn].nVolume = std::min<uint8>(songHeader.trackVol[chn], 64);
			}
		} else
		{
			const MMD2Song header = songHeader.GetMMD2Song();
			if(header.numTracks < 1 || header.numTracks > 64 || m_nChannels > 64)
				return false;

			const bool freePan = (header.flags3 & MMD2Song::FLAG3_FREEPAN);
			if(header.volAdjust)
				preamp = Util::muldivr_unsigned(preamp, std::min<uint16>(header.volAdjust, 800), 100);
			if (freePan)
				preamp /= 2;

			if(file.Seek(header.trackVolsOffset))
			{
				for(CHANNELINDEX chn = 0; chn < m_nChannels; chn++)
				{
					ChnSettings[chn].nVolume = std::min<uint8>(file.ReadUint8(), 64);
				}
			}
			if(header.trackPanOffset && file.Seek(header.trackPanOffset))
			{
				for(CHANNELINDEX chn = 0; chn < m_nChannels; chn++)
				{
					ChnSettings[chn].nPan = (Clamp<int8, int8>(file.ReadInt8(), -16, 16) + 16) * 8;
				}
			} else
			{
				SetupMODPanning(true);
			}

			std::vector<uint16be> sections;
			if(!file.Seek(header.sectionTableOffset)
			   || !file.CanRead(songHeader.songLength * 2)
			   || !file.ReadVector(sections, songHeader.songLength))
				continue;

			for(uint16 section : sections)
			{
				if(section > header.numPlaySeqs)
					continue;

				file.Seek(header.playSeqTableOffset + section * 4);
				if(!file.Seek(file.ReadUint32BE()) || !file.CanRead(sizeof(MMD2PlaySeq)))
					continue;

				MMD2PlaySeq playSeq;
				file.ReadStruct(playSeq);

				if(!order.empty())
					order.push_back(order.GetIgnoreIndex());

				size_t readOrders = playSeq.length;
				if(!file.CanRead(readOrders))
					LimitMax(readOrders, file.BytesLeft());
				LimitMax(readOrders, ORDERINDEX_MAX);

				size_t orderStart = order.size();
				order.reserve(orderStart + readOrders);
				for(size_t ord = 0; ord < readOrders; ord++)
				{
					PATTERNINDEX pat = file.ReadUint16BE();
					if(pat < 0x8000)
					{
						order.push_back(basePattern + pat);
					}
				}
				if(playSeq.name[0])
					order.SetName(mpt::ToUnicode(mpt::Charset::Amiga_no_C1, mpt::String::ReadAutoBuf(playSeq.name)));

				// Play commands (jump / stop)
				if(playSeq.commandTableOffset > 0 && file.Seek(playSeq.commandTableOffset))
				{
					MMDPlaySeqCommand command;
					while(file.ReadStruct(command))
					{
						FileReader chunk = file.ReadChunk(command.extraSize);
						ORDERINDEX ord = mpt::saturate_cast<ORDERINDEX>(orderStart + command.offset);
						if(command.offset == 0xFFFF || ord >= order.size())
							break;
						if(command.command == MMDPlaySeqCommand::kStop)
						{
							order[ord] = order.GetInvalidPatIndex();
						} else if(command.command == MMDPlaySeqCommand::kJump)
						{
							jumpTargets[ord] = chunk.ReadUint16BE();
							order[ord] = order.GetIgnoreIndex();
						}
					}
				}
			}
		}

		const bool volHex = (songHeader.flags & MMDSong::FLAG_VOLHEX) != 0;
		const bool is8Ch = (songHeader.flags & MMDSong::FLAG_8CHANNEL) != 0;
		const bool bpmMode = (songHeader.flags2 & MMDSong::FLAG2_BPM) != 0;
		const uint8 rowsPerBeat = 1 + (songHeader.flags2 & MMDSong::FLAG2_BMASK);
		m_nDefaultTempo = MMDTempoToBPM(songHeader.defaultTempo, is8Ch, bpmMode, rowsPerBeat);
		m_nDefaultSpeed = Clamp<uint8, uint8>(songHeader.tempo2, 1, 32);
		if(bpmMode)
		{
			m_nDefaultRowsPerBeat = rowsPerBeat;
			m_nDefaultRowsPerMeasure = m_nDefaultRowsPerBeat * 4u;
		}

		if(songHeader.masterVol)
			m_nDefaultGlobalVolume = std::min<uint8>(songHeader.masterVol, 64) * 4;
		m_nSamplePreAmp = m_nVSTiVolume = preamp;

		// For MED, this affects both volume and pitch slides
		m_SongFlags.set(SONG_FASTVOLSLIDES, !(songHeader.flags & MMDSong::FLAG_STSLIDE));

		if(expData.songNameOffset && file.Seek(expData.songNameOffset))
		{
			file.ReadString<mpt::String::maybeNullTerminated>(m_songName, expData.songNameLength);
			if(numSongs > 1)
				order.SetName(mpt::ToUnicode(mpt::Charset::Amiga_no_C1, m_songName));
		}
		if(expData.annoLength > 1 && file.Seek(expData.annoText))
		{
			m_songMessage.Read(file, expData.annoLength - 1, SongMessage::leAutodetect);
		}

#ifdef MPT_WITH_VST
		// Read MIDI messages
		if(expData.midiDumpOffset && file.Seek(expData.midiDumpOffset) && file.CanRead(8))
		{
			uint16 numDumps = std::min(file.ReadUint16BE(), static_cast<uint16>(m_MidiCfg.Zxx.size()));
			file.Skip(6);
			if(file.CanRead(numDumps * 4))
			{
				std::vector<uint32be> dumpPointers;
				file.ReadVector(dumpPointers, numDumps);
				for(uint16 dump = 0; dump < numDumps; dump++)
				{
					if(!file.Seek(dumpPointers[dump]) || !file.CanRead(sizeof(MMDDump)))
						continue;
					MMDDump dumpHeader;
					file.ReadStruct(dumpHeader);
					if(!file.Seek(dumpHeader.dataPointer) || !file.CanRead(dumpHeader.length))
						continue;
					std::array<char, kMacroLength> macro{};
					auto length = std::min(static_cast<size_t>(dumpHeader.length), macro.size() / 2u);
					for(size_t i = 0; i < length; i++)
					{
						const uint8 byte = file.ReadUint8(), high = byte >> 4, low = byte & 0x0F;
						macro[i * 2] = high + (high < 0x0A ? '0' : 'A' - 0x0A);
						macro[i * 2 + 1] = low + (low < 0x0A ? '0' : 'A' - 0x0A);
					}
					m_MidiCfg.Zxx[dump] = std::string_view{macro.data(), length * 2};
				}
			}
		}
#endif  // MPT_WITH_VST

		if(expData.mmdInfoOffset && file.Seek(expData.mmdInfoOffset) && file.CanRead(12))
		{
			file.Skip(6);  // Next info file (unused) + reserved
			if(file.ReadUint16BE() == 1)  // ASCII text
			{
				uint32 length = file.ReadUint32BE();
				if(length && file.CanRead(length))
				{
					const auto oldMsg = std::move(m_songMessage);
					m_songMessage.Read(file, length, SongMessage::leAutodetect);
					if(!oldMsg.empty())
						m_songMessage.SetRaw(oldMsg + std::string(2, SongMessage::InternalLineEnding) + m_songMessage);
				}
			}
		}

		// Track Names
		if(version >= 2 && expData.trackInfoOffset)
		{
			for(CHANNELINDEX chn = 0; chn < m_nChannels; chn++)
			{
				if(file.Seek(expData.trackInfoOffset + chn * 4)
				   && file.Seek(file.ReadUint32BE()))
				{
					uint32 nameOffset = 0, nameLength = 0;
					while(file.CanRead(sizeof(MMDTag)))
					{
						MMDTag tag;
						file.ReadStruct(tag);
						if(tag.type == MMDTag::MMDTAG_END)
							break;
						switch(tag.type & MMDTag::MMDTAG_MASK)
						{
						case MMDTag::MMDTAG_TRK_NAME: nameOffset = tag.data; break;
						case MMDTag::MMDTAG_TRK_NAMELEN: nameLength = tag.data; break;
						}
					}
					if(nameOffset > 0 && nameLength > 0 && file.Seek(nameOffset))
					{
						file.ReadString<mpt::String::maybeNullTerminated>(ChnSettings[chn].szName, nameLength);
					}
				}
			}
		}

		PATTERNINDEX numPatterns = songHeader.numBlocks;
		Patterns.ResizeArray(basePattern + numPatterns);
		for(PATTERNINDEX pat = 0; pat < numPatterns; pat++)
		{
			if(!(loadFlags & loadPatternData)
			   || !file.Seek(fileHeader.blockArrOffset + pat * 4u)
			   || !file.Seek(file.ReadUint32BE()))
			{
				continue;
			}

			CHANNELINDEX numTracks;
			ROWINDEX numRows;
			std::string patName;
			int transpose;
			FileReader cmdExt;

			if(version < 1)
			{
				transpose = NOTE_MIN + 47;
				MMD0PatternHeader patHeader;
				file.ReadStruct(patHeader);
				numTracks = patHeader.numTracks;
				numRows = patHeader.numRows + 1;
			} else
			{
				transpose = NOTE_MIN + (version <= 2 ? 47 : 23) + songHeader.playTranspose;
				MMD1PatternHeader patHeader;
				file.ReadStruct(patHeader);
				numTracks = patHeader.numTracks;
				numRows = patHeader.numRows + 1;
				if(patHeader.blockInfoOffset)
				{
					auto offset = file.GetPosition();
					file.Seek(patHeader.blockInfoOffset);
					MMDBlockInfo blockInfo;
					file.ReadStruct(blockInfo);
					if(file.Seek(blockInfo.nameOffset))
					{
						// We have now chased four pointers to get this far... lovely format.
						file.ReadString<mpt::String::maybeNullTerminated>(patName, blockInfo.nameLength);
					}
					if(blockInfo.cmdExtTableOffset
					   && file.Seek(blockInfo.cmdExtTableOffset)
					   && file.Seek(file.ReadUint32BE()))
					{
						cmdExt = file.ReadChunk(numTracks * numRows);
					}

					file.Seek(offset);
				}
			}

			if(!Patterns.Insert(basePattern + pat, numRows))
				continue;

			CPattern &pattern = Patterns[basePattern + pat];
			pattern.SetName(patName);
			LimitMax(numTracks, m_nChannels);

			for(ROWINDEX row = 0; row < numRows; row++)
			{
				ModCommand *m = pattern.GetpModCommand(row, 0);
				for(CHANNELINDEX chn = 0; chn < numTracks; chn++, m++)
				{
					int note = NOTE_NONE;
					if(version < 1)
					{
						const auto [noteInstr, instrCmd, param] = file.ReadArray<uint8, 3>();

						if(noteInstr & 0x3F)
							note = (noteInstr & 0x3F) + transpose;

						m->instr = (instrCmd >> 4) | ((noteInstr & 0x80) >> 3) | ((noteInstr & 0x40) >> 1);

						m->command = instrCmd & 0x0F;
						m->param = param;
					} else
					{
						const auto [noteVal, instr, command, param1] = file.ReadArray<uint8, 4>();
						m->vol = cmdExt.ReadUint8();

						if(noteVal & 0x7F)
							note = (noteVal & 0x7F) + transpose;
						else if(noteVal == 0x80)
							m->note = NOTE_NOTECUT;

						m->instr = instr & 0x3F;
						m->command = command;
						m->param = param1;
					}
					// Octave wrapping for 4-channel modules (TODO: this should not be set because of synth instruments)
					if(hardwareMixSamples && note >= NOTE_MIDDLEC + 2 * 12)
						needInstruments = true;

					if(note >= NOTE_MIN && note <= NOTE_MAX)
						m->note = static_cast<ModCommand::NOTE>(note);
					ConvertMEDEffect(*m, is8Ch, bpmMode, rowsPerBeat, volHex);
				}
			}
		}

		// Fix jump order commands
		for(const auto & [from, to] : jumpTargets)
		{
			PATTERNINDEX pat;
			if(from > 0 && order.IsValidPat(from - 1))
			{
				pat = order.EnsureUnique(from - 1);
			} else
			{
				if(to == from + 1)  // No action required
					continue;
				pat = Patterns.InsertAny(1);
				if(pat == PATTERNINDEX_INVALID)
					continue;
				order[from] = pat;
			}
			Patterns[pat].WriteEffect(EffectWriter(CMD_POSITIONJUMP, mpt::saturate_cast<ModCommand::PARAM>(to)).Row(Patterns[pat].GetNumRows() - 1).RetryPreviousRow());
			if(pat >= numPatterns)
				numPatterns = pat + 1;
		}

		basePattern += numPatterns;
		
		if(!expData.nextModOffset || !file.Seek(expData.nextModOffset))
			break;
	}
	Order.SetSequence(0);

	if(!needInstruments)
	{
		for(INSTRUMENTINDEX ins = 1; ins <= m_nInstruments; ins++)
		{
			delete Instruments[ins];
			Instruments[ins] = nullptr;
		}
		m_nInstruments = 0;
	}

	if(anySynthInstrs)
		AddToLog(LogWarning, U_("Synthesized MED instruments are not supported."));

	const mpt::uchar *madeWithTracker = MPT_ULITERAL("");
	switch(version)
	{
	case 0: madeWithTracker = m_nChannels > 4 ? MPT_ULITERAL("OctaMED v2.10 (MMD0)") : MPT_ULITERAL("MED v2 (MMD0)"); break;
	case 1: madeWithTracker = MPT_ULITERAL("OctaMED v4 (MMD1)"); break;
	case 2: madeWithTracker = MPT_ULITERAL("OctaMED v5 (MMD2)"); break;
	case 3: madeWithTracker = MPT_ULITERAL("OctaMED Soundstudio (MMD3)"); break;
	}

	m_modFormat.formatName = MPT_UFORMAT("OctaMED (MMD{})")(version);
	m_modFormat.type = MPT_USTRING("med");
	m_modFormat.madeWithTracker = madeWithTracker;
	m_modFormat.charset = mpt::Charset::Amiga_no_C1;

	return true;
}

OPENMPT_NAMESPACE_END