-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unkrawerter.cpp
1787 lines (1740 loc) · 88.9 KB
/
unkrawerter.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
/*
* UnkrawerterGBA
* Version 4.0
*
* This program automatically extracts music files from Game Boy Advance games
* that use the Krawall sound engine. Audio files are extracted in the XM or S3M
* module format, which can be opened by programs such as OpenMPT.
*
* Copyright (c) 2020-2022 JackMacWindows.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
#include <tuple>
#include <algorithm>
#include <string>
#include <algorithm>
#include <map>
// Maps type numbers detected in searchForOffsets to strings for display (only used in verbose mode)
static const char * typemap[] = {
"unknown",
"module",
"sample",
"module or sample",
"instrument",
"instrument or module",
"instrument or sample",
"any"
};
// Stores the Krawall version (used to determine some conversion parameters)
// This defaults to the latest version, but ROMs using versions before 2004-07-07 MUST set this
static uint32_t version = 0x20050421;
// Structure to hold results of offset search
struct OffsetSearchResult {
bool success = false;
uint32_t instrumentAddr = 0;
uint32_t instrumentCount = 0;
uint32_t sampleAddr = 0;
uint32_t sampleCount = 0;
std::vector<uint32_t> modules;
};
void unkrawerter_setVersion(uint32_t ver) {
version = ver;
}
// Searches a ROM file pointer for offsets to modules, an instrument list, and a sample list.
// This looks for sets of 4-byte aligned addresses in the form 0x08xxxxxx or 0x09xxxxxx
// Once the sets are found, their types are determined by dereferencing the addresses and checking
// whether the data stored therein is consistent with the structure type.
// Sets that don't match exactly one type are discarded.
// Returns a structure with the addresses to the instrument & sample lists, as well as all modules.
OffsetSearchResult unkrawerter_searchForOffsets(FILE* fp, int threshold = 4, bool verbose = false) {
OffsetSearchResult retval;
fseek(fp, 0, SEEK_END);
uint32_t romSize = ftell(fp); // Store the ROM's size so addresses that go over are ignored
rewind(fp);
std::vector<std::tuple<uint32_t, uint32_t, int> > foundAddressLists;
uint32_t startAddress = 0, count = 0;
// Look for lists of pointers (starting with 0x08xxxxxx or 0x09xxxxxx)
uint32_t lastDword = 0;
while (!feof(fp) && !ferror(fp)) {
fread(&lastDword, 4, 1, fp);
if ((lastDword & 0x08000000) && !(lastDword & 0xF6000000) && (lastDword & 0x1ffffff) < romSize && lastDword != 0x08080808 && !((uint16_t)(lastDword >> 16) - (uint16_t)(lastDword & 0xffff) < 4 && (lastDword & 0x00ff00ff) == 0x00080008)) {
// Count this address in a set
if (startAddress == 0 || count == 0) startAddress = ftell(fp) - 4;
count++;
} else if (count >= threshold && count < 1024) {
// We found an address list, add it to the results
foundAddressLists.push_back(std::make_tuple(startAddress, count, 0));
startAddress = 0;
count = 0;
} else if (count > 0) {
// Ignore this address (list)
startAddress = count = 0;
}
}
// Erase a few matches
foundAddressLists.erase(std::remove_if(foundAddressLists.begin(), foundAddressLists.end(), [fp](std::tuple<uint32_t, uint32_t, int>& addr)->bool {
// Check for addresses that are too close together
int numsize = std::min(std::get<1>(addr), 4u);
uint32_t nums[4];
fseek(fp, std::get<0>(addr), SEEK_SET);
for (int i = 0; i < numsize; i++) fread(nums + i, 4, 1, fp);
for (int i = 1; i < numsize; i++) if ((int32_t)nums[i] - (int32_t)nums[i-1] < 0x10) return true;
return false;
}), foundAddressLists.end());
// Find the type of each match
std::for_each(foundAddressLists.begin(), foundAddressLists.end(), [fp](std::tuple<uint32_t, uint32_t, int> &p) {
int possible_mask = 0b111;
do { // Check for module
fseek(fp, std::get<0>(p) - 8, SEEK_SET);
uint32_t tmp = fgetc(fp);
if (tmp == 0 || tmp > 0x10) {possible_mask &= 0b110; break;}
tmp = fgetc(fp);
if (tmp < 30) {possible_mask &= 0b110; break;} // tweak this?
for (int i = 0; i < 5; i++) if (fgetc(fp) & 0xfe) {possible_mask &= 0b110; break;}
if (!(possible_mask & 1)) break;
if (fgetc(fp)) {possible_mask &= 0b110; break;}
fread(&tmp, 4, 1, fp);
fseek(fp, tmp & 0x1ffffff, SEEK_SET);
if (fgetc(fp) || fgetc(fp)) {possible_mask &= 0b110; break;}
fgetc(fp);
if (fgetc(fp)) {possible_mask &= 0b110; break;}
fseek(fp, 28, SEEK_CUR);
uint16_t tmp2 = 0;
if (version < 0x20040707) tmp2 = fgetc(fp);
else fread(&tmp2, 2, 1, fp);
if (tmp2 > 256 || (tmp2 & 7)) {possible_mask &= 0b110; break;}
} while (0);
if (std::get<1>(p) < 4) possible_mask &= 0b001;
else {
for (int i = 0; i < std::min(std::get<1>(p), 4u); i++) { // Check for sample
fseek(fp, std::get<0>(p) + i*4, SEEK_SET);
uint32_t addr = 0;
fread(&addr, 4, 1, fp);
fseek(fp, addr & 0x1ffffff, SEEK_SET);
uint32_t tmp = 0, end = 0;
fread(&tmp, 4, 1, fp);
fread(&end, 4, 1, fp);
if (!(end & 0x08000000) || (end & 0xf6000000) || end <= addr + 18 || tmp > end - addr - 18) {possible_mask &= 0b101; break;}
fread(&tmp, 4, 1, fp);
if (tmp > 0xFFFFF) {possible_mask &= 0b101; break;}
fseek(fp, 4, SEEK_CUR);
if ((fgetc(fp) & 0xfe) || (fgetc(fp) & 0xfe)) {possible_mask &= 0b101; break;}
}
for (int n = 0; n < std::min(std::get<1>(p), 4u); n++) { // Check for instrument
fseek(fp, std::get<0>(p) + n*4, SEEK_SET);
uint32_t addr = 0;
fread(&addr, 4, 1, fp);
fseek(fp, addr & 0x1ffffff, SEEK_SET);
uint16_t tmp = 0, last = 0;
for (int i = 0; i < 96; i++) {
fread(&tmp, 2, 1, fp);
if ((tmp > 256 || (i > 0 && abs((int32_t)tmp - (int32_t)last) > 16)) && i < 94) {possible_mask &= 0b011; break;}
last = tmp;
}
if (!(possible_mask & 4)) break;
fseek(fp, 48, SEEK_CUR);
fgetc(fp); //if (fgetc(fp) > 12) {possible_mask &= 0b011; break;}
if (fgetc(fp) > 12) {possible_mask &= 0b011; break;}
if (fgetc(fp) > 12) {possible_mask &= 0b011; break;}
fgetc(fp); //if (fgetc(fp) > 0x10) {possible_mask &= 0b011; break;} // I think?
fseek(fp, 48, SEEK_CUR);
fgetc(fp); //if (fgetc(fp) > 12) {possible_mask &= 0b011; break;}
if (fgetc(fp) > 12) {possible_mask &= 0b011; break;}
if (fgetc(fp) > 12) {possible_mask &= 0b011; break;}
fgetc(fp); //if (fgetc(fp) > 0x10) {possible_mask &= 0b011; break;}
}
}
std::get<2>(p) = possible_mask;
});
// Show results if verbose
if (verbose) std::for_each(foundAddressLists.begin(), foundAddressLists.end(), [](std::tuple<uint32_t, uint32_t, int> p){printf("Found %d matches at %08X with type %s\n", std::get<1>(p), std::get<0>(p), typemap[std::get<2>(p)]);});
// Filter results down to one instrument & sample list, and all modules
for (auto p : foundAddressLists) {
if (std::get<2>(p) == 1) retval.modules.push_back(std::get<0>(p));
else if (std::get<2>(p) == 2 && std::get<1>(p) > retval.sampleCount) {retval.sampleCount = std::get<1>(p); retval.sampleAddr = std::get<0>(p);}
else if (std::get<2>(p) == 4 && std::get<1>(p) > retval.instrumentCount) {retval.instrumentCount = std::get<1>(p); retval.instrumentAddr = std::get<0>(p);}
}
// Show brief of results
if (retval.instrumentAddr) printf("> Found instrument list at address %08X\n", retval.instrumentAddr);
if (retval.sampleAddr) printf("> Found sample list at address %08X\n", retval.sampleAddr);
for (int i = 0; i < retval.modules.size(); i++) {
retval.modules[i] = (retval.modules[i] & 0x1ffffff) - 364;
printf("> Found module at address %08X\n", retval.modules[i]);
}
retval.success = retval.sampleAddr && !retval.modules.empty();
return retval;
}
// Reads a Krawall sample from a ROM and writes it to a WAV file
void unkrawerter_readSampleToWAV(FILE* fp, uint32_t offset, const char * filename) {
fseek(fp, offset, SEEK_SET);
unsigned long loopLength = 0, end = 0;
fread(&loopLength, 4, 1, fp);
fread(&end, 4, 1, fp);
end &= 0x1ffffff;
unsigned long currentSize = end - ftell(fp) - 10;
FILE* wav = fopen(filename, "wb");
fwrite("RIFF", 4, 1, wav);
unsigned long sampleRate = 0;
fread(&sampleRate, 4, 1, fp);
for (int i = 0; i < 6; i++) fgetc(fp);
unsigned long currentOffset = ftell(fp);
unsigned long size = end - currentOffset + 18;
fwrite(&size, 4, 1, wav);
fwrite("WAVEfmt \x10\0\0\0\x01\0\x01\0", 16, 1, wav);
fwrite(&sampleRate, 4, 1, wav);
fwrite(&sampleRate, 4, 1, wav);
fwrite("\x01\0\x08\0data", 8, 1, wav);
size -= 36;
fwrite(&size, 4, 1, wav);
char * data = (char*)malloc(size);
fread(data, 1, size, fp);
fwrite(data, 1, size, wav);
fclose(wav);
}
// Taken from Krawall's mtypes.h file
extern "C" {
#ifdef _MSC_VER
#pragma pack(push, 1)
#define PACKED
#endif
#ifdef __GNUC__
#define PACKED __attribute__ ((packed))
#endif
typedef struct PACKED {
uint32_t loopLength;
uint32_t size;
uint32_t c2Freq;
signed char fineTune;
signed char relativeNote;
unsigned char volDefault;
signed char panDefault;
unsigned char loop;
unsigned char hq;
signed char data[1];
} Sample;
typedef struct PACKED {
unsigned short coord, inc;
} EnvNode;
typedef struct PACKED {
EnvNode nodes[ 12 ];
unsigned char max;
unsigned char sus;
unsigned char loopStart;
unsigned char flags;
} Envelope;
typedef struct PACKED {
unsigned short samples[ 96 ];
Envelope envVol;
Envelope envPan;
unsigned short volFade;
unsigned char vibType;
unsigned char vibSweep;
unsigned char vibDepth;
unsigned char vibRate;
} Instrument;
typedef struct PACKED {
unsigned short length; // custom
unsigned short s3mlength; // custom
unsigned short index[ 16 ];
unsigned short rows;
unsigned char data[1];
} Pattern;
typedef struct PACKED {
unsigned char channels;
unsigned char numOrders;
unsigned char songRestart;
unsigned char order[ 256 ];
signed char channelPan[ 32 ];
unsigned char songIndex[ 64 ];
unsigned char volGlobal;
unsigned char initSpeed;
unsigned char initBPM;
unsigned char flagInstrumentBased;
unsigned char flagLinearSlides;
unsigned char flagVolSlides;
unsigned char flagVolOpt;
unsigned char flagAmigaLimits;
unsigned char ___padding;
const Pattern* patterns[1];
} Module;
#ifdef _MSC_VER
#pragma pack(pop)
#endif
#ifdef PACKED
#undef PACKED
#endif
}
// Read a pattern from a file pointer to a Pattern structure pointer
static Pattern * readPatternFile(FILE* fp, uint32_t offset, bool use2003format, bool isRipped) {
fseek(fp, offset + 32, SEEK_SET);
std::vector<uint8_t> fileContents;
unsigned short rows = 0;
unsigned short s3mlength = 0;
if (use2003format && !isRipped) rows = fgetc(fp);
else fread(&rows, 2, 1, fp);
// We don't need to do full decoding; decode just enough to understand the size of the pattern
for (int row = 0; row < rows; row++) {
for (;;) {
unsigned char follow = fgetc(fp);
s3mlength++;
fileContents.push_back(follow);
if (!follow) break;
if (follow & 0x20) {
unsigned char note = fgetc(fp);
fileContents.push_back(note);
fileContents.push_back(fgetc(fp));
s3mlength += 2;
if (!use2003format && (note & 0x80)) fileContents.push_back(fgetc(fp));
}
if (follow & 0x40) {
fileContents.push_back(fgetc(fp));
s3mlength++;
}
if (follow & 0x80) {
fileContents.push_back(fgetc(fp));
fileContents.push_back(fgetc(fp));
s3mlength += 2;
}
}
}
fseek(fp, offset, SEEK_SET);
Pattern * retval = (Pattern*)malloc(38 + fileContents.size());
retval->s3mlength = s3mlength;
retval->length = fileContents.size();
fread(retval->index, 2, 16, fp);
fseek(fp, 2, SEEK_CUR);
retval->rows = rows;
memcpy(retval->data, &fileContents[0], fileContents.size());
return retval;
}
// Read a module from a file pointer to a Module structure pointer
// This reads all its patterns as well
static Module * readModuleFile(FILE* fp, uint32_t offset) {
Module * retval = (Module*)malloc(sizeof(Module));
memset(retval, 0, sizeof(Module));
fseek(fp, offset, SEEK_SET);
fread(retval, 364, 1, fp);
unsigned char maxPattern = 0;
for (int i = 0; i < retval->numOrders; i++) if (retval->order[i] != 254) maxPattern = std::max(maxPattern, retval->order[i]);
Module * retval2 = (Module*)malloc(sizeof(Module) + sizeof(Pattern*) * (maxPattern + 1));
memcpy(retval2, retval, sizeof(Module));
uint32_t addr = 0;
for (int i = 0; i <= maxPattern; i++) {
fseek(fp, offset + 364 + i*4, SEEK_SET);
fread(&addr, 4, 1, fp);
if (offset != 4 && !(addr & 0x08000000) || (addr & 0xf6000000)) break;
retval2->patterns[i] = readPatternFile(fp, addr & 0x1ffffff, version < 0x20040707, offset == 4);
}
return retval2;
}
// Read an instrument from a file pointer to an Instrument structure
static Instrument readInstrumentFile(FILE* fp, uint32_t offset) {
fseek(fp, offset, SEEK_SET);
Instrument retval;
fread(&retval, sizeof(retval), 1, fp);
// There's a chance that one of the high bytes in the sample number list gets set to some random (?) value
// I've experienced this in Cocoto games, where one of the high notes' samples has the low byte the same as the others,
// but the high byte is set to some really high value (like 0x98).
// I'm not sure why this is, but we'll try to fix it anyway.
for (int i = 0; i < 96; i++) {
if ((retval.samples[i] & 0xff00) != 0 && (i > 0 ? (retval.samples[i] & 0xff) == (retval.samples[i-1] & 0xff) : true) && (i < 95 ? (retval.samples[i] & 0xff) == (retval.samples[i+1] & 0xff) : true)) {
retval.samples[i] &= 0xff;
}
}
return retval;
}
// Read a sample from a file pointer to a Sample structure pointer
static Sample * readSampleFile(FILE* fp, uint32_t offset) {
fseek(fp, offset + 4, SEEK_SET);
uint32_t size = 0;
fread(&size, 4, 1, fp);
size &= 0x1ffffff;
size -= offset;
fseek(fp, offset, SEEK_SET);
Sample * retval = (Sample*)malloc(size);
memset(retval, 0, size);
fread(retval, size, 1, fp);
retval->size = size - 18;
return retval;
}
// Stores note data while converting
typedef struct {
unsigned char xmflag;
unsigned char note, volume, effect, effectop;
unsigned short instrument;
} Note;
// Quick function to repeatedly put a character
inline void fputcn(int c, int num, FILE* fp) {for (; num > 0; num--) fputc(c, fp);}
// Effect map to convert Krawall effects to XM effects
// (effect . effectop) = first | (effectop & second)
// If first == 0xFFFF: ignore
// Some effects must be converted from S3M syntax to XM syntax.
// Some effects are only supported in S3M files, and are not converted.
// Some effects are only supported in MPT/OpenMPT, and may not play properly on other trackers.
const std::pair<unsigned short, unsigned char> effectMap_xm[] = {
{0xFFFF, 0xFF},
{0x0F00, 0xFF}, // EFF_SPEED
{0x0F00, 0xFF}, // EFF_BPM
{0x0F00, 0xFF}, // EFF_SPEEDBPM
{0x0B00, 0xFF}, // EFF_PATTERN_JUMP
{0x0D00, 0xFF}, // EFF_PATTERN_BREAK 5
{0x0A00, 0xFF}, // EFF_VOLSLIDE_S3M (S3M!)
{0x0A00, 0xFF}, // EFF_VOLSLIDE_XM
{0x0EB0, 0x0F}, // EFF_VOLSLIDE_DOWN_XM_FINE
{0x0EA0, 0x0F}, // EFF_VOLSLIDE_UP_XM_FINE
{0x0200, 0xFF}, // EFF_PORTA_DOWN_XM 10
{0x0200, 0xFF}, // EFF_PORTA_DOWN_S3M (S3M!)
{0x0E20, 0x0F}, // EFF_PORTA_DOWN_XM_FINE
{0x2120, 0x0F}, // EFF_PORTA_DOWN_XM_EFINE
{0x0100, 0xFF}, // EFF_PORTA_UP_XM
{0x0100, 0xFF}, // EFF_PORTA_UP_S3M 15 (S3M!)
{0x0E10, 0x0F}, // EFF_PORTA_UP_XM_FINE
{0x2110, 0x0F}, // EFF_PORTA_UP_XM_EFINE
{0x0C00, 0xFF}, // EFF_VOLUME
{0x0300, 0xFF}, // EFF_PORTA_NOTE
{0x0400, 0xFF}, // EFF_VIBRATO 20
{0x1D00, 0xFF}, // EFF_TREMOR
{0x0000, 0xFF}, // EFF_ARPEGGIO
{0x0600, 0xFF}, // EFF_VOLSLIDE_VIBRATO
{0x0500, 0xFF}, // EFF_VOLSLIDE_PORTA
{0xFFFF, 0xFF}, // EFF_CHANNEL_VOL 25 (S3M!)
{0xFFFF, 0xFF}, // EFF_CHANNEL_VOLSLIDE (S3M!)
{0x0900, 0xFF}, // EFF_OFFSET
{0x1900, 0xFF}, // EFF_PANSLIDE
{0x1B00, 0xFF}, // EFF_RETRIG
{0x0700, 0xFF}, // EFF_TREMOLO 30
{0xFFFF, 0xFF}, // EFF_FVIBRATO (S3M!)
{0x1000, 0xFF}, // EFF_GLOBAL_VOL
{0x1100, 0xFF}, // EFF_GLOBAL_VOLSLIDE
{0x0800, 0xFF}, // EFF_PAN
{0x2200, 0xFF}, // EFF_PANBRELLO 35 (MPT!)
{0xFFFF, 0xFF}, // EFF_MARK
{0x0E30, 0x0F}, // EFF_GLISSANDO
{0x0E40, 0x0F}, // EFF_WAVE_VIBR
{0x0E70, 0x0F}, // EFF_WAVE_TREMOLO
{0x2150, 0x0F}, // EFF_WAVE_PANBRELLO 40 (MPT!)
{0x2160, 0x0F}, // EFF_PATTERN_DELAYF (!)
{0x0E80, 0x0F}, // EFF_OLD_PAN (!) converted to EFF_PAN
{0x0E60, 0x0F}, // EFF_PATTERN_LOOP
{0x0EC0, 0x0F}, // EFF_NOTE_CUT
{0x0ED0, 0x0F}, // EFF_NOTE_DELAY 45
{0x0EE0, 0x0F}, // EFF_PATTERN_DELAY (*)
{0x1500, 0xFF}, // EFF_ENV_SETPOS
{0xFFFF, 0xFF}, // EFF_OFFSET_HIGH
{0x0600, 0xFF}, // EFF_VOLSLIDE_VIBRATO_XM
{0x0500, 0xFF} // EFF_VOLSLIDE_PORTA_XM 50
};
// Same for S3M effects
const std::pair<unsigned short, unsigned char> effectMap_s3m[] = {
{0xFF00, 0x00},
{0x0100, 0xFF}, // A: EFF_SPEED
{0x1400, 0xFF}, // T: EFF_BPM
{0xFF00, 0xFF}, // -: EFF_SPEEDBPM
{0x0200, 0xFF}, // B: EFF_PATTERN_JUMP
{0x0300, 0xFF}, // C: EFF_PATTERN_BREAK 5
{0x0400, 0xFF}, // D: EFF_VOLSLIDE_S3M
{0x0400, 0xFF}, // D: EFF_VOLSLIDE_XM
{0x04F0, 0x0F}, // D: EFF_VOLSLIDE_DOWN_XM_FINE
{0x040F, 0xF0}, // D: EFF_VOLSLIDE_UP_XM_FINE
{0x0500, 0xFF}, // E: EFF_PORTA_DOWN_XM 10
{0x0500, 0xFF}, // E: EFF_PORTA_DOWN_S3M
{0x05F0, 0x0F}, // E: EFF_PORTA_DOWN_XM_FINE
{0x05E0, 0x0F}, // E: EFF_PORTA_DOWN_XM_EFINE
{0x0600, 0xFF}, // F: EFF_PORTA_UP_XM
{0x0600, 0xFF}, // F: EFF_PORTA_UP_S3M 15
{0x06F0, 0x0F}, // F: EFF_PORTA_UP_XM_FINE
{0x06E0, 0x0F}, // F: EFF_PORTA_UP_XM_EFINE
{0xFF00, 0x00}, // -: EFF_VOLUME (XM!)
{0x0700, 0xFF}, // G: EFF_PORTA_NOTE
{0x0800, 0xFF}, // H: EFF_VIBRATO 20
{0x0900, 0xFF}, // I: EFF_TREMOR
{0x0A00, 0xFF}, // J: EFF_ARPEGGIO
{0x0B00, 0xFF}, // K: EFF_VOLSLIDE_VIBRATO
{0x0C00, 0xFF}, // L: EFF_VOLSLIDE_PORTA
{0x0D00, 0xFF}, // M: EFF_CHANNEL_VOL 25
{0x0E00, 0xFF}, // N: EFF_CHANNEL_VOLSLIDE
{0x0F00, 0xFF}, // O: EFF_OFFSET
{0x1000, 0xFF}, // P: EFF_PANSLIDE
{0x1100, 0xFF}, // Q: EFF_RETRIG
{0x1200, 0xFF}, // R: EFF_TREMOLO 30
{0x1500, 0xFF}, // U: EFF_FVIBRATO
{0x1600, 0xFF}, // V: EFF_GLOBAL_VOL
{0x1700, 0xFF}, // W: EFF_GLOBAL_VOLSLIDE
{0x1800, 0xFF}, // X: EFF_PAN
{0x1900, 0xFF}, // Y: EFF_PANBRELLO 35 (MPT!)
{0xFF00, 0x00}, // -: EFF_MARK (KRW!)
{0x1310, 0x0F}, // S: EFF_GLISSANDO
{0x1330, 0x0F}, // S: EFF_WAVE_VIBR
{0x1340, 0x0F}, // S: EFF_WAVE_TREMOLO
{0x1350, 0x0F}, // S: EFF_WAVE_PANBRELLO 40 (MPT!)
{0x1360, 0x0F}, // S: EFF_PATTERN_DELAYF (!)
{0x1380, 0x0F}, // S: EFF_OLD_PAN (!) converted to EFF_PAN
{0x13B0, 0x0F}, // S: EFF_PATTERN_LOOP
{0x13C0, 0x0F}, // S: EFF_NOTE_CUT
{0x13D0, 0x0F}, // S: EFF_NOTE_DELAY 45
{0x13E0, 0x0F}, // S: EFF_PATTERN_DELAY (*)
{0xFF00, 0x00}, // -: EFF_ENV_SETPOS (XM!)
{0x13A0, 0xFF}, // S: EFF_OFFSET_HIGH
{0x0B00, 0xFF}, // K: EFF_VOLSLIDE_VIBRATO_XM
{0x0C00, 0xFF} // L: EFF_VOLSLIDE_PORTA_XM 50
};
// Structure to hold a few per-channel memory things
struct channel_memory {
unsigned char s3m;
unsigned char pan;
int porta;
unsigned short instrument;
};
// Writes a module from a file pointer to a new XM file.
// XM file format from http://web.archive.org/web/20060809013752/http://pipin.tmd.ns.ac.yu/extra/fileformat/modules/xm/xm.txt
int unkrawerter_writeModuleToXM(FILE* fp, uint32_t moduleOffset, const std::vector<uint32_t> &sampleOffsets, const std::vector<uint32_t> &instrumentOffsets, const char * filename, bool trimInstruments = true, const char * name = NULL, bool fixCompatibility = true, FILE* instfp = NULL) {
if (instfp == NULL) instfp = fp;
// Die if there are too many instruments for XM & we're not trimming instruments
if (instrumentOffsets.size() > 255 && !trimInstruments) {
fprintf(stderr, "Error: This module cannot be ripped without trimming instruments.\n");
return 10;
}
// Open the XM file
FILE* out = fopen(filename, "wb");
if (out == NULL) {
fprintf(stderr, "Error: Could not open output file %s for writing.\n", filename);
return 2;
}
// Read the module from the file
Module * mod = readModuleFile(fp, moduleOffset);
int markerAdd = 0;
for (int i = 0; i < mod->numOrders; i++) {
mod->order[i] = mod->order[i+markerAdd];
while (mod->order[i] == 254) {markerAdd++; mod->order[i] = mod->order[i+markerAdd];}
}
mod->numOrders -= markerAdd;
unsigned char patternCount = 0;
for (int i = 0; i < mod->numOrders; i++) patternCount = std::max(patternCount, mod->order[i]);
patternCount++;
if (mod->flagInstrumentBased && instrumentOffsets.empty()) {
fprintf(stderr, "Error: Could not find all of the offsets required.\n * Does the ROM use the Krawall engine?\n * Try adjusting the search threshold.\n * You may need to find offsets yourself.\n");
for (int i = 0; i < patternCount; i++) free((void*)mod->patterns[i]);
free(mod);
fclose(out);
return 3;
}
// Write the XM header info
if (name == NULL) fwrite("Extended Module: Krawall conversion \032UnkrawerterGBA \x04\x01\x14\x01\0\0", 1, 64, out);
else {
fwrite("Extended Module: ", 1, 17, out);
fwrite(name, 1, std::min(strlen(name), (size_t)20), out);
for (int i = std::min(strlen(name), (size_t)20); i < 20; i++) fputc(' ', out);
fwrite("\032UnkrawerterGBA \x04\x01\x14\x01\0\0", 1, 27, out);
}
fputc(mod->numOrders, out);
fputc(0, out); // 1-byte padding
fputc(mod->songRestart, out);
fputc(0, out); // 1-byte padding
fputc(mod->channels, out);
fputc(0, out); // 2-byte padding
unsigned short pnum = patternCount;
fwrite(&pnum, 2, 1, out);
uint32_t instrumentSizePos = ftell(out); // we'll get back to this later
if (trimInstruments) fputcn(0, 2, out);
else {pnum = mod->flagInstrumentBased ? instrumentOffsets.size() : sampleOffsets.size(); fwrite(&pnum, 2, 1, out);}
fputc((mod->flagLinearSlides ? 1 : 0), out);
fputc(0, out); // 2-byte padding
fputc(mod->initSpeed, out);
fputc(0, out); // 2-byte padding
fputc(mod->initBPM, out);
fputc(0, out); // 2-byte padding
fwrite(mod->order, 1, 256, out);
std::vector<unsigned short> instrumentList; // used to hold the instruments used so we can remove unnecessary instruments
std::map<unsigned short, std::vector<std::pair<unsigned char, unsigned long> > > sampleOffsetList; // used to hold on to sample offset effects that may need fixing
// Write each pattern
for (int i = 0; i < patternCount; i++) {
// Write pattern header
fputc(9, out);
fputcn(0, 4, out); // 4-byte padding + packing type (always 0)
fwrite(&mod->patterns[i]->rows, 2, 1, out);
uint32_t sizePos = ftell(out); // Save the position so we can come back to write the size
fputcn(0, 2, out); // placeholder, we'll come back to this
// Convert the Krawall data into XM data
const unsigned char * data = mod->patterns[i]->data;
Note * thisrow = (Note*)calloc(mod->channels, sizeof(Note)); // stores the current row's notes
unsigned char warnings = 0; // for S3M/MPT warnings, we only warn once per pattern
struct channel_memory * memory = new struct channel_memory[mod->channels]; // to store memory for various patches
for (int i = 0; i < mod->channels; i++) {
memory[i].s3m = 0;
memory[i].porta = 0;
memory[i].pan = 0x80;
memory[i].instrument = 0;
}
unsigned char speed = mod->initSpeed; // to help portamento
for (int row = 0; row < mod->patterns[i]->rows; row++) {
memset(thisrow, 0, sizeof(Note) * mod->channels); // Zero so we can check the values for 0 later
for (;;) {
// Read the channel/next byte types
unsigned char follow = *data++;
if (!follow) break; // If it's 0, the row's done
unsigned char xmflag = 0x80; // Stores the next byte types in XM format
int channel = follow & 0x1f;
unsigned char note = 0, volume = 0, effect = 0, effectop = 0;
unsigned short instrument = 0;
if (follow & 0x20) { // Note & instrument follows
xmflag |= 0x03;
note = *data++;
instrument = *data++;
if (version < 0x20040707) { // For versions before 2004-07-07, note is high 7 bits & instrument is low 9 bits
instrument |= (note & 1) << 8;
note >>= 1;
} else if (note & 0x80) { // For versions starting with 2004-07-07, if the note > 128, the instrument field is 2 bytes long
instrument |= *data++ << 8;
note &= 0x7f;
}
if (note > 97 || note == 0) note = 97;
}
if (follow & 0x40) { // Volume follows
xmflag |= 0x04;
volume = *data++;
}
if (follow & 0x80) { // Effect follows
xmflag |= 0x18;
effect = *data++;
effectop = *data++;
// Convert the Krawall effect into an XM effect
unsigned short xmeffect = effectMap_xm[effect].first;
unsigned char effectmask = effectMap_xm[effect].second;
if (xmeffect == 0xFFFF) { // Ignored
xmflag &= ~0x18;
effect = 0;
effectop = 0;
} else if (effect == 6) { // S3M volume slide
if (effectop == 0 && memory[channel].s3m) effectop = memory[channel].s3m;
memory[channel].s3m = effectop;
if ((effectop & 0xF0) == 0xF0) { // fine decrease
effect = 0x0E;
effectop = 0xB0 | (effectop & 0x0F);
} else if ((effectop & 0x0F) == 0x0F && effectop != 0x0F) { // fine increase (note: 0x0F means normal slide)
effect = 0x0E;
effectop = 0xA0 | (effectop >> 4);
} else { // normal volume slide
effect = 0x0A;
}
} else if (effect == 11) { // S3M porta down
if (effectop == 0 && memory[channel].s3m) effectop = memory[channel].s3m;
memory[channel].s3m = effectop;
if ((effectop & 0xF0) == 0xF0) { // fine
effect = 0x0E;
effectop = 0x20 | (effectop & 0x0F);
} else if ((effectop & 0xF0) == 0xE0) { // extra fine
effect = 0x21;
effectop = 0x20 | (effectop & 0x0F);
} else { // normal
effect = 0x02;
}
} else if (effect == 15) { // S3M porta up
if (effectop == 0 && memory[channel].s3m) effectop = memory[channel].s3m;
memory[channel].s3m = effectop;
if ((effectop & 0xF0) == 0xF0) { // fine
effect = 0x0E;
effectop = 0x10 | (effectop & 0x0F);
} else if ((effectop & 0xF0) == 0xE0) { // extra fine
effect = 0x21;
effectop = 0x10 | (effectop & 0x0F);
} else { // normal
effect = 0x01;
}
} else if (effect == 23) { // S3M volume slide + vibrato
if (effectop == 0 && memory[channel].s3m) effectop = memory[channel].s3m;
memory[channel].s3m = effectop;
// XM doesn't have a fine Vol+Vib command, so put the volume slide command in the volume column & vibrato in the effects column
if ((effectop & 0xF0) == 0xF0) { // fine decrease
if (!(xmflag & 0x04)) {xmflag |= 0x04; volume = 0x80 | (effectop & 0x0F);}
effect = 0x04;
effectop = 0;
} else if ((effectop & 0x0F) == 0x0F) { // fine increase
if (!(xmflag & 0x04)) {xmflag |= 0x04; volume = 0x90 | (effectop >> 4);}
effect = 0x04;
effectop = 0;
} else { // normal volume slide + vibrato
effect = 0x06;
}
} else if (effect == 24) { // S3M volume slide + porta
if (effectop == 0 && memory[channel].s3m) effectop = memory[channel].s3m;
memory[channel].s3m = effectop;
// XM doesn't have a fine Vol+Porta command, so put the volume slide command in the volume column & portamento in the effects column
if ((effectop & 0xF0) == 0xF0) { // fine decrease
if (!(xmflag & 0x04)) {xmflag |= 0x04; volume = 0x80 | (effectop & 0x0F);}
effect = 0x03;
effectop = 0;
} else if ((effectop & 0x0F) == 0x0F) { // fine increase
if (!(xmflag & 0x04)) {xmflag |= 0x04; volume = 0x90 | (effectop >> 4);}
effect = 0x03;
effectop = 0;
} else { // normal volume slide + portamento
effect = 0x06;
}
} else if (effect == 25 || effect == 26 || effect == 31 || (effect == 1 && (effectop >= 0x20 || effectop == 0))) { // Unsupported S3M effects
if (!(warnings & 0x02) && !(effect == 1 && effectop == 0)) {warnings |= 0x02; fprintf(stderr, "Warning: Pattern %d uses an S3M effect that isn't compatible with XM. It will not play correctly.\n", i);}
xmflag &= ~0x18;
effect = 0;
effectop = 0;
} else { // Other effects
// Warn if MPT-only
if ((effect == 35 || effect == 40) && !(warnings & 0x01)) {warnings |= 0x01; fprintf(stderr, "Warning: Pattern %d uses an effect specific to OpenMPT. It may not play correctly in other trackers.\n", i);}
if (effect == 1 || effect == 3) speed = effectop;
if (effect == 29 && (effectop & 0xF0) == 0x00) effectop |= 0x80;
xmeffect = xmeffect | (effectop & effectmask);
effect = xmeffect >> 8;
effectop = xmeffect & 0xFF;
}
}
// If the channel is OOB then don't store it (prevents segfaults, but that shouldn't happen if the file's good)
if (channel >= mod->channels) continue;
if (fixCompatibility) {
// Krawall cuts off portamento below 0, while XM underflows below 0 and never stops, so we need to fix that
// To do that we need to keep track of the portamento value
// Since I kinda don't want to write an entire tracker system just for one effect, we're just keeping track of the main porta effects
if (!mod->flagAmigaLimits) {
if (note && note < 97) memory[channel].porta = note * 16; // If there's a new note, reset the porta
// Look for the new porta value according to the porta value
int d = 0;
if (effect == 0x02)
d = memory[channel].porta - effectop * speed;
else if (effect == 0x0E && (effectop & 0xF0) == 0x20)
d = memory[channel].porta - (effectop & 0x0F);
else if (effect == 0x21 && (effectop & 0xF0) == 0x20)
d = memory[channel].porta - ((effectop & 0x0F) >> 2);
else if (effect == 0x01)
d = memory[channel].porta + effectop * speed;
else if (effect == 0x0E && (effectop & 0xF0) == 0x10)
d = memory[channel].porta + (effectop & 0x0F);
else if (effect == 0x21 && (effectop & 0x0F) == 0x10)
d = memory[channel].porta + ((effectop & 0x0F) >> 2);
else d = 0xFFFF;
// If the new porta is below 0, cut off the note
if (d <= 0) {
if (memory[channel].porta > 0) {
// There's still a bit of porta left until 0, so handle that here
if (effect == 0x02)
effectop = (effectop * speed - memory[channel].porta) / speed;
else if (effect == 0x0E && (effectop & 0xF0) == 0x20)
effectop = (effectop & 0x0F) - memory[channel].porta;
else if (effect == 0x21 && (effectop & 0xF0) == 0x20)
effectop = (((effectop & 0x0F) >> 2) - memory[channel].porta) << 2;
} else {
// Otherwise just queue a cutoff note and remove the effect
note = 97;
xmflag &= ~0x18;
xmflag |= 0x01;
effect = 0;
effectop = 0;
}
}
// Set the new porta value in the memory
// Skip if we're already below 0 to avoid accidental underflow
if (memory[channel].porta > 0 && d != 0xFFFF) memory[channel].porta = d;
}
// If we're not using instruments then make sure the panning doesn't get messed up
if (!mod->flagInstrumentBased) {
if (memory[channel].pan != 0x80 && !(effect == 0x08 || (effect == 0x0E && (effectop & 0xF0) == 0x80))) {
if ((xmflag & 0x1A) == 0x02) {
// Best result, no effect is set so we can squeeze in a pan effect here
xmflag |= 0x18;
effect = 0x08;
effectop = memory[channel].pan;
} else if (instrument && instrument == memory[channel].instrument) {
// The panning only gets set when the instrument changes, so if the instrument didn't change we can just omit it and keep the last pan
xmflag &= ~0x02;
} else if ((xmflag & 0x06) == 0x02) {
// Effect column is already used, but volume isn't, so use the volume column
// Unfortunately this reduces the resolution to 4 bits, so not as desirable
xmflag |= 0x04;
volume = 0xC0 | (memory[channel].pan >> 4);
} else {
// Otherwise, both volume and effect columns are in use so we can't fix the panning. Oh well.
if (!(warnings & 0x04)) {warnings |= 0x04; fprintf(stderr, "Warning: Pattern %d uses special panning effects not available in XM. It will not play correctly.\n", i);}
}
}
if (effect == 0x08) {effectop <<= 1; memory[channel].pan = effectop;}
else if (effect == 0x0E && (effectop & 0xF0) == 0x80) memory[channel].pan = effectop << 4;
if (instrument && note < 97) memory[channel].instrument = instrument;
}
}
// Store the note data in the row
thisrow[channel].xmflag = xmflag;
thisrow[channel].note = note;
thisrow[channel].instrument = instrument;
thisrow[channel].volume = volume;
thisrow[channel].effect = effect;
thisrow[channel].effectop = effectop;
}
// Since Krawall doesn't need to fill all channels and XM does, convert that out
for (int j = 0; j < mod->channels; j++) {
if (thisrow[j].xmflag) { // If this was set, the note should be added
fputc(thisrow[j].xmflag, out);
if (thisrow[j].xmflag & 0x01) fputc(thisrow[j].note, out);
if (thisrow[j].xmflag & 0x02) {
if (thisrow[j].instrument == 0) fputc(0, out);
else if (!trimInstruments) fputc(thisrow[j].instrument & 0x7F, out);
else {
// Convert the instrument number so we can reduce the number of instruments
// Check if the instrument number is already in the list
unsigned char myInstrument = 0;
for (unsigned char k = 0; k < instrumentList.size(); k++) if (instrumentList[k] == thisrow[j].instrument - 1) {
myInstrument = k + 1;
break;
}
// If the instrument wasn't already added to the list, then add it
if (myInstrument == 0) {
// Instruments are listed as 8-bit numbers, so die if there are too many instruments
if (instrumentList.size() >= 254) {
fprintf(stderr, "Error: Too many instruments in current pattern, cannot continue.\n");
free(thisrow);
delete[] memory;
for (int l = 0; l < patternCount; l++) free((void*)mod->patterns[l]);
free(mod);
fclose(out);
return 3;
}
instrumentList.push_back(thisrow[j].instrument - 1);
myInstrument = instrumentList.size();
}
fputc(myInstrument, out);
}
}
if (thisrow[j].xmflag & 0x04) fputc(thisrow[j].volume, out);
if (thisrow[j].xmflag & 0x08) {
if (fixCompatibility && thisrow[j].effect == 0x09 && (thisrow[j].xmflag & 0x10))
sampleOffsetList[thisrow[j].instrument - 1].push_back(std::make_pair(thisrow[j].effectop, ftell(out)));
fputc(thisrow[j].effect, out);
}
if (thisrow[j].xmflag & 0x10) fputc(thisrow[j].effectop, out);
} else fputc(0x80, out); // Empty note (do nothing this row)
}
}
free(thisrow);
delete[] memory;
// Write the size of the packed pattern data
uint32_t endPos = ftell(out);
fseek(out, sizePos, SEEK_SET);
unsigned short size = endPos - sizePos - 2;
fwrite(&size, 2, 1, out);
fseek(out, endPos, SEEK_SET);
}
// Write the total number of instruments used in the module
if (trimInstruments) {
uint32_t endPos = ftell(out);
fseek(out, instrumentSizePos, SEEK_SET);
pnum = instrumentList.size();
fwrite(&pnum, 2, 1, out);
fseek(out, endPos, SEEK_SET);
} else if (mod->flagInstrumentBased) for (int i = 0; i < instrumentOffsets.size(); i++) instrumentList.push_back(i); // Add all instruments if not trimming & we're using instruments
else for (int i = 0; i < sampleOffsets.size(); i++) instrumentList.push_back(i); // Add all samples if not trimming & not using instruments
if (mod->flagInstrumentBased) {
// Write all of the instruments used by the module
for (unsigned short i : instrumentList) {
// Read the instrument info
Instrument instr = readInstrumentFile(instfp, instrumentOffsets[i]);
// Find all of the unique samples
std::vector<unsigned short> samples;
samples.resize(96);
samples.erase(std::unique_copy(instr.samples, instr.samples + 96, samples.begin()), samples.end());
unsigned short snum = samples.size();
// Start writing instrument header
fputc(snum == 0 ? 29 : 252, out);
fputcn(0, 3, out); // 4-byte padding
char name[22];
memset(name, 0, 22);
snprintf(name, 22, "Instrument%d", i);
fwrite(name, 1, 22, out);
fputc(0, out);
fwrite(&snum, 2, 1, out);
if (snum == 0) continue; // XM spec says if there's no samples then skip the rest
// Convert arbitrary sample numbers in the sample map to 0, 1, 2, etc.
// This is because Krawall has a global sample map, while XM counts samples per instrument
std::map<unsigned short, unsigned char> sample_conversion;
unsigned char new_samples[96];
for (unsigned char i = 0; i < snum; i++) sample_conversion[samples[i]] = i;
for (int i = 0; i < 96; i++) new_samples[i] = sample_conversion[instr.samples[i]];
// Write instrument data
fputc(40, out);
fputcn(0, 3, out); // 4-byte padding
fwrite(new_samples, 1, 96, out);
// Convert envelopes to XM format
// Turns out we don't even need the inc field! Everything's packed in coord.
unsigned short tmp;
for (int j = 0; j < 12; j++) {
tmp = instr.envVol.nodes[j].coord & 0x1ff;
fwrite(&tmp, 2, 1, out);
tmp = instr.envVol.nodes[j].coord >> 9;
fwrite(&tmp, 2, 1, out);
}
for (int j = 0; j < 12; j++) {
tmp = instr.envPan.nodes[j].coord & 0x1ff;
fwrite(&tmp, 2, 1, out);
tmp = instr.envPan.nodes[j].coord >> 9;
fwrite(&tmp, 2, 1, out);
}
// Here's a whole bunch of envelope parameters to write
fputc(instr.envVol.max + 1, out);
fputc(instr.envPan.max + 1, out);
fputc(instr.envVol.sus, out);
fputc(instr.envVol.loopStart, out);
fputc(instr.envVol.max, out);
fputc(instr.envPan.sus, out);
fputc(instr.envPan.loopStart, out);
fputc(instr.envPan.max, out);
fputc(instr.envVol.flags, out);
fputc(instr.envPan.flags, out);
fputc(instr.vibType, out);
fputc(instr.vibSweep, out);
fputc(instr.vibDepth, out);
fputc(instr.vibRate, out);
fwrite(&instr.volFade, 2, 1, out);
fputcn(0, 11, out); // Padding as required by XM
// Write all of the samples required for this instrument
// XM requires all of the headers to be written before the data, so we read
// all of the samples in one loop and then write the data in another
// Seems inefficient but it's impossible to avoid
std::vector<Sample*> sarr;
for (int j = 0; j < snum; j++) {
if (samples[j] > sampleOffsets.size()) {
// If the sample isn't present then insert an empty sample
fprintf(stderr, "Warning: Could not find sample %d in instrument %d; inserting an empty sample to avoid breaking things.\n", samples[j], i);
fputcn(0, 40, out);
// Add an empty sample structure to the sample list
Sample * blank = (Sample*)malloc(sizeof(Sample));
memset(blank, 0, sizeof(Sample));
sarr.push_back(blank);
continue;
}
// Read the sample from the file
Sample * s = readSampleFile(instfp, sampleOffsets[samples[j]]);
// Write the sample header
fwrite(&s->size, 4, 1, out);
// Loop start has to be computed from the end & length
if (s->loopLength == 0) fputcn(0, 4, out);
else {
uint32_t start = s->size - s->loopLength;
fwrite(&start, 4, 1, out);
}
// Some other sample parameters
fwrite(&s->loopLength, 4, 1, out);
fputc(s->volDefault, out);
fputc(s->fineTune, out);
fputc((s->loop ? 1 : 0), out);
fputc(s->panDefault + 0x80, out);
fputc(s->relativeNote, out);
fputc(0, out);
memset(name, ' ', 22);
snprintf(name, 22, "Sample%d", samples[j]);
fwrite(name, 1, 22, out);
sarr.push_back(s); // Push the read sample back so we don't have to allocate & read it again
// Update any offset effects that are too big for the instrument
if (fixCompatibility && sampleOffsetList.find(i) != sampleOffsetList.end()) {
unsigned long retpos = ftell(out);
for (std::pair<unsigned char, unsigned long> eff : sampleOffsetList[i]) {
if (eff.first >= (s->size >> 8)) {
fseek(out, eff.second, SEEK_SET);
fputcn(0, 2, out);
}