forked from y2361547758/hca.js
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhca.ts
4145 lines (3858 loc) · 183 KB
/
hca.ts
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
export class HCAInfo {
private rawHeader: Uint8Array;
version = "";
versionMajor = 2;
versionMinor = 0;
dataOffset = 0;
format = {
channelCount: 0,
samplingRate: 0,
blockCount: 0,
droppedHeader: 0,
droppedFooter: 0
}
blockSize = 0;
hasHeader: Record<string, boolean> = {};
headerOffset: Record<string, [number, number]> = {}; // [start (inclusive), end (exclusive)]
kbps = 0;
compDec = {
MinResolution: 0,
MaxResolution: 0,
TrackCount: 0,
ChannelConfig: 0,
TotalBandCount: 0,
BaseBandCount: 0,
StereoBandCount: 0,
HfrBandCount: 0,
BandsPerHfrGroup: 0,
Reserved1: 0,
Reserved2: 0,
};
dec = {
DecStereoType: 0,
}
loop = {
start: 0,
end: 0,
// count: 0, // Nyagamon's interpretation
// r01: 0,
droppedHeader: 0, // VGAudio's interpretation
droppedFooter: 0,
}
vbr = {
MaxBlockSize: 0,
NoiseLevel: 0,
}
UseAthCurve: boolean = false;
cipher = 0;
rva = 0.0;
comment = "";
// computed sample count/offsets
HfrGroupCount = 0;
fullSampleCount = 0;
startAtSample = 0;
fullEndAtSample = 0;
loopStartAtSample = 0;
loopEndAtSample = 0;
loopSampleCount = 0;
loopStartTime = 0; // in seconds
loopEndTime = 0; // in seconds
loopDuration = 0; // in seconds
endAtSample = 0;
sampleCount = 0;
duration = 0; // in seconds
// full file size / data part (excluding header, just blocks/frames) size
fullSize = 0;
dataSize = 0;
// depends on decoding mode (bit count)
inWavSize?: HCAInfoInWavSize;
private static getSign(raw: DataView, offset = 0, changeMask: boolean, encrypt: boolean) {
let magic = raw.getUint32(offset, true);
let strLen = 4;
for (let i = 0; i < 4; i++) {
if (raw.getUint8(offset + i) == 0) {
strLen = i;
break;
}
}
if (strLen > 0) {
let mask = 0x80808080 >>> 8 * (4 - strLen);
magic &= 0x7f7f7f7f;
if (changeMask) raw.setUint32(offset, encrypt ? magic | mask : magic, true);
}
let hex = [magic & 0xff, magic >> 8 & 0xff, magic >> 16 & 0xff, magic >> 24 & 0xff];
hex = hex.slice(0, strLen);
return String.fromCharCode.apply(String, hex);
}
clone(): HCAInfo {
return new HCAInfo(this.rawHeader);
}
private parseHeader(hca: Uint8Array, changeMask: boolean, encrypt: boolean, modList: Record<string, Uint8Array>) {
let p = new DataView(hca.buffer, hca.byteOffset, 8);
let head = HCAInfo.getSign(p, 0, false, encrypt); // do not overwrite for now, until checksum verified
if (head !== "HCA") {
throw new Error("Not a HCA file");
}
const version = {
main: p.getUint8(4),
sub: p.getUint8(5)
}
this.version = version.main + '.' + version.sub;
this.versionMajor = version.main;
this.versionMinor = version.sub;
this.dataOffset = p.getUint16(6);
// verify checksum
HCACrc16.verify(hca, this.dataOffset - 2);
let hasModDone = false;
// checksum verified, now we can overwrite it
if (changeMask) HCAInfo.getSign(p, 0, changeMask, encrypt);
// parse the header
p = new DataView(hca.buffer, hca.byteOffset, this.dataOffset);
let ftell = 8;
while (ftell < this.dataOffset - 2) {
let lastFtell = ftell;
// get the sig
let sign = HCAInfo.getSign(p, ftell, changeMask, encrypt);
// record hasHeader
this.hasHeader[sign] = true;
// padding should be the last one
if (sign == "pad") {
this.headerOffset[sign] = [ftell, this.dataOffset - 2];
break;
}
// parse data accordingly
switch (sign) {
case "fmt":
this.format.channelCount = p.getUint8(ftell + 4);
this.format.samplingRate = p.getUint32(ftell + 4) & 0x00ffffff;
this.format.blockCount = p.getUint32(ftell + 8);
this.format.droppedHeader = p.getUint16(ftell + 12);
this.format.droppedFooter = p.getUint16(ftell + 14);
ftell += 16;
break;
case "comp":
this.blockSize = p.getUint16(ftell + 4);
this.kbps = this.format.samplingRate * this.blockSize / 128000.0;
this.compDec.MinResolution = p.getUint8(ftell + 6);
this.compDec.MaxResolution = p.getUint8(ftell + 7);
this.compDec.TrackCount = p.getUint8(ftell + 8);
this.compDec.ChannelConfig = p.getUint8(ftell + 9);
this.compDec.TotalBandCount = p.getUint8(ftell + 10);
this.compDec.BaseBandCount = p.getUint8(ftell + 11);
this.compDec.StereoBandCount = p.getUint8(ftell + 12);
this.compDec.BandsPerHfrGroup = p.getUint8(ftell + 13);
this.compDec.Reserved1 = p.getUint8(ftell + 14);
this.compDec.Reserved2 = p.getUint8(ftell + 15);
ftell += 16;
break;
case "dec":
this.blockSize = p.getUint16(ftell + 4);
this.kbps = this.format.samplingRate * this.blockSize / 128000.0;
this.compDec.MinResolution = p.getUint8(ftell + 6);
this.compDec.MaxResolution = p.getUint8(ftell + 7);
this.compDec.TotalBandCount = p.getUint8(ftell + 8); + 1;
this.compDec.BaseBandCount = p.getUint8(ftell + 9); + 1;
let a = p.getUint8(ftell + 10);
this.compDec.TrackCount = HCAUtilFunc.GetHighNibble(a);
this.compDec.ChannelConfig = HCAUtilFunc.GetLowNibble(a);
this.dec.DecStereoType = p.getUint8(ftell + 11);
if (this.dec.DecStereoType == 0) {
this.compDec.BaseBandCount = this.compDec.TotalBandCount;
} else {
this.compDec.StereoBandCount = this.compDec.TotalBandCount - this.compDec.BaseBandCount;
}
ftell += 12;
break;
case "vbr":
ftell += 8;
break;
case "ath":
this.UseAthCurve = p.getUint16(ftell + 4) == 1;
ftell += 6;
break;
case "loop":
this.loop.start = p.getUint32(ftell + 4);
this.loop.end = p.getUint32(ftell + 8);
this.loop.droppedHeader = p.getUint16(ftell + 12);
this.loop.droppedFooter = p.getUint16(ftell + 14);
ftell += 16;
break;
case "ciph":
this.cipher = p.getUint16(ftell + 4);
ftell += 6;
break;
case "rva":
this.rva = p.getFloat32(ftell + 4);
ftell += 8;
break;
case "vbr":
this.vbr.MaxBlockSize = p.getUint16(ftell + 4);
this.vbr.NoiseLevel = p.getInt16(ftell + 6);
break;
case "comm":
let len = p.getUint8(ftell + 4);
let jisdecoder = new TextDecoder('shift-jis');
this.comment = jisdecoder.decode(hca.slice(ftell + 5, ftell + 5 + len));
break;
default: throw new Error("unknown header sig");
}
// record headerOffset
this.headerOffset[sign] = [lastFtell, ftell];
// do modification if needed
let sectionDataLen = ftell - lastFtell - 4;
let newData = modList[sign];
if (newData != null) {
if (newData.byteLength > sectionDataLen) throw new Error();
hca.set(newData, lastFtell + 4);
hasModDone = true;
}
}
/*
// (ported from) Nyagamon's original code, should be (almost) equivalent to CalculateHfrValues
this.compParam[2] = this.compParam[2] || 1;
let _a = this.compParam[4] - this.compParam[5] - this.compParam[6];
let _b = this.compParam[7];
this.compDec.Reserved1 = _b > 0 ? _a / _b + (_a % _b ? 1 : 0) : 0;
// Translating the above code with meaningful variable names:
this.compDec.TrackCount = this.compDec.TrackCount || 1;
this.compDec.HfrBandCount = this.compDec.TotalBandCount - this.compDec.BaseBandCount - this.compDec.StereoBandCount;
this.HfrGroupCount = this.compDec.BandsPerHfrGroup;
this.compDec.Reserved1 = this.HfrGroupCount > 0 ? this.compDec.HfrBandCount / this.HfrGroupCount + (this.compDec.HfrBandCount % this.HfrGroupCount ? 1 : 0) : 0;
*/
// CalculateHfrValues, ported from VGAudio
if (this.compDec.BandsPerHfrGroup > 0) {
this.compDec.HfrBandCount = this.compDec.TotalBandCount - this.compDec.BaseBandCount - this.compDec.StereoBandCount;
this.HfrGroupCount = HCAUtilFunc.DivideByRoundUp(this.compDec.HfrBandCount, this.compDec.BandsPerHfrGroup);
}
// calculate sample count/offsets
this.fullSampleCount = this.format.blockCount * HCAFrame.SamplesPerFrame;
this.startAtSample = this.format.droppedHeader;
this.fullEndAtSample = this.fullSampleCount - this.format.droppedFooter;
if (this.hasHeader["loop"]) {
this.loopStartAtSample = this.loop.start * HCAFrame.SamplesPerFrame + this.loop.droppedHeader;
this.loopEndAtSample = (this.loop.end + 1) * HCAFrame.SamplesPerFrame - this.loop.droppedFooter;
this.loopSampleCount = this.loopEndAtSample - this.loopStartAtSample;
this.loopStartTime = (this.loopStartAtSample - this.startAtSample) / this.format.samplingRate;
this.loopDuration = this.loopSampleCount / this.format.samplingRate;
this.loopEndTime = this.loopStartTime + this.loopDuration;
}
this.endAtSample = this.hasHeader["loop"] ? this.loopEndAtSample : this.fullEndAtSample;
this.sampleCount = this.endAtSample - this.startAtSample;
this.duration = this.sampleCount / this.format.samplingRate;
// calculate file/data size
this.dataSize = this.blockSize * this.format.blockCount;
this.fullSize = this.dataOffset + this.dataSize;
if (changeMask || hasModDone) {
// fix checksum if requested
HCACrc16.fix(hca, this.dataOffset - 2);
}
let rawHeader = hca.slice(0, this.dataOffset);
// check validity of parsed values
this.checkValidity();
return rawHeader;
}
private checkValidity(): void {
const results: Array<boolean> = [
this.blockSize > 0,
0 < this.format.blockCount,
0 <= this.startAtSample,
this.startAtSample < this.fullEndAtSample,
this.fullEndAtSample <= this.fullSampleCount,
this.duration > 0,
];
results.find((result, index) => {
if (!result) {
throw new Error(`did not pass normal check on rule ${index}`);
}
});
if (this.hasHeader["loop"]) {
const loopChecks: Array<boolean> = [
this.startAtSample <= this.loopStartAtSample,
this.loopStartAtSample < this.loopEndAtSample,
this.loopEndAtSample <= this.fullEndAtSample,
0 <= this.loopStartTime,
this.loopStartTime < this.loopEndTime,
this.loopEndTime <= this.duration + 1.0 / this.format.samplingRate,
];
loopChecks.find((result, index) => {
if (!result) {
throw new Error(`did not pass loop check on rule ${index}`);
}
});
}
}
getRawHeader(): Uint8Array {
return this.rawHeader.slice(0);
}
private isHeaderChanged(hca: Uint8Array): boolean {
if (hca.length >= this.rawHeader.length) {
for (let i = 0; i < this.rawHeader.length; i++) {
if (hca[i] != this.rawHeader[i]) {
return true;
}
}
} else return true;
return false;
}
modify(hca: Uint8Array, sig: string, newData: Uint8Array): void {
// reparse header if needed
if (this.isHeaderChanged(hca)) {
this.parseHeader(hca, false, false, {});
}
// prepare to modify data in-place
let modList: Record<string, Uint8Array> = {};
modList[sig] = newData;
let encrypt = this.cipher != 0;
if (sig === "ciph") {
encrypt = new DataView(newData.buffer, newData.byteOffset, newData.byteLength).getUint16(0) != 0;
}
// do actual modification & check validity
this.rawHeader = this.parseHeader(hca, true, encrypt, modList);
}
static addHeader(hca: Uint8Array, sig: string, newData: Uint8Array): Uint8Array {
// sig must consist of 1-4 ASCII characters
if (sig.length < 1 || sig.length > 4) throw new Error();
let newSig = new Uint8Array(4);
for (let i = 0; i < 4; i++) {
let c = sig.charCodeAt(i);
if (c >= 0x80) throw new Error();
newSig[i] = c;
}
// parse header & check validty
let info = new HCAInfo(hca);
// check whether specified header section already exists
if (info.hasHeader[sig]) throw new Error(`header section ${sig} already exists`);
// prepare a newly allocated buffer
let newHca = new Uint8Array(hca.byteLength + newSig.byteLength + newData.byteLength);
let insertOffset = info.headerOffset["pad"][0];
// copy existing headers (except padding)
newHca.set(hca.subarray(0, insertOffset), 0);
// copy inserted header
newHca.set(newSig, insertOffset);
newHca.set(newData, insertOffset + newSig.byteLength);
// copy remaining data (padding and blocks)
newHca.set(hca.subarray(insertOffset, hca.byteLength), insertOffset + newSig.byteLength + newData.byteLength);
// update dataOffset
info.dataOffset += newSig.byteLength + newData.byteLength;
let p = new DataView(newHca.buffer, newHca.byteOffset, newHca.byteLength);
p.setInt16(6, info.dataOffset);
// fix checksum
HCACrc16.fix(newHca, info.dataOffset - 2);
// reparse header & recheck validty
info = new HCAInfo(newHca);
return newHca;
}
static addCipherHeader(hca: Uint8Array, cipherType?: number): Uint8Array {
let newData = new Uint8Array(2);
if (cipherType != null) new DataView(newData.buffer).setUint16(0, cipherType);
return this.addHeader(hca, "ciph", newData);
}
static fixHeaderChecksum(hca: Uint8Array): Uint8Array {
let p = new DataView(hca.buffer, hca.byteOffset, 8);
let head = this.getSign(p, 0, false, false);
if (head !== "HCA") {
throw new Error("Not a HCA file");
}
let dataOffset = p.getUint16(6);
HCACrc16.fix(hca, dataOffset - 2);
return hca;
}
calcInWavSize(mode = 32): HCAInfoInWavSize {
switch (mode) {
case 0: // float
case 8: case 16: case 24: case 32: // integer
break;
default:
mode = 32;
}
let bitsPerSample = mode == 0 ? 32 : mode;
let sampleSizeInWav = this.format.channelCount * bitsPerSample / 8;
return this.inWavSize = {
bitsPerSample: bitsPerSample,
sample: sampleSizeInWav,
block: HCAFrame.SamplesPerFrame * sampleSizeInWav,
dropped: {
header: this.format.droppedHeader * sampleSizeInWav,
footer: this.format.droppedFooter * sampleSizeInWav,
},
loop: this.hasHeader["loop"] ? {
loopPart: (this.loopEndAtSample - this.loopStartAtSample) * sampleSizeInWav,
dropped: {
header: this.loop.droppedHeader * sampleSizeInWav,
footer: this.loop.droppedFooter * sampleSizeInWav,
}
} : undefined,
}
}
constructor(hca: Uint8Array, changeMask: boolean = false, encrypt: boolean = false) {
// if changeMask == true, (un)mask the header sigs in-place
this.rawHeader = this.parseHeader(hca, changeMask, encrypt, {});
}
}
interface HCAInfoInWavSize {
bitsPerSample: number,
sample: number,
block: number,
dropped: {
header: number,
footer: number,
}
loop?: {
loopPart: number,
dropped: {
header: number,
footer: number,
}
}
}
class HCAUtilFunc {
static DivideByRoundUp(value: number, divisor: number): number {
return Math.ceil(value / divisor);
}
static GetHighNibble(value: number): number {
if (value > 0xff) throw new Error();
if (value < -0x80) throw new Error();
return (value >>> 4) & 0xF;
}
static GetLowNibble(value: number): number {
if (value > 0xff) throw new Error();
if (value < -0x80) throw new Error();
return value & 0xF;
}
private static readonly SignedNibbles = [0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1];
static GetHighNibbleSigned(value: number) {
if (value > 0xff) throw new Error();
if (value < -0x80) throw new Error();
return this.SignedNibbles[(value >>> 4) & 0xF];
}
static GetLowNibbleSigned(value: number) {
if (value > 0xff) throw new Error();
if (value < -0x80) throw new Error();
return this.SignedNibbles[value & 0xF];
}
static CombineNibbles(high: number, low: number) {
return ((high << 4) | (low & 0xF)) & 0xFF;
}
static GetNextMultiple(value: number, multiple: number): number {
if (multiple <= 0)
return value;
if (value % multiple == 0)
return value;
return value + multiple - value % multiple;
}
static SignedBitReverse32(value: number): number {
if (value > 0xffffffff) throw new Error();
if (value < -0x80000000) throw new Error();
value = ((value & 0xaaaaaaaa) >>> 1) | ((value & 0x55555555) << 1);
value = ((value & 0xcccccccc) >>> 2) | ((value & 0x33333333) << 2);
value = ((value & 0xf0f0f0f0) >>> 4) | ((value & 0x0f0f0f0f) << 4);
value = ((value & 0xff00ff00) >>> 8) | ((value & 0x00ff00ff) << 8);
return ((value & 0xffff0000) >>> 16) | ((value & 0x0000ffff) << 16);
}
static UnsignedBitReverse32(value: number): number {
return this.SignedBitReverse32(value) >>> 0;
}
static UnsignedBitReverse32Trunc(value: number, bitCount: number): number {
return this.UnsignedBitReverse32(value) >>> (32 - bitCount);
}
static SignedBitReverse32Trunc(value: number, bitCount: number): number {
return this.UnsignedBitReverse32Trunc(value >>> 0, bitCount);
}
static BitReverse8(value: number): number {
if (value > 0xff) throw new Error();
if (value < -0x80) throw new Error();
value >>>= 0;
value = ((value & 0xaa) >>> 1) | ((value & 0x55) << 1);
value = ((value & 0xcc) >>> 2) | ((value & 0x33) << 2);
return (((value & 0xf0) >>> 4) | ((value & 0x0f) << 4)) >>> 0;
}
static Clamp(value: number, min: number, max: number): number {
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static DebugAssert(condition: any) {
if (!condition) throw new Error("DebugAssert failed");
}
}
export class HCA {
constructor() {
}
static decrypt(hca: Uint8Array, key1?: any, key2?: any, subkey?: any): Uint8Array {
return this.decryptOrEncrypt(hca, false, key1, key2, subkey);
}
static encrypt(hca: Uint8Array, key1?: any, key2?: any, subkey?: any): Uint8Array {
return this.decryptOrEncrypt(hca, true, key1, key2, subkey);
}
static decryptOrEncrypt(hca: Uint8Array, encrypt: boolean, key1?: any, key2?: any, subkey?: any): Uint8Array {
// in-place decryption/encryption
// handle subkey
let mixed = HCACipher.mixWithSubkey(key1, key2, subkey);
key1 = mixed.key1;
key2 = mixed.key2;
// parse header
let info = new HCAInfo(hca); // throws "Not a HCA file" if mismatch
if (!encrypt && !info.hasHeader["ciph"]) {
return hca; // not encrypted
} else if (encrypt && !info.hasHeader["ciph"]) {
throw new Error("Input hca lacks \"ciph\" header section. Please call HCAInfo.addCipherHeader(hca) first.");
}
let cipher: HCACipher;
switch (info.cipher) {
case 0:
// not encrypted
if (encrypt) cipher = new HCACipher(key1, key2).invertTable();
else return hca;
break;
case 1:
// encrypted with "no key"
if (encrypt) throw new Error("already encrypted with \"no key\", please decrypt first");
else cipher = new HCACipher("none"); // ignore given keys
break;
case 0x38:
// encrypted with keys - will yield incorrect waveform if incorrect keys are given!
if (encrypt) throw new Error("already encrypted with specific keys, please decrypt with correct keys first");
else cipher = new HCACipher(key1, key2);
break;
default:
throw new Error("unknown ciph.type");
}
for (let i = 0; i < info.format.blockCount; ++i) {
let ftell = info.dataOffset + info.blockSize * i;
let block = hca.subarray(ftell, ftell + info.blockSize);
// verify block checksum
HCACrc16.verify(block, info.blockSize - 2);
// decrypt/encrypt block
cipher.mask(block, 0, info.blockSize - 2);
// fix checksum
HCACrc16.fix(block, info.blockSize - 2);
}
// re-(un)mask headers, and set ciph header to new value
let newCipherData = new Uint8Array(2);
let newCipherType = encrypt ? cipher.getType() : 0;
new DataView(newCipherData.buffer).setUint16(0, newCipherType);
info.modify(hca, "ciph", newCipherData);
return hca;
}
static findKey(
hca: Uint8Array, givenKeyList?: [any, any][], subkey?: any, threshold = 0.5, depth = 1024
): [number, number] | undefined {
let keyList: [number, number][], unmixedKeyList: [number, number][];
if (givenKeyList == null) {
keyList = HCAKnownKeys;
} else {
keyList = givenKeyList.map((keys) => [HCACipher.parseKey(keys[0]), HCACipher.parseKey(keys[1])]);
HCAKnownKeys.forEach((keys) => keyList?.push(keys));
}
unmixedKeyList = keyList.slice();
if (subkey != null) {
// handle subkey
keyList = keyList.map((keys) => {
let mixed = HCACipher.mixWithSubkey(keys[0], keys[1], subkey);
return [mixed.key1, mixed.key2];
});
}
// parse header
const info = new HCAInfo(hca); // throws "Not a HCA file" if mismatch
if (info.cipher == 0) return; // not encrypted
const frame = new HCAFrame(info);
const scores = keyList.map(() => 0);
let cipher: HCACipher | undefined;
const testKey = (block: Uint8Array, keys: [number, number]): boolean => {
if (cipher == null) cipher = new HCACipher(keys[0], keys[1]);
// decrypt block
block = block.slice();
cipher.mask(block, 0, info.blockSize - 2);
// test if the key is correct
let reader = new HCABitReader(block);
let result = false;
try {
result = HCAPacking.UnpackFrame(frame, reader);
} catch (e) { }
if (!result) {
cipher = undefined;
}
return result;
}
let testedBlockCount = 0;
for (let i = 0, lastFound = -1; i < info.format.blockCount && i < depth; i++) {
let ftell = info.dataOffset + info.blockSize * i;
let block = hca.subarray(ftell, ftell + info.blockSize);
let found = -1;
if (lastFound != -1) {
// test last found key
if (testKey(block, keyList[lastFound])) found = lastFound;
}
if (found == -1) {
// last found key does not match, test others
found = keyList.findIndex((keys, index) => index == lastFound ? false : testKey(block, keys));
}
if (found != -1) {
lastFound = found;
scores[found]++;
}
testedBlockCount++;
}
let bestScore = 0, bestIndex = -1;
scores.forEach((s, i) => s > bestScore && (bestScore = s, bestIndex = i));
if (bestIndex == -1 || bestScore / testedBlockCount < threshold) return; // cannot found valid key
else return unmixedKeyList[bestIndex];
}
static decode(hca: Uint8Array, mode = 32, loop = 0, volume = 1.0) {
switch (mode) {
case 0: // float
case 8: case 16: case 24: case 32: // integer
break;
default:
mode = 32;
}
if (volume > 1) volume = 1;
else if (volume < 0) volume = 0;
let info = new HCAInfo(hca); // throws "Not a HCA file" if mismatch
let frame = new HCAFrame(info);
if (info.hasHeader["ciph"] && info.cipher != 0) {
throw new Error("HCA is encrypted, please decrypt it first before decoding");
}
// prepare output WAV file
const outputWav = new HCAWav(info, mode, loop);
const fileBuf = outputWav.fileBuf;
const dataPart = outputWav.dataPart;
// calculate in-WAV size
let inWavSize = info.calcInWavSize(mode);
// decode blocks (frames)
let failedBlocks = [], lastError = undefined;
for (let i = 0, offset = 0; i < info.format.blockCount; i++) {
let lastDecodedSamples = i * HCAFrame.SamplesPerFrame;
let currentDecodedSamples = lastDecodedSamples + HCAFrame.SamplesPerFrame;
if (currentDecodedSamples <= info.startAtSample || lastDecodedSamples >= info.endAtSample) {
continue;
}
let startOffset = info.dataOffset + info.blockSize * i;
let block = hca.subarray(startOffset, startOffset + info.blockSize);
try {
this.decodeBlock(frame, block);
} catch (e) {
failedBlocks.push(i);
lastError = e;
frame = new HCAFrame(info);
}
let wavebuff: Uint8Array;
if (lastDecodedSamples < info.startAtSample || currentDecodedSamples > info.endAtSample) {
// crossing startAtSample/endAtSample, skip/drop specified bytes
wavebuff = this.writeToPCM(frame, mode, volume);
if (lastDecodedSamples < info.startAtSample) {
let skippedSize = (info.startAtSample - lastDecodedSamples) * inWavSize.sample;
wavebuff = wavebuff.subarray(skippedSize, inWavSize.block);
} else if (currentDecodedSamples > info.endAtSample) {
let writeSize = (info.endAtSample - lastDecodedSamples) * inWavSize.sample;
wavebuff = wavebuff.subarray(0, writeSize);
} else throw Error("should never go here");
dataPart.set(wavebuff, offset);
} else {
wavebuff = this.writeToPCM(frame, mode, volume, dataPart, offset);
}
offset += wavebuff.byteLength;
}
if (failedBlocks.length > 0) {
console.error(`error decoding following blocks, filled zero`, failedBlocks, lastError);
}
// decoding done, then just copy looping part
if (info.hasHeader["loop"] && loop) {
// "tail" beyond loop end is dropped
// copy looping audio clips
if (inWavSize.loop == null) throw new Error();
let preLoopSizeInWav = inWavSize.sample * (info.loopStartAtSample - info.startAtSample);
let src = dataPart.subarray(preLoopSizeInWav, preLoopSizeInWav + inWavSize.loop.loopPart);
for (let i = 0, start = preLoopSizeInWav + inWavSize.loop.loopPart; i < loop; i++) {
let dst = dataPart.subarray(start, start + inWavSize.loop.loopPart);
dst.set(src);
start += inWavSize.loop.loopPart;
}
}
return fileBuf;
}
static decodeBlock(frame: HCAFrame, block: Uint8Array): void {
let info = frame.Hca;
if (block.byteLength != info.blockSize) throw new Error();
// verify checksum
HCACrc16.verify(block, info.blockSize - 2);
// decode
HCADecoder.DecodeFrame(block, frame);
}
static writeToPCM(frame: HCAFrame, mode = 32, volume = 1.0,
writer?: Uint8Array, ftell?: number): Uint8Array {
switch (mode) {
case 0: // float
case 8: case 16: case 24: case 32: // integer
break;
default:
mode = 32;
}
if (volume > 1) volume = 1;
else if (volume < 0) volume = 0;
// create new writer if not specified
let info = frame.Hca;
if (writer == null) {
writer = new Uint8Array(HCAFrame.SamplesPerFrame * info.format.channelCount * (mode == 0 ? 32 : mode) / 8);
if (ftell == null) {
ftell = 0;
}
} else {
if (ftell == null) throw new Error();
}
// write decoded data into writer
let p = new DataView(writer.buffer, writer.byteOffset, writer.byteLength);
let ftellBegin = ftell;
for (let sf = 0; sf < HCAFrame.SubframesPerFrame; sf++) {
for (let s = 0; s < HCAFrame.SamplesPerSubFrame; s++) {
for (let c = 0; c < frame.Channels.length; c++) {
let f = frame.Channels[c].PcmFloat[sf][s] * volume;
if (f > 1) f = 1;
else if (f < -1) f = -1;
switch (mode) {
case 8:
// must be unsigned
p.setUint8(ftell, f * 0x7F + 0x80);
ftell += 1;
break;
case 16:
// for above 8-bit integer, little-endian signed integer is used
// (setUint16/setInt16 actually doesn't seem to make any difference here)
p.setInt16(ftell, f * 0x7FFF, true);
ftell += 2;
break;
case 24:
// there's no setInt24, write 3 bytes with setUint8 respectively
f *= 0x7FFFFF;
p.setUint8(ftell, f & 0xFF);
p.setUint8(ftell + 1, f >> 8 & 0xFF);
p.setUint8(ftell + 2, f >> 16 & 0xFF);
ftell += 3;
break;
case 32:
p.setInt32(ftell, f * 0x7FFFFFFF, true);
ftell += 4;
break;
case 0:
// float
p.setFloat32(ftell, f, true);
ftell += 4;
break;
default:
throw new Error("unknown mode");
}
}
}
}
return writer.subarray(ftellBegin, ftell);
}
static fixChecksum(hca: Uint8Array): Uint8Array {
HCAInfo.fixHeaderChecksum(hca);
let info = new HCAInfo(hca);
for (let i = 0; i < info.format.blockCount; i++) {
let ftell = info.dataOffset + i * info.blockSize;
let block = hca.subarray(ftell, ftell + info.blockSize);
HCACrc16.fix(block, info.blockSize - 2);
}
return hca;
}
}
class HCAWav {
readonly fileBuf: Uint8Array;
readonly dataPart: Uint8Array;
readonly waveRiff: HCAWavWaveRiffHeader;
readonly fmt: HCAWavFmtChunk;
readonly note?: HCAWavCommentChunk;
readonly smpl?: HCAWaveSmplChunk;
constructor(info: HCAInfo, mode = 32, loop = 0) {
switch (mode) {
case 0: // float
case 8: case 16: case 24: case 32: // integer
break;
default:
mode = 32;
}
if (isNaN(loop)) throw new Error("loop is not number");
loop = Math.floor(loop);
if (loop < 0) throw new Error();
let inWavSize = info.calcInWavSize(mode);
let dataSize = inWavSize.sample * info.sampleCount;
if (loop > 0) {
if (inWavSize.loop == null) throw new Error();
dataSize += inWavSize.loop.loopPart * loop;
}
// prepare metadata chunks and data chunk header
this.fmt = new HCAWavFmtChunk(info, mode);
if (info.hasHeader["comm"]) this.note = new HCAWavCommentChunk(info);
if (info.hasHeader["loop"]) this.smpl = new HCAWaveSmplChunk(info);
this.waveRiff = new HCAWavWaveRiffHeader(
8 + this.fmt.size
+ (this.note == null ? 0 : 8 + this.note.size)
+ 8 + dataSize
+ (this.smpl == null ? 0 : 8 + this.smpl.size)
);
// get bytes of prepared chunks
let waveRiffHeader = this.waveRiff.get();
let fmtChunk = this.fmt.get();
let noteChunk = this.note != null ? this.note.get() : new Uint8Array(0);
let dataChunkHeader = new Uint8Array(8);
dataChunkHeader.set(new TextEncoder().encode("data"));
new DataView(dataChunkHeader.buffer).setUint32(4, dataSize, true);
let smplChunk = this.smpl != null ? this.smpl.get() : new Uint8Array(0);
// create whole-file buffer
this.fileBuf = new Uint8Array(8 + this.waveRiff.size);
// copy prepared metadata chunks and data chunk header to whole-file buffer
let writtenLength = 0;
[waveRiffHeader, fmtChunk, noteChunk, dataChunkHeader].forEach((chunk) => {
this.fileBuf.set(chunk, writtenLength);
writtenLength += chunk.byteLength;
});
// skip dataPart since it's empty
this.dataPart = this.fileBuf.subarray(writtenLength, writtenLength + dataSize);
writtenLength += dataSize;
// copy the last prepared chunk to whole-file buffer
this.fileBuf.set(smplChunk, writtenLength);
writtenLength += smplChunk.byteLength;
if (writtenLength != this.fileBuf.byteLength) throw new Error();
}
}
class HCAWavWaveRiffHeader {
readonly size: number;
constructor(size: number) {
if (isNaN(size)) throw new Error("size must be number");
size = Math.floor(size);
if (size <= 0) throw new Error();
this.size = 4 + size; // "WAVE" + remaining part
}
get(): Uint8Array {
let buf = new ArrayBuffer(12);
let ret = new Uint8Array(buf);
let p = new DataView(buf);
let te = new TextEncoder();
ret.set(te.encode("RIFF"), 0);
p.setUint32(4, this.size, true);
ret.set(te.encode("WAVE"), 8);
return ret;
}
}
class HCAWavFmtChunk {
readonly size = 16;
readonly formatTag: number;
readonly channelCount: number;
readonly samplesPerSec: number;
readonly bytesPerSec: number;
readonly blockAlign: number;
readonly bitsPerSample: number;
constructor(info: HCAInfo, mode = 32) {
switch (mode) {
case 0: // float
case 8: case 16: case 24: case 32: // integer
break;
default:
mode = 32;
}
let inWavSize = info.calcInWavSize(mode);
this.formatTag = mode > 0 ? 1 : 3;
this.channelCount = info.format.channelCount;
this.samplesPerSec = info.format.samplingRate;
this.bytesPerSec = inWavSize.sample * info.format.samplingRate;
this.blockAlign = inWavSize.sample;
this.bitsPerSample = inWavSize.bitsPerSample;
}
get(): Uint8Array {
let buf = new ArrayBuffer(8 + this.size);
let ret = new Uint8Array(buf);
let p = new DataView(buf);
let te = new TextEncoder();
ret.set(te.encode("fmt "), 0);
p.setUint32(4, this.size, true);
p.setUint16(8, this.formatTag, true);
p.setUint16(10, this.channelCount, true);
p.setUint32(12, this.samplesPerSec, true);
p.setUint32(16, this.bytesPerSec, true);
p.setUint16(20, this.blockAlign, true);
p.setUint16(22, this.bitsPerSample, true);
return ret;
}
}
class HCAWavCommentChunk {
readonly size: number;
readonly commentBuf: Uint8Array;
constructor(info: HCAInfo) {
this.commentBuf = new TextEncoder().encode(info.comment);
let size = this.commentBuf.byteLength;
size += 4;
if (size % 4) size += 4 - size % 4;
this.size = size;
}
get(): Uint8Array {
let buf = new ArrayBuffer(8 + this.size);
let ret = new Uint8Array(buf);
let p = new DataView(buf);
let te = new TextEncoder();
ret.set(te.encode("note"), 0);
p.setUint32(4, this.size, true);
ret.set(this.commentBuf, 8);
return ret;
}
}
class HCAWaveSmplChunk {
readonly size = 60;
readonly manufacturer = 0;
readonly product = 0;
readonly samplePeriod: number;
readonly MIDIUnityNote = 0x3c;
readonly MIDIPitchFraction = 0;
readonly SMPTEFormat = 0;
readonly SMPTEOffset: number;
readonly sampleLoops = 1;
readonly samplerData = 0x18;
readonly loop_Identifier = 0;
readonly loop_Type = 0;
readonly loop_Start: number;
readonly loop_End: number;
readonly loop_Fraction = 0;
readonly loop_PlayCount = 0;
constructor(info: HCAInfo) {
if (!info.hasHeader["loop"]) throw new Error("missing \"loop\" header");
this.samplePeriod = (1 / info.format.samplingRate * 1000000000);
this.loop_Start = info.loopStartAtSample - info.startAtSample;
this.loop_End = info.loopEndAtSample - info.startAtSample;
this.SMPTEOffset = 1;
}
get(): Uint8Array {
let buf = new ArrayBuffer(8 + this.size);
let ret = new Uint8Array(buf);
let p = new DataView(buf);
let te = new TextEncoder();
ret.set(te.encode("smpl"), 0);
p.setUint32(4, this.size, true);
p.setUint32(8, this.manufacturer, true);
p.setUint32(12, this.product, true);
p.setUint32(16, this.samplePeriod, true);
p.setUint32(20, this.MIDIUnityNote, true);
p.setUint32(24, this.MIDIPitchFraction, true);
p.setUint32(28, this.SMPTEFormat, true);
p.setUint32(32, this.SMPTEOffset, true);
p.setUint32(36, this.sampleLoops, true);
p.setUint32(40, this.samplerData, true);
p.setUint32(44, this.loop_Identifier, true);
p.setUint32(48, this.loop_Type, true);
p.setUint32(52, this.loop_Start, true);
p.setUint32(56, this.loop_End, true);
p.setUint32(60, this.loop_Fraction, true);
p.setUint32(64, this.loop_PlayCount, true);
return ret;
}
}
class HCABitReader {
Buffer: Uint8Array;
dv: DataView;
LengthBits: number;
Position: number;
get Remaining(): number {
return this.LengthBits - this.Position;
}
constructor(buffer: Uint8Array) {
this.Buffer = buffer;
this.dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
this.LengthBits = buffer.length * 8;
this.Position = 0;
}
ReadInt(bitCount: number): number {
let value: number = this.PeekInt(bitCount);