web/src/decrypt/xm.ts

67 lines
2.2 KiB
TypeScript
Raw Normal View History

2021-05-23 17:30:38 +00:00
import {Decrypt as RawDecrypt} from "@/decrypt/raw";
import {DecryptResult} from "@/decrypt/entity";
2021-12-14 06:57:48 +00:00
import {AudioMimeType, BytesHasPrefix, GetArrayBuffer, GetCoverFromFile, GetMetaFromFile} from "@/decrypt/utils";
2020-04-23 12:46:08 +00:00
import {parseBlob as metaParseBlob} from "music-metadata-browser";
2020-04-23 12:46:08 +00:00
const MagicHeader = [0x69, 0x66, 0x6D, 0x74]
const MagicHeader2 = [0xfe, 0xfe, 0xfe, 0xfe]
2021-05-23 17:30:38 +00:00
const FileTypeMap: { [key: string]: string } = {
2020-04-23 12:46:08 +00:00
" WAV": ".wav",
"FLAC": ".flac",
" MP3": ".mp3",
" A4M": ".m4a",
}
2021-05-23 17:30:38 +00:00
export async function Decrypt(file: File, raw_filename: string, raw_ext: string): Promise<DecryptResult> {
2020-04-23 12:46:08 +00:00
const oriData = new Uint8Array(await GetArrayBuffer(file));
if (!BytesHasPrefix(oriData, MagicHeader) || !BytesHasPrefix(oriData.slice(8, 12), MagicHeader2)) {
2020-04-23 12:46:08 +00:00
if (raw_ext === "xm") {
2021-05-23 17:30:38 +00:00
throw Error("此xm文件已损坏")
2020-04-23 12:46:08 +00:00
} else {
return await RawDecrypt(file, raw_filename, raw_ext, true)
}
}
let typeText = (new TextDecoder()).decode(oriData.slice(4, 8))
if (!FileTypeMap.hasOwnProperty(typeText)) {
2021-05-23 17:30:38 +00:00
throw Error("未知的.xm文件类型")
2020-04-23 12:46:08 +00:00
}
let key = oriData[0xf]
2020-08-13 07:26:15 +00:00
let dataOffset = oriData[0xc] | oriData[0xd] << 8 | oriData[0xe] << 16
2020-04-23 12:46:08 +00:00
let audioData = oriData.slice(0x10);
let lenAudioData = audioData.length;
for (let cur = dataOffset; cur < lenAudioData; ++cur)
audioData[cur] = (audioData[cur] - key) ^ 0xff;
2020-08-13 07:25:41 +00:00
const ext = FileTypeMap[typeText];
2020-04-23 12:46:08 +00:00
const mime = AudioMimeType[ext];
let musicBlob = new Blob([audioData], {type: mime});
const musicMeta = await metaParseBlob(musicBlob);
2020-04-23 12:46:08 +00:00
if (ext === "wav") {
//todo:未知的编码方式
2021-05-24 14:19:37 +00:00
console.info(musicMeta.common)
2020-04-23 12:46:08 +00:00
musicMeta.common.album = "";
musicMeta.common.artist = "";
musicMeta.common.title = "";
}
const {title, artist} = GetMetaFromFile(raw_filename,
musicMeta.common.title, musicMeta.common.artist,
raw_filename.indexOf("_") === -1 ? "-" : "_")
2020-04-23 12:46:08 +00:00
return {
title,
artist,
ext,
mime,
2020-04-23 12:46:08 +00:00
album: musicMeta.common.album,
picture: GetCoverFromFile(musicMeta),
2020-04-23 12:46:08 +00:00
file: URL.createObjectURL(musicBlob),
2021-05-24 19:06:28 +00:00
blob: musicBlob,
2020-05-14 09:36:16 +00:00
rawExt: "xm"
2020-04-23 12:46:08 +00:00
}
}