klaudio 0.11.2 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/extractor.js CHANGED
@@ -1,213 +1,213 @@
1
- import { execFile } from "node:child_process";
2
- import { readdir, mkdir, stat, chmod } from "node:fs/promises";
3
- import { createWriteStream } from "node:fs";
4
- import { join, extname, basename, resolve as resolvePath } from "node:path";
5
- import { platform, homedir, tmpdir } from "node:os";
6
- import { pipeline } from "node:stream/promises";
7
-
8
- const TOOLS_DIR = join(homedir(), ".klaudio", "tools");
9
-
10
- // Packed audio formats that vgmstream-cli can convert to WAV
11
- const PACKED_EXTENSIONS = new Set([".wem", ".bnk", ".bank", ".fsb", ".pck", ".bun"]);
12
-
13
- /**
14
- * Check if a file is a packed audio format we can extract.
15
- */
16
- export function isPackedAudio(filePath) {
17
- return PACKED_EXTENSIONS.has(extname(filePath).toLowerCase());
18
- }
19
-
20
- /**
21
- * Check if a game directory has extractable packed audio.
22
- */
23
- export async function hasPackedAudio(gamePath) {
24
- const formats = { wem: 0, bnk: 0, bank: 0, fsb: 0, pck: 0 };
25
- await scanForPackedAudio(gamePath, formats, 0);
26
- return {
27
- total: Object.values(formats).reduce((a, b) => a + b, 0),
28
- formats,
29
- };
30
- }
31
-
32
- async function scanForPackedAudio(dir, formats, depth) {
33
- if (depth > 5) return;
34
- try {
35
- const entries = await readdir(dir, { withFileTypes: true });
36
- for (const entry of entries) {
37
- if (entry.isDirectory()) {
38
- await scanForPackedAudio(join(dir, entry.name), formats, depth + 1);
39
- } else if (entry.isFile()) {
40
- const ext = extname(entry.name).toLowerCase().slice(1);
41
- if (ext in formats) formats[ext]++;
42
- }
43
- // Stop early if we found enough
44
- if (Object.values(formats).reduce((a, b) => a + b, 0) > 100) return;
45
- }
46
- } catch { /* skip */ }
47
- }
48
-
49
- /**
50
- * Get the path to vgmstream-cli, downloading it if needed.
51
- */
52
- export async function getVgmstreamPath(onProgress) {
53
- const os = platform();
54
- const exeName = os === "win32" ? "vgmstream-cli.exe" : "vgmstream-cli";
55
- const toolPath = join(TOOLS_DIR, exeName);
56
-
57
- // Check if already downloaded
58
- try {
59
- await stat(toolPath);
60
- return toolPath;
61
- } catch { /* not found, need to download */ }
62
-
63
- if (onProgress) onProgress("Downloading vgmstream-cli...");
64
-
65
- await mkdir(TOOLS_DIR, { recursive: true });
66
-
67
- // Download the appropriate release
68
- const isWindows = os === "win32";
69
- const releaseUrl = isWindows
70
- ? "https://github.com/vgmstream/vgmstream-releases/releases/download/nightly/vgmstream-win64.zip"
71
- : os === "darwin"
72
- ? "https://github.com/vgmstream/vgmstream-releases/releases/download/nightly/vgmstream-mac-cli.tar.gz"
73
- : "https://github.com/vgmstream/vgmstream-releases/releases/download/nightly/vgmstream-linux-cli.tar.gz";
74
-
75
- const archiveExt = isWindows ? ".zip" : ".tar.gz";
76
- const archivePath = join(tmpdir(), `vgmstream${archiveExt}`);
77
-
78
- // Download using Node.js fetch
79
- const response = await fetch(releaseUrl, { redirect: "follow" });
80
- if (!response.ok) throw new Error(`Failed to download vgmstream: ${response.status}`);
81
-
82
- const fileStream = createWriteStream(archivePath);
83
- await pipeline(response.body, fileStream);
84
-
85
- if (onProgress) onProgress("Extracting vgmstream-cli...");
86
-
87
- // Extract: PowerShell for Windows, tar for macOS/Linux
88
- if (isWindows) {
89
- await new Promise((resolve, reject) => {
90
- execFile("powershell.exe", [
91
- "-NoProfile", "-Command",
92
- `Expand-Archive -Path '${archivePath}' -DestinationPath '${TOOLS_DIR}' -Force`,
93
- ], { windowsHide: true }, (err) => {
94
- if (err) reject(err);
95
- else resolve();
96
- });
97
- });
98
- } else {
99
- await new Promise((resolve, reject) => {
100
- execFile("tar", ["xzf", archivePath, "-C", TOOLS_DIR], (err) => {
101
- if (err) reject(err);
102
- else resolve();
103
- });
104
- });
105
- // Make executable
106
- try { await chmod(toolPath, 0o755); } catch { /* ignore */ }
107
- // Remove macOS quarantine attribute so Gatekeeper doesn't block execution
108
- if (os === "darwin") {
109
- try {
110
- await new Promise((resolve) => {
111
- execFile("xattr", ["-d", "com.apple.quarantine", toolPath], () => resolve());
112
- });
113
- } catch { /* ignore — attribute may not exist */ }
114
- }
115
- }
116
-
117
- // Verify it exists
118
- await stat(toolPath);
119
- return toolPath;
120
- }
121
-
122
- /**
123
- * Find all extractable audio files in a game directory.
124
- */
125
- export async function findPackedAudioFiles(gamePath, maxFiles = 50) {
126
- const results = [];
127
-
128
- async function scan(dir, depth = 0) {
129
- if (depth > 5 || results.length >= maxFiles) return;
130
- try {
131
- const entries = await readdir(dir, { withFileTypes: true });
132
- for (const entry of entries) {
133
- if (results.length >= maxFiles) break;
134
- const fullPath = join(dir, entry.name);
135
- if (entry.isDirectory()) {
136
- const lower = entry.name.toLowerCase();
137
- if (["__pycache__", "node_modules", ".git"].some(s => lower.includes(s))) continue;
138
- await scan(fullPath, depth + 1);
139
- } else if (entry.isFile()) {
140
- const ext = extname(entry.name).toLowerCase();
141
- // Formats vgmstream-cli can convert directly
142
- // (.bnk needs bnkextr preprocessing — skip for now)
143
- if (ext === ".wem" || ext === ".fsb" || ext === ".bank" || ext === ".bun") {
144
- results.push({ path: fullPath, name: entry.name, dir });
145
- }
146
- }
147
- }
148
- } catch { /* skip */ }
149
- }
150
-
151
- await scan(gamePath);
152
- return results;
153
- }
154
-
155
- /**
156
- * Extract/convert a packed audio file to WAV using vgmstream-cli.
157
- *
158
- * @param {string} inputPath - Path to .wem/.bnk/.bank/.fsb file
159
- * @param {string} outputDir - Directory to write WAV files to
160
- * @param {string} vgmstreamPath - Path to vgmstream-cli binary
161
- * @returns {string[]} Array of output WAV file paths
162
- */
163
- export async function extractToWav(inputPath, outputDir, vgmstreamPath) {
164
- await mkdir(outputDir, { recursive: true });
165
-
166
- // Resolve to absolute OS-native paths (critical on Windows where
167
- // MSYS uses forward slashes but native exes need backslashes)
168
- const absInput = resolvePath(inputPath);
169
- const ext = extname(absInput).toLowerCase();
170
- const baseName = basename(absInput, ext);
171
- const outputPath = resolvePath(join(outputDir, `${baseName}.wav`));
172
-
173
- return new Promise((resolve, reject) => {
174
- // For .bnk files, vgmstream can extract subsongs
175
- // First try with -S flag to get subsong count
176
- execFile(vgmstreamPath, ["-m", absInput], { windowsHide: true, timeout: 10000 }, (err, stdout) => {
177
- if (err) {
178
- // Single file conversion
179
- execFile(vgmstreamPath, ["-o", outputPath, absInput], { windowsHide: true, timeout: 30000 }, (err2) => {
180
- if (err2) reject(new Error(`Failed to convert ${basename(absInput)}: ${err2.message}`));
181
- else resolve([outputPath]);
182
- });
183
- return;
184
- }
185
-
186
- // Check if it has multiple subsongs
187
- const subsongMatch = stdout.match(/stream count:\s*(\d+)/i) || stdout.match(/subsong count:\s*(\d+)/i);
188
- const subsongCount = subsongMatch ? parseInt(subsongMatch[1]) : 1;
189
-
190
- if (subsongCount <= 1) {
191
- // Single conversion
192
- execFile(vgmstreamPath, ["-o", outputPath, absInput], { windowsHide: true, timeout: 30000 }, (err2) => {
193
- if (err2) reject(new Error(`Failed to convert ${basename(absInput)}: ${err2.message}`));
194
- else resolve([outputPath]);
195
- });
196
- } else {
197
- // Extract each subsong (up to 20)
198
- const count = Math.min(subsongCount, 20);
199
- const outputs = [];
200
- let done = 0;
201
-
202
- for (let i = 1; i <= count; i++) {
203
- const subOutput = join(outputDir, `${baseName}_${String(i).padStart(3, "0")}.wav`);
204
- execFile(vgmstreamPath, ["-o", resolvePath(subOutput), "-s", String(i), absInput], { windowsHide: true, timeout: 30000 }, (err2) => {
205
- if (!err2) outputs.push(subOutput);
206
- done++;
207
- if (done === count) resolve(outputs);
208
- });
209
- }
210
- }
211
- });
212
- });
213
- }
1
+ import { execFile } from "node:child_process";
2
+ import { readdir, mkdir, stat, chmod } from "node:fs/promises";
3
+ import { createWriteStream } from "node:fs";
4
+ import { join, extname, basename, resolve as resolvePath } from "node:path";
5
+ import { platform, homedir, tmpdir } from "node:os";
6
+ import { pipeline } from "node:stream/promises";
7
+
8
+ const TOOLS_DIR = join(homedir(), ".klaudio", "tools");
9
+
10
+ // Packed audio formats that vgmstream-cli can convert to WAV
11
+ const PACKED_EXTENSIONS = new Set([".wem", ".bnk", ".bank", ".fsb", ".pck", ".bun"]);
12
+
13
+ /**
14
+ * Check if a file is a packed audio format we can extract.
15
+ */
16
+ export function isPackedAudio(filePath) {
17
+ return PACKED_EXTENSIONS.has(extname(filePath).toLowerCase());
18
+ }
19
+
20
+ /**
21
+ * Check if a game directory has extractable packed audio.
22
+ */
23
+ export async function hasPackedAudio(gamePath) {
24
+ const formats = { wem: 0, bnk: 0, bank: 0, fsb: 0, pck: 0 };
25
+ await scanForPackedAudio(gamePath, formats, 0);
26
+ return {
27
+ total: Object.values(formats).reduce((a, b) => a + b, 0),
28
+ formats,
29
+ };
30
+ }
31
+
32
+ async function scanForPackedAudio(dir, formats, depth) {
33
+ if (depth > 5) return;
34
+ try {
35
+ const entries = await readdir(dir, { withFileTypes: true });
36
+ for (const entry of entries) {
37
+ if (entry.isDirectory()) {
38
+ await scanForPackedAudio(join(dir, entry.name), formats, depth + 1);
39
+ } else if (entry.isFile()) {
40
+ const ext = extname(entry.name).toLowerCase().slice(1);
41
+ if (ext in formats) formats[ext]++;
42
+ }
43
+ // Stop early if we found enough
44
+ if (Object.values(formats).reduce((a, b) => a + b, 0) > 100) return;
45
+ }
46
+ } catch { /* skip */ }
47
+ }
48
+
49
+ /**
50
+ * Get the path to vgmstream-cli, downloading it if needed.
51
+ */
52
+ export async function getVgmstreamPath(onProgress) {
53
+ const os = platform();
54
+ const exeName = os === "win32" ? "vgmstream-cli.exe" : "vgmstream-cli";
55
+ const toolPath = join(TOOLS_DIR, exeName);
56
+
57
+ // Check if already downloaded
58
+ try {
59
+ await stat(toolPath);
60
+ return toolPath;
61
+ } catch { /* not found, need to download */ }
62
+
63
+ if (onProgress) onProgress("Downloading vgmstream-cli...");
64
+
65
+ await mkdir(TOOLS_DIR, { recursive: true });
66
+
67
+ // Download the appropriate release
68
+ const isWindows = os === "win32";
69
+ const releaseUrl = isWindows
70
+ ? "https://github.com/vgmstream/vgmstream-releases/releases/download/nightly/vgmstream-win64.zip"
71
+ : os === "darwin"
72
+ ? "https://github.com/vgmstream/vgmstream-releases/releases/download/nightly/vgmstream-mac-cli.tar.gz"
73
+ : "https://github.com/vgmstream/vgmstream-releases/releases/download/nightly/vgmstream-linux-cli.tar.gz";
74
+
75
+ const archiveExt = isWindows ? ".zip" : ".tar.gz";
76
+ const archivePath = join(tmpdir(), `vgmstream${archiveExt}`);
77
+
78
+ // Download using Node.js fetch
79
+ const response = await fetch(releaseUrl, { redirect: "follow" });
80
+ if (!response.ok) throw new Error(`Failed to download vgmstream: ${response.status}`);
81
+
82
+ const fileStream = createWriteStream(archivePath);
83
+ await pipeline(response.body, fileStream);
84
+
85
+ if (onProgress) onProgress("Extracting vgmstream-cli...");
86
+
87
+ // Extract: PowerShell for Windows, tar for macOS/Linux
88
+ if (isWindows) {
89
+ await new Promise((resolve, reject) => {
90
+ execFile("powershell.exe", [
91
+ "-NoProfile", "-Command",
92
+ `Expand-Archive -Path '${archivePath}' -DestinationPath '${TOOLS_DIR}' -Force`,
93
+ ], { windowsHide: true }, (err) => {
94
+ if (err) reject(err);
95
+ else resolve();
96
+ });
97
+ });
98
+ } else {
99
+ await new Promise((resolve, reject) => {
100
+ execFile("tar", ["xzf", archivePath, "-C", TOOLS_DIR], (err) => {
101
+ if (err) reject(err);
102
+ else resolve();
103
+ });
104
+ });
105
+ // Make executable
106
+ try { await chmod(toolPath, 0o755); } catch { /* ignore */ }
107
+ // Remove macOS quarantine attribute so Gatekeeper doesn't block execution
108
+ if (os === "darwin") {
109
+ try {
110
+ await new Promise((resolve) => {
111
+ execFile("xattr", ["-d", "com.apple.quarantine", toolPath], () => resolve());
112
+ });
113
+ } catch { /* ignore — attribute may not exist */ }
114
+ }
115
+ }
116
+
117
+ // Verify it exists
118
+ await stat(toolPath);
119
+ return toolPath;
120
+ }
121
+
122
+ /**
123
+ * Find all extractable audio files in a game directory.
124
+ */
125
+ export async function findPackedAudioFiles(gamePath, maxFiles = 50) {
126
+ const results = [];
127
+
128
+ async function scan(dir, depth = 0) {
129
+ if (depth > 5 || results.length >= maxFiles) return;
130
+ try {
131
+ const entries = await readdir(dir, { withFileTypes: true });
132
+ for (const entry of entries) {
133
+ if (results.length >= maxFiles) break;
134
+ const fullPath = join(dir, entry.name);
135
+ if (entry.isDirectory()) {
136
+ const lower = entry.name.toLowerCase();
137
+ if (["__pycache__", "node_modules", ".git"].some(s => lower.includes(s))) continue;
138
+ await scan(fullPath, depth + 1);
139
+ } else if (entry.isFile()) {
140
+ const ext = extname(entry.name).toLowerCase();
141
+ // Formats vgmstream-cli can convert directly
142
+ // (.bnk needs bnkextr preprocessing — skip for now)
143
+ if (ext === ".wem" || ext === ".fsb" || ext === ".bank" || ext === ".bun") {
144
+ results.push({ path: fullPath, name: entry.name, dir });
145
+ }
146
+ }
147
+ }
148
+ } catch { /* skip */ }
149
+ }
150
+
151
+ await scan(gamePath);
152
+ return results;
153
+ }
154
+
155
+ /**
156
+ * Extract/convert a packed audio file to WAV using vgmstream-cli.
157
+ *
158
+ * @param {string} inputPath - Path to .wem/.bnk/.bank/.fsb file
159
+ * @param {string} outputDir - Directory to write WAV files to
160
+ * @param {string} vgmstreamPath - Path to vgmstream-cli binary
161
+ * @returns {string[]} Array of output WAV file paths
162
+ */
163
+ export async function extractToWav(inputPath, outputDir, vgmstreamPath) {
164
+ await mkdir(outputDir, { recursive: true });
165
+
166
+ // Resolve to absolute OS-native paths (critical on Windows where
167
+ // MSYS uses forward slashes but native exes need backslashes)
168
+ const absInput = resolvePath(inputPath);
169
+ const ext = extname(absInput).toLowerCase();
170
+ const baseName = basename(absInput, ext);
171
+ const outputPath = resolvePath(join(outputDir, `${baseName}.wav`));
172
+
173
+ return new Promise((resolve, reject) => {
174
+ // For .bnk files, vgmstream can extract subsongs
175
+ // First try with -S flag to get subsong count
176
+ execFile(vgmstreamPath, ["-m", absInput], { windowsHide: true, timeout: 10000 }, (err, stdout) => {
177
+ if (err) {
178
+ // Single file conversion
179
+ execFile(vgmstreamPath, ["-o", outputPath, absInput], { windowsHide: true, timeout: 30000 }, (err2) => {
180
+ if (err2) reject(new Error(`Failed to convert ${basename(absInput)}: ${err2.message}`));
181
+ else resolve([outputPath]);
182
+ });
183
+ return;
184
+ }
185
+
186
+ // Check if it has multiple subsongs
187
+ const subsongMatch = stdout.match(/stream count:\s*(\d+)/i) || stdout.match(/subsong count:\s*(\d+)/i);
188
+ const subsongCount = subsongMatch ? parseInt(subsongMatch[1]) : 1;
189
+
190
+ if (subsongCount <= 1) {
191
+ // Single conversion
192
+ execFile(vgmstreamPath, ["-o", outputPath, absInput], { windowsHide: true, timeout: 30000 }, (err2) => {
193
+ if (err2) reject(new Error(`Failed to convert ${basename(absInput)}: ${err2.message}`));
194
+ else resolve([outputPath]);
195
+ });
196
+ } else {
197
+ // Extract each subsong (up to 20)
198
+ const count = Math.min(subsongCount, 20);
199
+ const outputs = [];
200
+ let done = 0;
201
+
202
+ for (let i = 1; i <= count; i++) {
203
+ const subOutput = join(outputDir, `${baseName}_${String(i).padStart(3, "0")}.wav`);
204
+ execFile(vgmstreamPath, ["-o", resolvePath(subOutput), "-s", String(i), absInput], { windowsHide: true, timeout: 30000 }, (err2) => {
205
+ if (!err2) outputs.push(subOutput);
206
+ done++;
207
+ if (done === count) resolve(outputs);
208
+ });
209
+ }
210
+ }
211
+ });
212
+ });
213
+ }