-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhca.html
648 lines (635 loc) · 27.4 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
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>HCA decoder demo</h1>
<hr>
<button disabled id="startworkerbtn">start background worker</button><br>
<button disabled id="shutdownbtn">shutdown background worker</button><br>
<hr>
<h3>Choose a HCA 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" onchange="buttons.loadfilebtn = this.files.length > 0"><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="bgm01_anime02_hca.hca"><br>
<button id="downloadbtn">download</button><br>
<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>Note: output waveform will be nothing but unpleasant meaningless noise if incorrect keys are given!</i><br>
<hr>
<h3>Decode the whole file</h3>
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="number" step="1" min="0" max="100" placeholder="0-100" id="volumeinput" value="100"><br>
Note:<br>
(1) Setting decoding mode to <b>zero means 32-bit float mode</b>, or <b>8/16/24/32-bit integer mode</b> otherwise.<br>
(2) Loop count is <b>ignored if HCA header doesn't have loop section</b><br>
(3) 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>
(4) When <b>decoding the whole file</b>, setting loop count to <b>zero</b> means: <b>disabling loop</b>.</b><br>
<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>
<button disabled id="fixcsumbtn">fix checksum</button><br>
<button disabled id="encryptbtn">encrypt</button><br>
<button disabled id="decryptbtn">decrypt</button><br>
<button disabled id="decodebtn">decode</button><br>
<audio id="audioElement" controls></audio>
<!-- <script src="https://unpkg.com/@ffmpeg/[email protected]/dist/ffmpeg.min.js"></script> -->
<script type="module">
const hcaJsUrl = new URL("hca.js", document.baseURI);
var hcaJsModule, hcaJsObjUrl, HCAInfo, HCAWorker;
// mime types
const defMimeType = "application/octet-stream";
const mimeTypeMap = {
wav: "audio/x-wav",
hca: defMimeType,
}
// HCAWorker instance
var worker = null;
// dragged file
var draggedFile = null;
// local file picker
const localfile = document.getElementById("localfile");
const localfileform = document.getElementById("localfileform");
// reset state on refresh
// https://bugzilla.mozilla.org/show_bug.cgi?id=685657
localfileform.reset();
// input HCA URL
const urlinput = document.getElementById("urlinput");
// file name
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],
]],
["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],
]],
["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};
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},
});
}
// 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,
},
}
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: "decodebtn",
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;
document.body.insertBefore(document.createElement("br"), refNode);
document.body.insertBefore(el, refNode);
// update value
this.value = val;
},
});
}
function clearAllData() {
localfileform.reset();
for (let suffix in hcaFileData) {
hcaFileData[suffix].data = 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 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 (HCAInfo == null) HCAInfo = hcaJsModule.HCAInfo;
if (HCAWorker == null) HCAWorker = hcaJsModule.HCAWorker;
worker = await HCAWorker.create(hcaJsObjUrl);
console.log("started background worker");
}
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 = await file.arrayBuffer();
hcaFileData.original.data = new Uint8Array(ab);
self.textContent = "load picked file (successful)";
// let the button bounce
self.disabled = false;
// next step
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();
hcaFileData.original.data = new Uint8Array(ab);
self.textContent = "download (successful)";
// let the button bounce
self.disabled = false;
// next step
buttons.infobtn = true;
buttons.fixcsumbtn = true;
},
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.decodebtn = !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;
},
decodebtn: 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;
},
};
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;},
});
}
buttons.startworkerbtn = "click"; // start background worker
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;
default:
buttons[btnID] = false;
}
}
}
resetButtonsExcept(); // same to above, reset state on refresh
async function encryptOrDecrypt(self, isEncrypting) {
const action = isEncrypting ? "encrypt" : "decrypt";
const opposite = isEncrypting ? "decrypt" : "encrypt";
// disable both buttons
self.disabled = true;
buttons[opposite + "btn"] = false;
self.textContent = action + "ing...";
// disable decodebtn if necessary
if (!isEncrypting)
buttons.decodebtn = false
// prepare data
let hca = hcaFileData[
[opposite + "ed", "fixed_checksum", "original"].find((suffix) => {
if (hcaFileData[suffix].data != null) {
console.log(`${action}ing ${suffix} data...`);
return true;
}
})
].data;
if (isEncrypting && !hcaInfoTable.body.data.hasHeader["ciph"]) {
// check for ciph header section
console.log("input HCA lacks ciph header section, adding it");
hca = await worker.addCipherHeader(hca);
} else {
hca = hca.slice(0); // just copy to new buffer
}
// start to encrypt/decrypt
try {
worker.tick();
// although decryption/encryption is done in-place,
// however since we are not using SharedArrayBuffer,
// the background worker is still actually overwritting a newly allocated buffer
let resultPromise = worker[action](hca, keys.key1, keys.key2);
worker.tock(isEncrypting ? "encryption" : "decryption");
let result = await resultPromise;
self.textContent = action + " (done)";
// update data
hcaFileData[action + "ed"].data = result;
// next steps
buttons[opposite + "btn"] = true;
if (!isEncrypting)
buttons.decodebtn = true;
} catch (e) {
console.error(e);
self.textContent = "Error during " + (isEncrypting ? "encryption" : "decryption");
}
}
</script>
</body>
</html>