forked from y2361547758/hca.js
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhca.html
1181 lines (1145 loc) · 49.9 KB
/
hca.html
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
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
max-width: 100%;
max-height: 100%;
}
body .hidden {
display: none;
visibility: hidden;
}
body .overlay {
position: fixed;
z-index: 9999;
top: 0;
left: 0;
height: 100%;
width: 100%;
justify-content: center;
background-color: #000;
color: #fff;
filter: opacity(0.5);
}
</style>
</head>
<body>
<div id="audioctx_unlocker" class="hidden">
<div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">
AudioContext is locked.<br>Click to unlock.
</div>
</div>
<h1>HCA decoder demo</h1>
<a href="https://github.com/y2361547758/hca.js">GitHub repo</a>
<hr>
<button disabled id="startworkerbtn">start background worker</button><br>
<button disabled id="shutdownbtn">shutdown background worker</button><br>
<hr>
<h3>Choose a HCA or AWB file</h3>
Drag & drop a file here,<br>
<form id="localfileform">
Or pick a local file: <input type="file" id="localfile" accept=".hca,application/octet-stream"><br>
<input type="checkbox" id="hcaonly" checked>
<label for="hcaonly">pick HCA file only (uncheck if unable to pick)</label><br>
</form>
<b><u>Don't forget to</u></b> <button disabled id="loadfilebtn">load picked file</button><br>
Or download from URL: <input type="text" spellcheck="false" id="urlinput" value="bgm22_battle01_hca.hca"><br>
<button id="downloadbtn">download</button><br>
<div id="awbsubsongswitcher"></div>
<hr>
<h3>Set keys for decryption/encryption</h3>
key1=<input type="text" spellcheck="false" id="key1input" value="0x01395C51"><br>
key2=<input type="text" spellcheck="false" id="key2input" value="0x00000000"><br>
<i>(optional) </i>subkey=<input type="text" spellcheck="false" id="subkeyinput" value="0x0"><br>
<i>Note: output waveform will be (almostly all) silence if incorrect keys are given!</i><br>
<hr>
<h3>Streaming (<a href="https://developer.mozilla.org/en-US/docs/Web/API/AudioWorklet">AudioWorklet API</a>)</h3>
<input type="checkbox" checked id="awautoplayondrop">
<label for="awautoplyondrop">Automatically play drag & dropped HCA file</label><br>
<b><u>Some browsers like Safari (Apple WebKit) may lock AudioContext initially, which blocks auto-play.<br>
To unlock AudioContext (so that auto-play will no longer be blocked),<br>
please click anywhere on this page after drag & drop.</u></b><br>
Load a HCA file for playing, which has been fully loaded/downloaded above:<br>
<button id="awloadwholehcabtn">Load</button><br>
Load directly from the URL above, without fully downloading the whole file:<br>
<button id="awloadfromurlbtn">Load</button><br>
Progress control:<br>
<input type="checkbox" id="awplayinbackground">
<label for="awplayinbackground">Play in background (may glitch)</label><br>
<button id="awresumebtn">Play/Resume</button><br>
<button id="awpausebtn">Pause</button><br>
<button id="awstopbtn">Stop</button><br>
<a href="#volumeslider">Volume control</a> (in "decoding parameters" section)<br>
<hr>
<h3>Decode the whole file</h3>
Note:<br>
(1) <b>Please click "get HCA info" button first.</b><br>
(2) Setting decoding mode to <b>zero means 32-bit float mode</b>, or <b>8/16/24/32-bit integer mode</b>
otherwise.<br>
(3) Loop count is <b>ignored if HCA header doesn't have loop section</b><br>
(4) Loop count doesn't count the existing part which is originally supposed to be looped.<br>
<b>In other words, actual loop count will be: the number set here plus one.</b><br>
(5) When <b>decoding the whole file</b>, setting loop count to <b>zero</b> means: <b>disabling loop</b>.</b><br>
<fieldset>
<legend>HCA info</legend>
<button disabled id="infobtn">get HCA info</button><br>
<style>
table {
border-top: 1px solid #000;
border-left: 1px solid #000;
border-spacing: 0;
}
tbody td {
border-bottom: 1px solid #000;
border-right: 1px solid #000;
min-width: 8ch;
}
thead tr th,
tfoot tr th {
background-color: #fff;
color: #000;
border-bottom: 1px solid #000;
border-right: 1px solid #000;
}
</style>
<table id="hcaInfoTable">
<thead>
<tr>
<th colspan="3">HCA info</th>
</tr>
</thead>
<tbody>
<tr>
<td>(Not loaded)</td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset>
<legend>Checksum</legend>
<button disabled id="fixcsumbtn">fix checksum</button><br>
</fieldset>
<fieldset>
<legend>Cipher</legend>
<button disabled id="encryptbtn">encrypt</button><br>
<button disabled id="decryptbtn">decrypt</button><br>
</fieldset>
<fieldset>
<legend>Decoding parameters</legend>
Decoding mode: <input type="number" step="8" min="0" max="32" placeholder="0-99" id="decodingmodeinput"
value="16"><br>
Loop count: <input type="number" step="1" min="0" max="99" placeholder="0-99" id="loopcountinput" value="0"><br>
Volume: <input type="range" step="1" min="0" max="100" placeholder="0-100" id="volumeslider" value="100">
<input type="number" step="1" min="0" max="100" placeholder="0-100" id="volumeinput" value="100"><br>
<i>This volume control affects <a href="#awresumebtn">AudioWorklet</a> and <a
href="#webaudioplaybtn">WebAudio</a> playing as well.</i><br>
</fieldset>
<fieldset>
<legend>Decode to HTML5 Audio</legend>
<button disabled id="decodetoh5btn">decode</button><br>
<audio id="audioElement" controls></audio><br>
</fieldset>
<fieldset>
<legend>Decode to WebAudio AudioBufferSourceNode</legend>
<b>Playing will seamlessly loop if HCA supports looping.</b><br>
<button disabled id="decodetowabtn">decode</button><br>
<input type="checkbox" id="webaudioplayinbackground">
<label for="webaudioplayinbackground">Play in background (may glitch)</label><br>
<button disabled id="webaudioplaybtn">Play</button><br>
<button disabled id="webaudiopausebtn">Pause</button><br>
<button disabled id="webaudiostopbtn">Stop</button><br>
</fieldset>
<!-- <script src="https://unpkg.com/@ffmpeg/[email protected]/dist/ffmpeg.min.js"></script> -->
<script>
var AWBSubsongSelect = null;
</script>
<script type="module">
const hcaJsUrl = new URL("hca.js", document.baseURI);
var hcaJsModule, hcaJsObjUrl, AWBArchive, HCAInfo, HCAWorker, HCAWebAudioLoopPlayer;
// mime types
const defMimeType = "application/octet-stream";
const mimeTypeMap = {
wav: "audio/x-wav",
hca: defMimeType,
}
// HCAWorker instance
var worker = null;
// HCAWebAudioLoopPlayer instance
var webAudioLoopPlayer = null;
// dragged file
var draggedFile = null;
// parsed AWB
var parsedAWB = null;
// local file picker
const localfile = document.getElementById("localfile");
const localfileform = document.getElementById("localfileform");
// onchange does not work on iOS Safari
localfile.addEventListener("change", function (ev) { buttons.loadfilebtn = this.files.length > 0; });
// reset state on refresh
// https://bugzilla.mozilla.org/show_bug.cgi?id=685657
localfileform.reset();
// workaround for iOS Safari file picker
document.getElementById("hcaonly").addEventListener("change", function (ev) {
localfile.accept = ev.target.checked ? ".hca,application/octet-stream" : "";
});
// AWB subsong switcher
const awbsubsongswitcher = document.getElementById("awbsubsongswitcher");
AWBSubsongSelect = function (selected, doNotPlay) {
let index = selected.id.replace(/^awb_subsong_index_/, "");
fileName = `${AWBFileName}_${index}.hca`;
hcaFileData.original.data = parsedAWB.hcaFiles[index].file;
if (!doNotPlay && document.getElementById("awautoplayondrop").checked) {
// doNotPlay=true, will play in "drop" event
buttons.awloadwholehcabtn = "click";
buttons.awresumebtn = "click";
}
}
function setAWBSubSongSwitcher(enable) {
if (!enable) {
awbsubsongswitcher.innerHTML = "";
keys.subkey = "0x0";
return;
}
const subkey = `0x${parsedAWB.subkey.toString(16).toUpperCase()}`;
console.log(`AWB archive version=[${parsedAWB.version}]`
+ `, subsong count=[${parsedAWB.hcaFiles.length}], subkey=[${subkey}]`);
const listEntries = parsedAWB.hcaFiles.map((entry, index) => {
// filter out non-HCA entries
if (entry.file.byteLength == 0) return;
try {
new HCAInfo(entry.file);
} catch (e) {
return;
}
// convert to HTML
return `<div><input type=\"radio\" name=\"awb_subsong_id\" id=\"awb_subsong_index_${index}\"`
+ ` onclick=\"AWBSubsongSelect(this);\">`
+ `<label for=\"awb_subsong_index_${index}\">waveID=${entry.waveID}</label>`
+ `</div>`;
}).filter((str) => str != null).join("\n");
keys.subkey = subkey;
awbsubsongswitcher.innerHTML = `<fieldset><legend>AWB archive subsongs</legend>\n`
+ `${listEntries}\n`
+ `</fieldset>`;
}
// input HCA URL
const urlinput = document.getElementById("urlinput");
// file name
var AWBFileName = null;
var fileName = null;
// HCA info table
const hcaInfoTable = {
el: document.getElementById("hcaInfoTable"),
body: {
el: document.getElementById("hcaInfoTable")
.getElementsByTagName('tbody')[0],
defText: document.getElementById("hcaInfoTable")
.getElementsByTagName('tbody')[0]
.getElementsByTagName("td")[0]
.textContent,
data: {},
},
}
Object.defineProperty(hcaInfoTable.body, "data", {
get: function () { return this.value },
set: function (val) {
// clear existing content
for (let i = hcaInfoTable.body.el.getElementsByTagName("tr").length - 1; i >= 0; i--) {
hcaInfoTable.body.el.deleteRow(i);
}
function appendRow(cells, rowspan) {
let newRow = hcaInfoTable.body.el.insertRow(-1);
cells.forEach((val, idx) => {
let newCell = newRow.insertCell(idx);
if (rowspan != null && idx == 0)
newCell.setAttribute("rowspan", rowspan);
if (cells.length < 3 && idx == cells.length - 1)
newCell.setAttribute("colspan", cells.length - idx + 1);
let newText = val != null
? document.createTextNode("" + val)
: (() => {
let italic = document.createElement("i");
italic.innerHTML = "(not defined)";
return italic;
})();
newCell.appendChild(newText);
});
}
function toHex(num) {
const padding = "0000";
let hex = padding + num.toString(padding.length * 4).toUpperCase();
return "0x" + hex.substring(hex.length - padding.length, hex.length)
}
if (val == null || !val instanceof HCAInfo) {
appendRow([hcaInfoTable.body.defText]);
return; // nothing to add
}
// add given content
let info = val;
const hcaInfoTextArray = [
["Version", info.version],
["Header size", info.dataOffset],
["Format", !info.hasHeader["fmt"] ? null : [
["Channels", info.format.channelCount],
["Sampling Rate", info.format.samplingRate],
["Blocks", info.format.blockCount],
["Dropped smpl. (head)", info.format.droppedHeader],
["Dropped smpl. (tail)", info.format.droppedFooter],
["Duration (calc)", `${info.duration.toFixed(3)}s`],
]],
["Block size", !info.hasHeader["comp"] && !info.hasHeader["dec"] ? null : info.blockSize],
["Bitrate (kbps)", !info.hasHeader["comp"] && !info.hasHeader["dec"] ? null : info.kbps],
["VBR", info.hasHeader["vbr"] ? "yes" : "no"],
["ATH", !info.hasHeader["ath"] ? null : toHex(info.ath)],
["Loop", !info.hasHeader["loop"] ? null : [
["Start", info.loop.start],
["End", info.loop.end],
["Dropped smpl. (head)", info.loop.droppedHeader],
["Dropped smpl. (tail)", info.loop.droppedFooter],
["StartTime (calc)", `${info.loopStartTime.toFixed(3)}s`],
["EndTime (calc)", `${info.loopEndTime.toFixed(3)}s`],
["Duration (calc)", `${info.loopDuration.toFixed(3)}s`],
]],
["Cipher", !info.hasHeader["ciph"] ? null : toHex(info.cipher)],
["RVA (volume)", !info.hasHeader["rva"] ? null : info.rva],
["Comment", !info.hasHeader["comm"] ? null : info.comment],
];
for (let item of hcaInfoTextArray) {
let key = item[0];
let val = item[1];
if (Array.isArray(val)) {
let textList = val[0].slice(0);
textList.unshift(key);
appendRow(textList, val.length);
val.shift();
val.forEach((item) => appendRow(item))
} else {
appendRow([key, val]);
}
}
// update value
this.value = val;
},
});
// keys
const keys = { key1: undefined, key2: undefined, subkey: undefined };
for (let key in keys) {
Object.defineProperty(keys, key, {
get: function () { return document.getElementById(key + "input").value },
set: function (val) { document.getElementById(key + "input").value = val },
});
}
async function testAndFindValidKeyAsync() {
worker.tick();
let resultPromise = worker.findKey(hcaFileData.original.data, [[keys.key1, keys.key2]], keys.subkey);
worker.tock(`findKey`);
let result = await resultPromise;
if (result != null) {
result = result.map((k) => `0x${k.toString(16).toUpperCase()}`);
console.log(`found valid key`, result);
keys.key1 = result[0];
keys.key2 = result[1];
} else {
console.warn(`not encrypted, or no valid key found!`);
}
}
// mode/loop/volume
const decodingParam = {
mode: {
el: document.getElementById("decodingmodeinput"),
defVal: 16,
},
loop: {
el: document.getElementById("loopcountinput"),
defVal: 0,
},
volumePerCent: {
el: document.getElementById("volumeinput"),
defVal: 100,
},
}
function setVolume(val) {
val = Number(val) / 100;
if (worker != null && worker.awHcaPlayer != null) {
worker.awHcaPlayer.volume = val;
}
if (webAudioLoopPlayer != null) {
webAudioLoopPlayer.volume = val;
}
}
document.getElementById("volumeslider").addEventListener("input", (ev) => {
const val = ev.target.value;
document.getElementById("volumeinput").value = val;
setVolume(val);
});
document.getElementById("volumeinput").addEventListener("input", (ev) => {
const val = ev.target.value;
const slider = document.getElementById("volumeslider");
if (slider.value != val) {
slider.value = val;
}
setVolume(val);
});
// play in background checkbox
const awplayinbackground = document.getElementById("awplayinbackground");
awplayinbackground.addEventListener("change", (ev) => {
if (worker == null || worker.awHcaPlayer == null) return;
worker.awHcaPlayer.playInBackground = ev.target.checked;
}, false);
const webaudioplayinbackground = document.getElementById("webaudioplayinbackground");
webaudioplayinbackground.addEventListener("change", (ev) => {
if (webAudioLoopPlayer == null) return;
webAudioLoopPlayer.playInBackground = ev.target.checked;
}, false);
for (let paramName in decodingParam) {
let el = decodingParam[paramName].el;
let defVal = decodingParam[paramName].defVal;
let attr = {};
["min", "max", "step"].forEach((attrName) => attr[attrName] = el.getAttribute(attrName));
let clampVal = function (val) {
if (val == null || val === "")
return defVal;
val = parseInt(val);
if (isNaN(val))
return defVal;
if (val % attr.step != 0)
val = Math.floor(val / attr.step);
else if (val < attr.min)
val = attr.min;
else if (val > attr.max)
val = attr.max;
return val;
}
Object.defineProperty(decodingParam, paramName, {
get: function () {
let clamped = clampVal(el.value);
el.value = "" + clamped;
return clamped;
},
set: function (val) {
el.value = "" + clampVal(val);
}
});
}
// HCA file data
const hcaFileData = {
// original HCA file content
original: {
btnID: "downloadbtn",
data: {},
},
// after fixing checksum
fixed_checksum: {
btnID: "fixcsumbtn",
data: {},
},
// after decryption
decrypted: {
btnID: "decryptbtn",
data: {},
},
// after encryption
encrypted: {
btnID: "encryptbtn",
data: {},
},
// after decoding
decoded: {
btnID: "decodetoh5btn",
data: {},
},
}
for (let suffix in hcaFileData) {
Object.defineProperty(hcaFileData[suffix], "data", {
get: function () { return this.value },
set: function (val) {
this.value = null; // clear existing data
const fileExtRegEx = /\.([^\.]+)$/;
let newFileName = fileName.replace(fileExtRegEx, "_" + suffix + ".$1");
if (suffix === "decoded")
newFileName = newFileName.replace(fileExtRegEx, ".wav");
let id = suffix + "-download-link";
let el = document.getElementById(id);
if (el != null) {
// remove existing download link
URL.revokeObjectURL(el.getAttribute("href"));
el.nextSibling.remove();
el.remove();
}
if (val == null) {
console.log(`hcaFileData ${suffix} cleared`);
return; // nothing to create
}
console.log(`hcaFileData ${suffix} byteLength=${val.byteLength}`);
// create new download link
el = document.createElement("a");
el.setAttribute("id", id);
el.setAttribute("download", newFileName);
let extName = newFileName.match(fileExtRegEx)[0];
let mimeType = mimeTypeMap[extName];
if (mimeType == null) mimeType = defMimeType;
el.setAttribute("href", URL.createObjectURL(new Blob([val], { type: mimeType })));
el.innerHTML = newFileName;
let refNode = document.getElementById(hcaFileData[suffix].btnID).nextSibling;
refNode.parentElement.insertBefore(document.createElement("br"), refNode);
refNode.parentElement.insertBefore(el, refNode);
// update value
this.value = val;
},
});
}
function clearAllData() {
localfileform.reset();
for (let suffix in hcaFileData) {
hcaFileData[suffix].data = null;
}
setAWBSubSongSwitcher(null);
hcaInfoTable.body.data = null;
audioElement.src = null;
console.log(`cleared all data`);
}
// Audio element
const audioElement = {
el: document.getElementById("audioElement"),
src: ""
};
Object.defineProperty(audioElement, "src", {
get: function () { return this.value },
set: function (val) {
if (this.value != null && this.value != "")
URL.revokeObjectURL(this.value);
if (val == null || val === "") {
this.value = audioElement.el.src = "";
return;
}
let newUrl;
if (val instanceof ArrayBuffer || val.buffer instanceof ArrayBuffer) {
newUrl = URL.createObjectURL(new Blob([val], { type: mimeTypeMap.wav }));
} else {
newUrl = val;
}
this.value = audioElement.el.src = newUrl;
}
});
// buttons
const hcaWorkerLoadedEvent = new CustomEvent("hcaworkerloaded");
const audioCtxUnlockedEvent = new CustomEvent("audioctxunlocked");
const buttons = {
startworkerbtn: async (self) => {
if (worker == null) {
if (hcaJsObjUrl == null) {
const response = await fetch(hcaJsUrl.href);
const blob = new Blob([await response.arrayBuffer()], { type: "text/javascript" });
hcaJsObjUrl = URL.createObjectURL(blob);
}
if (hcaJsModule == null) {
hcaJsModule = await import(hcaJsObjUrl);
}
if (AWBArchive == null) AWBArchive = hcaJsModule.AWBArchive;
if (HCAInfo == null) HCAInfo = hcaJsModule.HCAInfo;
if (HCAWorker == null) HCAWorker = hcaJsModule.HCAWorker;
if (HCAWebAudioLoopPlayer == null) HCAWebAudioLoopPlayer = hcaJsModule.HCAWebAudioLoopPlayer;
worker = await HCAWorker.create(hcaJsObjUrl);
console.log("started background worker");
window.dispatchEvent(hcaWorkerLoadedEvent);
}
self.disabled = true; // added because button won't grey out if there's any await above
buttons.shutdownbtn = true;
},
shutdownbtn: async (self) => {
if (worker != null) {
await worker.shutdown();
worker = null;
console.log("background worker is now shut down");
}
self.disabled = true; // added together with above startworkerbtn
buttons.startworkerbtn = true;
},
loadfilebtn: async (self) => {
let file = null;
if (draggedFile != null) {
self.textContent = "loading dragged file...";
file = draggedFile;
draggedFile = null;
} else {
self.textContent = "loading picked file...";
file = localfile.files[0];
}
let newFileName = file.name;
// update fileName
fileName = newFileName;
// clear all existing data
clearAllData();
resetButtonsExcept(self.id);
// update data
let ab;
if (file.arrayBuffer == null) {
let objUrl = URL.createObjectURL(file);
let resp = await fetch(objUrl);
URL.revokeObjectURL(objUrl);
ab = await resp.arrayBuffer();
} else {
ab = await file.arrayBuffer();
}
// parse AWB
AWBFileName = null;
parsedAWB = null;
if (AWBArchive.isAWB(new Uint8Array(ab))) {
try {
parsedAWB = new AWBArchive(new Uint8Array(ab));
} catch (e) {
console.error(`error parsing AWB archive`, e);
}
}
if (parsedAWB != null && parsedAWB.hcaFiles.length > 0) {
AWBFileName = fileName;
setAWBSubSongSwitcher(true);
AWBSubsongSelect({ id: "awb_subsong_index_0" }, true); // doNotPlay=true, will play in "drop" event
} else {
setAWBSubSongSwitcher(null);
hcaFileData.original.data = new Uint8Array(ab);
}
// find valid key
await testAndFindValidKeyAsync();
self.textContent = "load picked file (successful)";
// no need to let the button bounce
// next step
buttons.awloadwholehcabtn = true;
buttons.infobtn = true;
buttons.fixcsumbtn = true;
},
downloadbtn: async (self) => {
self.textContent = "downloading...";
let requestUrl = urlinput.value;
if (requestUrl === "") {
self.textContent = "download (empty URL)";
self.disabled = false;
return;
}
let response = null;
try {
response = await fetch(requestUrl);
} catch (e) {
console.error(e);
self.textContent = "download (network error)";
self.disabled = false;
return;
}
if (response.status != 200) {
console.error("download failed,", response);
self.textContent = `download (failed, ${response.status} ${response.statusText})`;
self.disabled = false;
return;
}
// get filename from Content-Disposition
let cd = response.headers.get("Content-Disposition");
let newFileName = null;
if (cd != null) {
let splitted = cd.split(";");
let cdFileName = splitted.find((substr) => substr.startsWith("filename="));
if (cdFileName != null) {
newFileName = cdFileName.substring("filename=".length)
.replaceAll(" ", "")
.replaceAll("\"", "");
}
}
// failed to get filename from Content-Disposition, try URL
const fileNameRegEx = /[^\/^\\]+$/;
if (newFileName == null || newFileName === "") {
let urlFilename = [response.url, requestUrl].find((url) => url != null && url.match(fileNameRegEx));
if (urlFilename != null)
newFileName = urlFilename.match(fileNameRegEx)[0];
}
// failed to get filename, use default filename
if (newFileName == null || newFileName === "") {
newFileName = "downloaded.hca";
}
// strip query string
let stripped = newFileName.match(/^[^\?]+/);
if (stripped != null)
newFileName = stripped[0];
// update fileName
fileName = newFileName;
// clear all existing data
clearAllData();
resetButtonsExcept(self.id);
// update data
let ab = await response.arrayBuffer();
// parse AWB
AWBFileName = null;
parsedAWB = null;
if (AWBArchive.isAWB(new Uint8Array(ab))) {
try {
parsedAWB = new AWBArchive(new Uint8Array(ab));
} catch (e) {
console.error(`error parsing AWB archive`, e);
}
}
if (parsedAWB != null && parsedAWB.hcaFiles.length > 0) {
AWBFileName = fileName;
setAWBSubSongSwitcher(true);
AWBSubsongSelect({ id: "awb_subsong_index_0" }, true); // doNotPlay=true, will play in "drop" event
} else {
setAWBSubSongSwitcher(null);
hcaFileData.original.data = new Uint8Array(ab);
}
self.textContent = "download (successful)";
// find valid key
await testAndFindValidKeyAsync();
// let the button bounce
self.disabled = false;
// next step
buttons.awloadwholehcabtn = true;
buttons.infobtn = true;
buttons.fixcsumbtn = true;
},
awloadwholehcabtn: async (self) => {
try {
await worker.loadHCAForPlaying(hcaFileData.original.data, keys.key1, keys.key2, keys.subkey);
worker.awHcaPlayer.playInBackground = awplayinbackground.checked;
self.textContent = "Load (successful)";
} catch (e) {
self.textContent = "Load (failed)";
console.error(e);
}
// let the button bounce
self.disabled = false;
// next step
buttons.awpausebtn = false;
buttons.awresumebtn = true;
buttons.awstopbtn = true;
// TODO pause/rewind/fast-forward etc
},
awloadfromurlbtn: async (self) => {
try {
await worker.loadHCAForPlaying(urlinput.value, keys.key1, keys.key2, keys.subkey);
worker.awHcaPlayer.playInBackground = awplayinbackground.checked;
self.textContent = "Load (successful)";
} catch (e) {
self.textContent = "Load (failed)";
console.error(e);
}
// let the button bounce
self.disabled = false;
// next step
buttons.awpausebtn = false;
buttons.awresumebtn = true;
buttons.awstopbtn = true;
// TODO rewind/fast-forward etc
},
awpausebtn: async (self) => {
try {
await worker.pausePlaying();
self.textContent = "Paused";
} catch (e) {
self.textContent = "Pause (Error)";
console.log(e);
// let the button bounce
self.disabled = false;
}
// next step
buttons.awresumebtn = true;
},
awresumebtn: async (self) => {
try {
await worker.resumePlaying();
self.textContent = "Playing/Resumed";
} catch (e) {
self.textContent = "Play/Resume (Error)";
console.log(e);
// let the button bounce
self.disabled = false;
}
// next step
buttons.awpausebtn = true;
},
awstopbtn: async (self) => {
try {
await worker.stopPlaying();
self.textContent = "Stopped";
} catch (e) {
self.textContent = "Stop (Error)";
console.log(e);
// let the button bounce
self.disabled = false;
}
// next step
buttons.awpausebtn = false;
buttons.awresumebtn = false;
},
infobtn: async (self) => {
let hca = hcaFileData[
["fixed_checksum", "original"].find((suffix) => {
if (hcaFileData[suffix].data != null) {
console.log(`get HCA info from ${suffix} file data`);
return true;
}
})
].data;
try {
let info = new HCAInfo(hca);
self.textContent = "get HCA info (successful)";
// update table content
hcaInfoTable.body.data = info;
// next step
let isEncrypted = info.hasHeader["ciph"] && info.cipher != 0;
buttons.encryptbtn = !isEncrypted;
buttons.decryptbtn = isEncrypted;
buttons.decodetoh5btn = !isEncrypted;
buttons.decodetowabtn = !isEncrypted;
} catch (e) {
console.error(e);
self.textContent = "get HCA info (failed)";
}
// let the button bounce
self.disabled = false;
},
fixcsumbtn: async (self) => {
try {
worker.tick();
let newHcaPromise = worker.fixChecksum(hcaFileData.original.data);
worker.tock("fix checksum");
let newHca = await newHcaPromise;
// update data
hcaFileData.fixed_checksum.data = newHca;
self.textContent = "fix checksum (successful)";
} catch (e) {
console.error(e);
self.textContent = "fix checksum (failed)";
}
// let the button bounce
self.disabled = false;
},
encryptbtn: async (self) => {
await encryptOrDecrypt(self, true);
// let the button bounce
self.disabled = false;
},
decryptbtn: async (self) => {
await encryptOrDecrypt(self, false);
// let the button bounce
self.disabled = false;
},
decodetoh5btn: async (self) => {
// prepare data
let hca = hcaFileData[
["decrypted", "fixed_checksum", "original"].find((suffix) => {
if (hcaFileData[suffix].data != null) {
console.log(`decoding ${suffix} data...`);
return true;
}
})
].data;
// start decoding
try {
worker.tick();
let decodedPromise = worker.decode(hca,
decodingParam.mode, decodingParam.loop, decodingParam.volumePerCent / 100);
worker.tock("decoding");
let decoded = await decodedPromise;
// update data
hcaFileData.decoded.data = decoded;
self.textContent = "decode (done)";
// next step (play)
audioElement.src = decoded;
} catch (e) {
console.error(e);
self.textContent = "decode (failed)";
}
// let the button bounce
self.disabled = false;
},
decodetowabtn: async (self) => {
// prepare data
let hca = hcaFileData[
["decrypted", "fixed_checksum", "original"].find((suffix) => {
if (hcaFileData[suffix].data != null) {
console.log(`decoding ${suffix} data...`);
return true;
}
})
].data;
// start decoding
try {
worker.tick();
let decodedPromise = HCAWebAudioLoopPlayer.create(hca, worker, decodingParam.volumePerCent / 100);
worker.tock("decoding");
let newPlayer = await decodedPromise;
// update player instance
if (webAudioLoopPlayer != null) await webAudioLoopPlayer.stop();
webAudioLoopPlayer = newPlayer;
webAudioLoopPlayer.playInBackground = webaudioplayinbackground.checked;
self.textContent = "decode (done)";
// next step (play)
buttons.webaudioplaybtn = true;
} catch (e) {
console.error(e);
self.textContent = "decode (failed)";
}
// let the button bounce
self.disabled = false;
},
webaudioplaybtn: async (self) => {
try {
webAudioLoopPlayer.play();
self.textContent = "Playing/Resumed";
} catch (e) {
self.textContent = "Play/Resume (Error)";
console.log(e);
// let the button bounce
self.disabled = false;
}
// next step
buttons.webaudiopausebtn = true;
buttons.webaudiostopbtn = true;
},
webaudiopausebtn: async (self) => {
try {
webAudioLoopPlayer.pause();
self.textContent = "Paused";
} catch (e) {
self.textContent = "Pause (Error)";
console.log(e);
// let the button bounce
self.disabled = false;
}
// next step
buttons.webaudioplaybtn = true;
},
webaudiostopbtn: async (self) => {
try {
await webAudioLoopPlayer.stop();
self.textContent = "Stopped";
} catch (e) {
self.textContent = "Stop (Error)";
console.log(e);
// let the button bounce
self.disabled = false;
}
// next step
buttons.webaudiopausebtn = false;
buttons.webaudioplaybtn = false;
},
};
const _buttons = {};
for (let id in buttons) {
let el = document.getElementById(id);
let onclick = buttons[id];
el.onclick = (ev) => {
let self = ev.srcElement;
self.disabled = true;
onclick(self);
}
const initialText = el.textContent;
Object.defineProperty(buttons, id, {
get: function () { return !el.disabled },
set: function (val) {
if (val === "click") {
el.disabled = true;
onclick(el);
return;
}
el.textContent = initialText;
el.disabled = !val;
},
});
Object.defineProperty(_buttons, id, {
get: function () { return onclick; },
});
}
function resetButtonsExcept(exceptBtnID) {
for (let btnID in buttons) {
if (btnID !== exceptBtnID) switch (btnID) {
case "startworkerbtn":
buttons[btnID] = worker == null || !worker.isAlive;
break;
case "shutdownbtn":
buttons[btnID] = worker != null && worker.isAlive;
break;
case "loadfilebtn":
buttons[btnID] = false;
break;
case "downloadbtn":
buttons[btnID] = true;
break;
case "awloadwholehcabtn":
buttons[btnID] = false;
break;
case "awloadfromurlbtn":
buttons[btnID] = true;
break;
case "awresumebtn":