Repository navigation
Expand file tree
/
Copy pathXAudioScan.cpp
More file actions
2054 lines (1809 loc) · 71.5 KB
/
Copy pathXAudioScan.cpp
File metadata and controls
2054 lines (1809 loc) · 71.5 KB
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
// =====================================================================
// XAudioScan - finds (and optionally repairs) Skyrim audio that
// XAudio2 2.7 cannot play
//
// Standalone. No external libraries. Build with:
// cl /std:c++20 /EHsc /O2 /utf-8 XAudioScan.cpp
//
// Targets Skyrim Special Edition. Includes its own LZ4-block
// decompressor so compressed BSA entries can be read without any
// external library. Skyrim LE archives (v103/v104) are reported and
// skipped rather than guessed at.
//
// Run with --help for usage.
// =====================================================================
#define NOMINMAX
#include <algorithm>
#include <array>
#include <cctype>
#include <chrono>
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <string_view>
#include <vector>
namespace fs = std::filesystem;
// =====================================================================
// LZ4 block format decompression
// =====================================================================
bool Lz4BlockDecompress(const std::uint8_t* src, std::size_t srcSize,
std::vector<std::uint8_t>& out, std::size_t expected)
{
out.clear();
out.reserve(expected);
std::size_t ip = 0;
while (ip < srcSize) {
const std::uint8_t token = src[ip++];
// ---- literals ----
std::size_t litLen = token >> 4;
if (litLen == 15) {
for (;;) {
if (ip >= srcSize) return false;
const std::uint8_t b = src[ip++];
litLen += b;
if (b != 255) break;
}
}
if (ip + litLen > srcSize || out.size() + litLen > expected) {
return false;
}
out.insert(out.end(), src + ip, src + ip + litLen);
ip += litLen;
// The final sequence is literals only and carries no match.
if (ip >= srcSize) {
break;
}
// ---- match ----
if (ip + 2 > srcSize) {
return false;
}
const std::size_t offset =
static_cast<std::size_t>(src[ip]) | (static_cast<std::size_t>(src[ip + 1]) << 8);
ip += 2;
if (offset == 0 || offset > out.size()) {
return false;
}
std::size_t matchLen = token & 0x0F;
if (matchLen == 15) {
for (;;) {
if (ip >= srcSize) return false;
const std::uint8_t b = src[ip++];
matchLen += b;
if (b != 255) break;
}
}
matchLen += 4; // minimum match length
if (out.size() + matchLen > expected) {
return false;
}
const std::size_t start = out.size() - offset;
for (std::size_t i = 0; i < matchLen; ++i) {
out.push_back(out[start + i]); // overlapping copies are legal
}
}
return out.size() == expected;
}
// =====================================================================
// Audio format structures
// =====================================================================
#pragma pack(push, 1)
struct WaveFormatEx {
std::uint16_t formatTag;
std::uint16_t channels;
std::uint32_t samplesPerSec;
std::uint32_t avgBytesPerSec;
std::uint16_t blockAlign;
std::uint16_t bitsPerSample;
std::uint16_t cbSize;
};
#pragma pack(pop)
constexpr std::uint16_t kFmtPCM = 0x0001;
constexpr std::uint16_t kFmtADPCM = 0x0002;
constexpr std::uint16_t kFmtFloat = 0x0003;
constexpr std::uint16_t kFmtALaw = 0x0006;
constexpr std::uint16_t kFmtMuLaw = 0x0007;
constexpr std::uint16_t kFmtIMAADPCM = 0x0011;
constexpr std::uint16_t kFmtGSM610 = 0x0031;
constexpr std::uint16_t kFmtMP3 = 0x0055;
constexpr std::uint16_t kFmtWMAudio2 = 0x0161;
constexpr std::uint16_t kFmtWMAudio3 = 0x0162;
constexpr std::uint16_t kFmtWMALossless = 0x0163;
constexpr std::uint16_t kFmtWMASpdif = 0x0164;
constexpr std::uint16_t kFmtExtensible = 0xFFFE;
constexpr std::uint32_t kMinSampleRate = 1000;
constexpr std::uint32_t kMaxSampleRate = 200000;
constexpr std::uint32_t kMaxChannels = 64;
std::string FormatTagName(std::uint16_t tag)
{
switch (tag) {
case kFmtPCM: return "PCM";
case kFmtADPCM: return "MS ADPCM";
case kFmtFloat: return "IEEE float";
case kFmtALaw: return "A-law";
case kFmtMuLaw: return "mu-law";
case kFmtIMAADPCM: return "IMA/DVI ADPCM";
case kFmtGSM610: return "GSM 6.10";
case kFmtMP3: return "MP3";
case kFmtWMAudio2: return "xWMA (WMAudio2)";
case kFmtWMAudio3: return "xWMA (WMAudio3)";
case kFmtWMALossless: return "WMA Lossless";
case kFmtWMASpdif: return "WMA S/PDIF";
case kFmtExtensible: return "WAVE_FORMAT_EXTENSIBLE";
default: return "unknown codec";
}
}
// =====================================================================
// Findings
// =====================================================================
enum class Severity { Ok = 0, Warning = 1, Fatal = 2 };
struct Finding {
Severity severity{ Severity::Warning };
std::string reason;
std::string fix;
};
struct Report {
Severity severity{ Severity::Ok };
std::vector<Finding> findings;
void Add(Severity sev, std::string reason, std::string fix)
{
if (sev > severity) {
severity = sev;
}
findings.push_back({ sev, std::move(reason), std::move(fix) });
}
bool Fatal() const { return severity == Severity::Fatal; }
bool Clean() const { return severity == Severity::Ok; }
};
// =====================================================================
// Blob
// =====================================================================
struct Blob {
std::vector<std::uint8_t> bytes;
std::uint64_t trueSize{ 0 };
bool complete{ true };
bool ReadAt(std::uint64_t off, void* dst, std::size_t n) const
{
if (off + n > bytes.size()) {
return false;
}
std::memcpy(dst, bytes.data() + off, n);
return true;
}
std::uint32_t U32At(std::uint64_t off, bool& good) const
{
std::uint32_t v = 0;
good = ReadAt(off, &v, sizeof(v));
return v;
}
};
constexpr std::uint32_t FourCC(const char (&s)[5])
{
return static_cast<std::uint32_t>(static_cast<std::uint8_t>(s[0])) |
(static_cast<std::uint32_t>(static_cast<std::uint8_t>(s[1])) << 8) |
(static_cast<std::uint32_t>(static_cast<std::uint8_t>(s[2])) << 16) |
(static_cast<std::uint32_t>(static_cast<std::uint8_t>(s[3])) << 24);
}
constexpr std::uint32_t kRIFF = FourCC("RIFF");
constexpr std::uint32_t kWAVE = FourCC("WAVE");
constexpr std::uint32_t kXWMA = FourCC("XWMA");
constexpr std::uint32_t kFMT_ = FourCC("fmt ");
constexpr std::uint32_t kDATA = FourCC("data");
constexpr std::uint32_t kDPDS = FourCC("dpds");
constexpr std::uint32_t kFUZE = FourCC("FUZE");
// =====================================================================
// Format inspection
// =====================================================================
std::uint16_t EffectiveTag(const std::vector<std::uint8_t>& fmtChunk, const WaveFormatEx& fmt)
{
if (fmt.formatTag != kFmtExtensible || fmtChunk.size() < 40) {
return fmt.formatTag;
}
static constexpr std::uint8_t tail[12] = {
0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71
};
if (std::memcmp(fmtChunk.data() + 28, tail, sizeof(tail)) != 0) {
return kFmtExtensible;
}
std::uint32_t subData1 = 0;
std::memcpy(&subData1, fmtChunk.data() + 24, 4);
return static_cast<std::uint16_t>(subData1);
}
bool ParseFormat(const std::vector<std::uint8_t>& fmtChunk, WaveFormatEx& fmt)
{
if (fmtChunk.size() < 16) {
return false;
}
std::memset(&fmt, 0, sizeof(fmt));
std::memcpy(&fmt, fmtChunk.data(), (std::min)(fmtChunk.size(), sizeof(WaveFormatEx)));
if (fmtChunk.size() < 18) {
fmt.cbSize = 0;
}
return true;
}
void InspectFormat(const std::vector<std::uint8_t>& fmtChunk, Report& r)
{
WaveFormatEx fmt{};
if (!ParseFormat(fmtChunk, fmt)) {
r.Add(Severity::Fatal,
std::format("The 'fmt ' chunk is only {} bytes; 16 is the minimum.", fmtChunk.size()),
"Re-export the file from the original source.");
return;
}
const std::uint16_t bits = fmt.bitsPerSample;
std::uint16_t effectiveTag = fmt.formatTag;
if (fmt.formatTag == kFmtExtensible) {
if (fmtChunk.size() < 40 || fmt.cbSize < 22) {
r.Add(Severity::Fatal,
std::format("WAVE_FORMAT_EXTENSIBLE declares cbSize={} in a {}-byte chunk, but "
"22 extra bytes are required.", fmt.cbSize, fmtChunk.size()),
"Re-export as plain 16-bit PCM WAV.");
return;
}
effectiveTag = EffectiveTag(fmtChunk, fmt);
if (effectiveTag == kFmtExtensible) {
r.Add(Severity::Fatal,
"WAVE_FORMAT_EXTENSIBLE uses a non-standard SubFormat GUID that XAudio2 2.7 "
"cannot map to a known codec.",
"Re-export as plain 16-bit PCM WAV.");
return;
}
std::uint16_t validBits = 0;
std::memcpy(&validBits, fmtChunk.data() + 18, 2);
if (validBits != 0 && validBits > bits) {
r.Add(Severity::Fatal,
std::format("wValidBitsPerSample ({}) exceeds wBitsPerSample ({}).", validBits, bits),
"Re-export as plain 16-bit PCM WAV.");
}
}
if (fmt.channels == 0) {
r.Add(Severity::Fatal,
"Channel count is 0. Every buffer-size calculation downstream divides by this.",
"Header is corrupt. Re-encode from the original source.");
} else if (fmt.channels > kMaxChannels) {
r.Add(Severity::Fatal,
std::format("Channel count is {}. XAudio2 2.7 supports at most {}.",
fmt.channels, kMaxChannels),
"Downmix to mono for sound effects, stereo for music.");
} else if (fmt.channels > 2) {
r.Add(Severity::Warning,
std::format("{} channels. Skyrim's audio graph is built around mono and stereo; "
"multichannel sources behave unpredictably through the 3D emitter path.",
fmt.channels),
"Downmix to mono for sound effects, stereo for music.");
}
if (fmt.samplesPerSec < kMinSampleRate || fmt.samplesPerSec > kMaxSampleRate) {
r.Add(Severity::Fatal,
std::format("Sample rate is {} Hz. XAudio2 2.7 accepts {}-{} Hz only.",
fmt.samplesPerSec, kMinSampleRate, kMaxSampleRate),
"Resample to 44100 Hz.");
} else {
static constexpr std::uint32_t common[] = {
8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000
};
if (std::find(std::begin(common), std::end(common), fmt.samplesPerSec) == std::end(common)) {
r.Add(Severity::Warning,
std::format("Unusual sample rate ({} Hz). Legal, but pitch-shifted variants of a "
"high-rate source can exceed the 200 kHz ceiling XAudio2 2.7 enforces.",
fmt.samplesPerSec),
"Resample to 44100 Hz.");
}
}
switch (effectiveTag) {
case kFmtPCM:
if (bits != 8 && bits != 16 && bits != 24 && bits != 32) {
r.Add(Severity::Fatal,
std::format("{}-bit PCM. XAudio2 2.7 supports 8, 16, 24 and 32-bit PCM only.", bits),
"Re-export as 16-bit PCM.");
} else if (bits != 16) {
r.Add(Severity::Warning,
std::format("{}-bit PCM. XAudio2 accepts it, but Skyrim's own code paths assume "
"16-bit and several mod tools mishandle it.", bits),
"Re-export as 16-bit PCM.");
}
break;
case kFmtFloat:
if (bits != 32 && bits != 64) {
r.Add(Severity::Fatal,
std::format("IEEE float declared with {} bits per sample; only 32 or 64 is valid.", bits),
"Re-export as 16-bit PCM.");
} else {
r.Add(Severity::Warning,
std::format("{}-bit float WAV. This is what a modern DAW exports by default and "
"it is not what Skyrim expects.", bits),
"Re-export as 16-bit PCM. Audacity: File > Export > WAV, 'Signed 16-bit PCM'.");
}
break;
case kFmtADPCM:
case kFmtIMAADPCM:
case kFmtGSM610:
case kFmtMP3:
case kFmtALaw:
case kFmtMuLaw:
r.Add(Severity::Fatal,
std::format("Codec is {} (0x{:04X}). XAudio2 2.7 has no decoder for this; "
"CreateSourceVoice fails and the caller is left with a null voice pointer.",
FormatTagName(effectiveTag), effectiveTag),
"Re-encode to 16-bit PCM WAV, or to xWMA if you need the compression.");
break;
case kFmtWMAudio2:
case kFmtWMAudio3:
if (fmt.blockAlign == 0) {
r.Add(Severity::Fatal, "xWMA format with nBlockAlign = 0.",
"Re-encode with xWMAEncode.exe from the DirectX SDK, or Yakitori Audio Converter.");
}
break;
case kFmtWMALossless:
case kFmtWMASpdif:
r.Add(Severity::Fatal,
std::format("Codec is {} (0x{:04X}), which XAudio2 2.7 cannot play.",
FormatTagName(effectiveTag), effectiveTag),
"Re-encode to 16-bit PCM WAV or standard xWMA.");
break;
default:
r.Add(Severity::Fatal, std::format("Unrecognised codec tag 0x{:04X}.", effectiveTag),
"Re-encode to 16-bit PCM WAV.");
break;
}
if (fmt.blockAlign == 0) {
r.Add(Severity::Fatal,
"nBlockAlign is 0. Buffer length is computed as bytes / nBlockAlign, which is a "
"divide-by-zero waiting to happen.",
"Rebuild the WAV header - any re-export from Audacity or ffmpeg fixes it.");
}
const bool linearPcm = (effectiveTag == kFmtPCM || effectiveTag == kFmtFloat);
if (linearPcm && fmt.channels > 0 && bits > 0) {
const auto expectedAlign = static_cast<std::uint16_t>(fmt.channels * (bits / 8));
const auto expectedAvg = static_cast<std::uint32_t>(fmt.samplesPerSec) * expectedAlign;
if (expectedAlign != 0 && fmt.blockAlign != expectedAlign) {
r.Add(Severity::Fatal,
std::format("nBlockAlign is {} but {} channels x {} bits requires {}. The decoder "
"will walk off the end of every buffer it is given.",
fmt.blockAlign, fmt.channels, bits, expectedAlign),
"Header is malformed. Re-export the file.");
}
if (expectedAvg != 0 && fmt.avgBytesPerSec != expectedAvg && fmt.blockAlign == expectedAlign) {
r.Add(Severity::Warning,
std::format("nAvgBytesPerSec is {} but the declared format implies {}.",
fmt.avgBytesPerSec, expectedAvg),
"Cosmetic, but it means the header was hand-edited or written by a broken tool.");
}
}
}
// =====================================================================
// RIFF walking
// =====================================================================
struct RiffInfo {
bool valid{ false };
std::uint32_t formType{ 0 };
std::vector<std::uint8_t> fmtChunk;
std::vector<std::uint8_t> dpdsChunk;
bool haveData{ false };
std::uint64_t dataOffset{ 0 };
std::uint64_t dataSize{ 0 };
bool haveDpds{ false };
bool truncated{ false };
bool chunkOverrun{ false };
bool incomplete{ false };
};
RiffInfo WalkRiff(const Blob& blob, std::uint64_t base)
{
RiffInfo info;
bool good = false;
if (blob.U32At(base, good) != kRIFF || !good) {
return info;
}
const auto riffSize = blob.U32At(base + 4, good);
if (!good) {
return info;
}
info.formType = blob.U32At(base + 8, good);
if (!good) {
return info;
}
info.valid = true;
std::uint64_t declaredEnd = base + 8 + riffSize;
if (declaredEnd > blob.trueSize) {
info.truncated = true;
declaredEnd = blob.trueSize;
}
std::uint64_t offset = base + 12;
while (offset + 8 <= declaredEnd) {
if (offset + 8 > blob.bytes.size()) {
info.incomplete = true;
break;
}
const auto id = blob.U32At(offset, good);
if (!good) break;
const auto chunkSize = blob.U32At(offset + 4, good);
if (!good) break;
const std::uint64_t body = offset + 8;
if (body + chunkSize > blob.trueSize) {
info.chunkOverrun = true;
}
if (id == kFMT_) {
const auto want = (std::min)(static_cast<std::uint64_t>(chunkSize), std::uint64_t{ 64 });
info.fmtChunk.resize(static_cast<std::size_t>(want));
if (want == 0 || !blob.ReadAt(body, info.fmtChunk.data(), static_cast<std::size_t>(want))) {
info.fmtChunk.clear();
}
} else if (id == kDATA) {
info.haveData = true;
info.dataOffset = body;
info.dataSize = chunkSize;
} else if (id == kDPDS) {
info.haveDpds = true;
const auto want = (std::min)(static_cast<std::uint64_t>(chunkSize),
std::uint64_t{ 1 } << 20);
info.dpdsChunk.resize(static_cast<std::size_t>(want));
if (want == 0 || !blob.ReadAt(body, info.dpdsChunk.data(), static_cast<std::size_t>(want))) {
info.dpdsChunk.clear();
}
}
const std::uint64_t advance = 8ull + chunkSize + (chunkSize & 1);
if (advance <= 8) break;
offset += advance;
}
return info;
}
void EvaluateRiff(const RiffInfo& info, const std::string& displayPath, Report& r)
{
if (!info.valid) {
r.Add(Severity::Fatal, "Not a valid RIFF container - does not start with 'RIFF'.",
"The file is corrupt, truncated, or a different format with the wrong extension.");
return;
}
const bool isXwma = (info.formType == kXWMA);
if (info.formType != kWAVE && !isXwma) {
r.Add(Severity::Fatal, "RIFF form type is neither 'WAVE' nor 'XWMA'.",
"Re-encode to 16-bit PCM WAV or xWMA.");
}
if (info.truncated) {
r.Add(Severity::Fatal,
"The RIFF header declares more data than the file contains. The file is truncated.",
"Re-download or re-extract the mod - usually a bad extraction or interrupted download.");
}
if (info.chunkOverrun) {
r.Add(Severity::Fatal, "At least one chunk claims to extend past the end of the file.",
"Header is corrupt. Re-export the file.");
}
if (info.fmtChunk.empty()) {
if (!info.incomplete) {
r.Add(Severity::Fatal, "No usable 'fmt ' chunk.",
"Re-export the file from the original source.");
}
} else {
InspectFormat(info.fmtChunk, r);
std::string lower = displayPath;
std::transform(lower.begin(), lower.end(), lower.begin(),
[](unsigned char c) {
c = static_cast<unsigned char>(std::tolower(c));
return static_cast<char>(c == '\\' ? '/' : c);
});
if (lower.find("sound/fx/") != std::string::npos && info.fmtChunk.size() >= 4) {
std::uint16_t ch = 0;
std::memcpy(&ch, info.fmtChunk.data() + 2, 2);
if (ch == 2) {
r.Add(Severity::Warning,
"Stereo file inside Sound\\FX. Skyrim submits these to a 3D emitter, which "
"expects a mono source; the channel counts on the output matrix then disagree.",
"Convert to mono, or make sure the Sound Descriptor is not flagged as 3D.");
}
}
}
if (!info.haveData && !info.incomplete) {
r.Add(Severity::Fatal, "No 'data' chunk. The file declares a format but contains no audio.",
"Re-export the file.");
} else if (info.haveData && info.dataSize == 0) {
r.Add(Severity::Fatal, "The 'data' chunk is zero bytes long.",
"Re-export the file. A zero-length placeholder faults as soon as it is submitted.");
}
if (isXwma && !info.incomplete) {
if (!info.haveDpds) {
r.Add(Severity::Fatal,
"xWMA file with no 'dpds' chunk. XAudio2's xWMA path needs that seek table to "
"locate packet boundaries; without it, playback reads garbage packet offsets.",
"Re-encode with xWMAEncode.exe, or Yakitori Audio Converter. This almost always "
"comes from renaming a .wma to .xwm.");
} else if (info.dpdsChunk.size() < 4) {
r.Add(Severity::Fatal, "The 'dpds' seek table is present but empty.",
"Re-encode with xWMAEncode.exe.");
}
}
}
// =====================================================================
// Asset inspection
// =====================================================================
std::uint64_t FindEmbeddedRiff(const Blob& blob, std::uint64_t from)
{
if (blob.bytes.size() < 12) {
return UINT64_MAX;
}
for (std::uint64_t i = from; i + 12 <= blob.bytes.size(); ++i) {
bool good = false;
if (blob.U32At(i, good) == kRIFF && good) {
const auto form = blob.U32At(i + 8, good);
if (good && (form == kXWMA || form == kWAVE)) {
return i;
}
}
}
return UINT64_MAX;
}
Report InspectBlob(const Blob& blob, const std::string& displayPath, std::string_view ext)
{
Report r;
if (blob.trueSize == 0) {
r.Add(Severity::Fatal, "Zero-byte file.",
"Delete or replace it. Usually left behind by a failed archive extraction.");
return r;
}
if (blob.trueSize < 12 || blob.bytes.size() < 12) {
r.Add(Severity::Fatal,
std::format("File is only {} bytes - too small to contain a header.", blob.trueSize),
"Delete or replace the file.");
return r;
}
bool good = false;
const auto magic = blob.U32At(0, good);
if (!good) {
r.Add(Severity::Fatal, "Could not read the first four bytes.", "Replace the file.");
return r;
}
if (ext == ".fuz") {
if (magic == kRIFF) {
r.Add(Severity::Fatal,
"This .fuz is actually a bare RIFF. Skyrim reads the first 12 bytes as a FUZE "
"header, gets a nonsense LIP length, and seeks to an arbitrary offset.",
"Wrap it properly, or rename it to match its contents. Repairable with --fix.");
return r;
}
if (magic != kFUZE) {
r.Add(Severity::Fatal, "Not a FUZE container - does not start with 'FUZE'.",
"Rebuild the .fuz from its audio and .lip parts.");
return r;
}
const auto version = blob.U32At(4, good);
if (good && version != 1) {
r.Add(Severity::Warning,
std::format("FUZE version field is {}; every vanilla file uses 1.", version),
"Rebuild the .fuz with a current tool.");
}
const auto lipSize = blob.U32At(8, good);
if (!good) {
r.Add(Severity::Fatal, "Truncated FUZE header.", "Rebuild the .fuz.");
return r;
}
const std::uint64_t audioOffset = 12ull + lipSize;
RiffInfo inner;
if (audioOffset + 12 <= blob.bytes.size()) {
inner = WalkRiff(blob, audioOffset);
}
if (!inner.valid) {
const auto actual = FindEmbeddedRiff(blob, 12);
if (actual != UINT64_MAX) {
r.Add(Severity::Fatal,
std::format("The FUZE header points at offset {} but the embedded RIFF "
"actually starts at {}. The declared LIP length is wrong.",
audioOffset, actual),
std::format("The LIP length field should be {}. Repairable with --fix.",
actual - 12));
auto real = WalkRiff(blob, actual);
EvaluateRiff(real, displayPath, r);
} else if (audioOffset >= blob.trueSize) {
r.Add(Severity::Fatal,
std::format("FUZE header says the LIP block is {} bytes, putting the audio "
"start at offset {} in a {}-byte file.",
lipSize, audioOffset, blob.trueSize),
"Header is corrupt or the file is truncated. Rebuild the .fuz.");
} else {
r.Add(Severity::Fatal,
"The embedded audio block inside the .fuz is not a RIFF container, and no "
"RIFF header was found anywhere in the file.",
"Rebuild the .fuz from its source audio.");
}
return r;
}
EvaluateRiff(inner, displayPath, r);
return r;
}
if (magic == kFUZE) {
r.Add(Severity::Fatal, std::format("This {} file is actually a FUZE container.", ext),
"Rename it to .fuz, or unpack the audio out of it.");
return r;
}
auto info = WalkRiff(blob, 0);
EvaluateRiff(info, displayPath, r);
if (info.valid) {
if (ext == ".xwm" && info.formType == kWAVE) {
r.Add(Severity::Warning, "Extension is .xwm but the form type is 'WAVE'.",
"If it really is a plain WAV, rename it to .wav and update the sound record.");
} else if (ext == ".wav" && info.formType == kXWMA) {
r.Add(Severity::Fatal, "Extension is .wav but the contents are xWMA.",
"Rename it to .xwm and update the sound record, or decode it to PCM.");
}
}
return r;
}
// =====================================================================
// Repair engine
//
// Everything here rebuilds a clean container from the parts that are
// recoverable. Sample data is only ever converted between linear PCM
// representations - nothing is re-encoded through a lossy codec.
// =====================================================================
struct RepairOptions {
bool monoFx = false;
bool placeholders = false;
};
struct RepairResult {
bool changed = false;
bool unfixable = false;
bool isPlaceholder = false;
std::vector<std::uint8_t> data;
std::vector<std::string> actions;
};
void AppendU32(std::vector<std::uint8_t>& v, std::uint32_t x)
{
v.push_back(static_cast<std::uint8_t>(x & 0xFF));
v.push_back(static_cast<std::uint8_t>((x >> 8) & 0xFF));
v.push_back(static_cast<std::uint8_t>((x >> 16) & 0xFF));
v.push_back(static_cast<std::uint8_t>((x >> 24) & 0xFF));
}
void AppendTag(std::vector<std::uint8_t>& v, const char (&s)[5])
{
v.insert(v.end(), s, s + 4);
}
std::vector<std::uint8_t> BuildRiff(std::uint32_t formType,
const std::vector<std::uint8_t>& fmtChunk,
const std::vector<std::uint8_t>& dpdsChunk,
const std::uint8_t* data, std::size_t dataSize)
{
std::vector<std::uint8_t> out;
out.reserve(dataSize + fmtChunk.size() + dpdsChunk.size() + 64);
AppendTag(out, "RIFF");
AppendU32(out, 0); // patched at the end
AppendU32(out, formType);
AppendTag(out, "fmt ");
AppendU32(out, static_cast<std::uint32_t>(fmtChunk.size()));
out.insert(out.end(), fmtChunk.begin(), fmtChunk.end());
if (fmtChunk.size() & 1) {
out.push_back(0);
}
if (!dpdsChunk.empty()) {
AppendTag(out, "dpds");
AppendU32(out, static_cast<std::uint32_t>(dpdsChunk.size()));
out.insert(out.end(), dpdsChunk.begin(), dpdsChunk.end());
if (dpdsChunk.size() & 1) {
out.push_back(0);
}
}
AppendTag(out, "data");
AppendU32(out, static_cast<std::uint32_t>(dataSize));
out.insert(out.end(), data, data + dataSize);
if (dataSize & 1) {
out.push_back(0);
}
const std::uint32_t riffSize = static_cast<std::uint32_t>(out.size() - 8);
std::memcpy(out.data() + 4, &riffSize, 4);
return out;
}
std::vector<std::uint8_t> MakePcmFmtChunk(std::uint16_t channels, std::uint32_t rate)
{
WaveFormatEx fmt{};
fmt.formatTag = kFmtPCM;
fmt.channels = channels;
fmt.samplesPerSec = rate;
fmt.bitsPerSample = 16;
fmt.blockAlign = static_cast<std::uint16_t>(channels * 2);
fmt.avgBytesPerSec = rate * fmt.blockAlign;
std::vector<std::uint8_t> chunk(16);
std::memcpy(chunk.data(), &fmt, 16); // 16 bytes = classic PCM header, no cbSize
return chunk;
}
std::vector<std::uint8_t> MakeSilentWav(std::uint16_t channels, std::uint32_t rate, double seconds)
{
if (channels == 0 || channels > 2) channels = 1;
if (rate < kMinSampleRate || rate > kMaxSampleRate) rate = 44100;
const auto frames = static_cast<std::size_t>(rate * seconds);
std::vector<std::uint8_t> silence(frames * channels * 2, 0);
return BuildRiff(kWAVE, MakePcmFmtChunk(channels, rate), {}, silence.data(), silence.size());
}
std::int16_t ClampToI16(double v)
{
if (v > 32767.0) return 32767;
if (v < -32768.0) return -32768;
return static_cast<std::int16_t>(v);
}
bool ConvertToPcm16(const std::uint8_t* src, std::size_t srcSize,
std::uint16_t tag, std::uint16_t bits, std::uint16_t channels,
std::vector<std::int16_t>& out)
{
if (channels == 0 || bits == 0) {
return false;
}
const std::size_t bytesPerSample = bits / 8u;
if (bytesPerSample == 0) {
return false;
}
const std::size_t sampleCount = srcSize / bytesPerSample;
out.assign(sampleCount, 0);
if (tag == kFmtPCM) {
switch (bits) {
case 8:
for (std::size_t i = 0; i < sampleCount; ++i) {
out[i] = static_cast<std::int16_t>((static_cast<int>(src[i]) - 128) << 8);
}
return true;
case 16:
if (sampleCount > 0) {
std::memcpy(out.data(), src, sampleCount * 2);
}
return true;
case 24:
for (std::size_t i = 0; i < sampleCount; ++i) {
const std::uint8_t* p = src + i * 3;
const auto v = static_cast<std::int32_t>((static_cast<std::uint32_t>(p[2]) << 24) |
(static_cast<std::uint32_t>(p[1]) << 16) |
(static_cast<std::uint32_t>(p[0]) << 8));
out[i] = static_cast<std::int16_t>(v >> 16);
}
return true;
case 32:
for (std::size_t i = 0; i < sampleCount; ++i) {
std::int32_t v = 0;
std::memcpy(&v, src + i * 4, 4);
out[i] = static_cast<std::int16_t>(v >> 16);
}
return true;
default:
return false;
}
}
if (tag == kFmtFloat) {
if (bits == 32) {
for (std::size_t i = 0; i < sampleCount; ++i) {
float f = 0.0f;
std::memcpy(&f, src + i * 4, 4);
out[i] = ClampToI16(static_cast<double>(f) * 32767.0);
}
return true;
}
if (bits == 64) {
for (std::size_t i = 0; i < sampleCount; ++i) {
double d = 0.0;
std::memcpy(&d, src + i * 8, 8);
out[i] = ClampToI16(d * 32767.0);
}
return true;
}
}
return false;
}
RepairResult RepairRiff(const Blob& blob, std::uint64_t base, const std::string& displayPath,
const RepairOptions& opts)
{
RepairResult res;
auto info = WalkRiff(blob, base);
if (!info.valid || info.fmtChunk.empty()) {
res.unfixable = true;
return res;
}
WaveFormatEx fmt{};
if (!ParseFormat(info.fmtChunk, fmt)) {
res.unfixable = true;
return res;
}
const std::uint16_t tag = EffectiveTag(info.fmtChunk, fmt);
if (!info.haveData) {
res.unfixable = true;
return res;
}
std::uint64_t dataEnd = info.dataOffset + info.dataSize;
bool clamped = false;
if (dataEnd > blob.bytes.size()) {
dataEnd = blob.bytes.size();
clamped = true;
}
if (dataEnd <= info.dataOffset) {
res.unfixable = true;
return res;
}
const auto dataSize = static_cast<std::size_t>(dataEnd - info.dataOffset);
const std::uint8_t* data = blob.bytes.data() + info.dataOffset;
// ---- xWMA: header repairs only, the payload is opaque to us -------
if (info.formType == kXWMA || tag == kFmtWMAudio2 || tag == kFmtWMAudio3) {
if (!info.haveDpds || info.dpdsChunk.size() < 4) {
res.unfixable = true;
res.actions.push_back("xWMA without a usable dpds seek table cannot be repaired "
"without re-encoding");
return res;
}
if (!info.truncated && !info.chunkOverrun && !clamped) {
return res; // already fine
}
res.data = BuildRiff(kXWMA, info.fmtChunk, info.dpdsChunk, data, dataSize);
res.changed = true;
res.actions.push_back(std::format(
"rebuilt the xWMA container around the {} bytes of audio that exist", dataSize));
return res;
}
// ---- linear PCM family -------------------------------------------
if (tag != kFmtPCM && tag != kFmtFloat) {
res.unfixable = true;
res.actions.push_back(std::format(
"{} (0x{:04X}) would have to be re-encoded, which needs a real audio tool",
FormatTagName(tag), tag));
return res;
}
std::uint16_t channels = fmt.channels;
if (channels == 0 || channels > kMaxChannels) {
res.unfixable = true;
res.actions.push_back("channel count is not recoverable from the header");
return res;
}
std::uint32_t rate = fmt.samplesPerSec;
bool rateFixed = false;
if (rate < kMinSampleRate || rate > kMaxSampleRate) {
rate = 44100;
rateFixed = true;
}
std::vector<std::int16_t> samples;
if (!ConvertToPcm16(data, dataSize, tag, fmt.bitsPerSample, channels, samples)) {
res.unfixable = true;
res.actions.push_back(std::format("{}-bit {} could not be converted to 16-bit PCM",
fmt.bitsPerSample, FormatTagName(tag)));
return res;
}
if (samples.empty()) {
res.unfixable = true;
return res;
}
// Drop a trailing partial frame so the payload is a whole number of frames.
if (channels > 1 && (samples.size() % channels) != 0) {
samples.resize(samples.size() - (samples.size() % channels));
}
const bool converted = (tag != kFmtPCM || fmt.bitsPerSample != 16);
bool downmixed = false;
std::string lower = displayPath;
std::transform(lower.begin(), lower.end(), lower.begin(),
[](unsigned char c) {
c = static_cast<unsigned char>(std::tolower(c));
return static_cast<char>(c == '\\' ? '/' : c);
});
const bool inFx = lower.find("sound/fx/") != std::string::npos;
if (opts.monoFx && inFx && channels == 2 && samples.size() >= 2) {
std::vector<std::int16_t> mono(samples.size() / 2);
for (std::size_t i = 0; i < mono.size(); ++i) {
mono[i] = static_cast<std::int16_t>(
(static_cast<int>(samples[i * 2]) + static_cast<int>(samples[i * 2 + 1])) / 2);
}
samples = std::move(mono);
channels = 1;
downmixed = true;
}
const auto expectedAlign = static_cast<std::uint16_t>(fmt.channels * (fmt.bitsPerSample / 8));
const bool headerBad = (expectedAlign == 0) || (fmt.blockAlign != expectedAlign) ||