klaudio 0.1.0 → 0.2.0-c2cee62
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/README.md +67 -65
- package/package.json +44 -40
- package/src/cache.js +262 -262
- package/src/cli.js +1200 -999
- package/src/extractor.js +203 -203
- package/src/installer.js +161 -128
- package/src/player.js +359 -359
- package/src/presets.js +5 -5
- package/src/scanner.js +41 -6
- package/src/unity.js +241 -0
package/src/player.js
CHANGED
|
@@ -1,359 +1,359 @@
|
|
|
1
|
-
import { execFile, spawn } from "node:child_process";
|
|
2
|
-
import { platform } from "node:os";
|
|
3
|
-
import { resolve, extname, basename, join } from "node:path";
|
|
4
|
-
import { open, mkdir, stat } from "node:fs/promises";
|
|
5
|
-
import { tmpdir } from "node:os";
|
|
6
|
-
import { createHash } from "node:crypto";
|
|
7
|
-
|
|
8
|
-
const MAX_PLAY_SECONDS = 10;
|
|
9
|
-
const FADE_SECONDS = 2; // fade out over last 2 seconds
|
|
10
|
-
|
|
11
|
-
// Formats that Windows MediaPlayer (PresentationCore) can play natively
|
|
12
|
-
const MEDIA_PLAYER_FORMATS = new Set([".wav", ".mp3", ".wma", ".aac"]);
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Determine the best playback strategy for a file on the current OS.
|
|
16
|
-
*/
|
|
17
|
-
function getPlaybackCommand(absPath, { withFade = false } = {}) {
|
|
18
|
-
const os = platform();
|
|
19
|
-
const ext = extname(absPath).toLowerCase();
|
|
20
|
-
|
|
21
|
-
// ffplay args with optional fade-out and silence-skip
|
|
22
|
-
const ffplayArgs = ["-nodisp", "-autoexit", "-loglevel", "quiet"];
|
|
23
|
-
if (withFade) {
|
|
24
|
-
// silenceremove strips leading silence (below -50dB threshold)
|
|
25
|
-
// afade fades out over last FADE_SECONDS before the MAX_PLAY_SECONDS cut
|
|
26
|
-
const fadeStart = MAX_PLAY_SECONDS - FADE_SECONDS;
|
|
27
|
-
const filters = [
|
|
28
|
-
"silenceremove=start_periods=1:start_silence=0.1:start_threshold=-50dB",
|
|
29
|
-
`afade=t=out:st=${fadeStart}:d=${FADE_SECONDS}`,
|
|
30
|
-
];
|
|
31
|
-
ffplayArgs.push("-af", filters.join(","));
|
|
32
|
-
ffplayArgs.push("-t", String(MAX_PLAY_SECONDS));
|
|
33
|
-
}
|
|
34
|
-
ffplayArgs.push(absPath);
|
|
35
|
-
|
|
36
|
-
if (os === "darwin") {
|
|
37
|
-
// afplay doesn't support filters — use ffplay if fade needed, fall back to afplay
|
|
38
|
-
if (withFade) {
|
|
39
|
-
return { type: "exec", cmd: "ffplay", args: ffplayArgs, fallback: "afplay" };
|
|
40
|
-
}
|
|
41
|
-
return { type: "exec", cmd: "afplay", args: [absPath] };
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
if (os === "win32") {
|
|
45
|
-
if (withFade || !MEDIA_PLAYER_FORMATS.has(ext)) {
|
|
46
|
-
// Prefer ffplay for fade support and non-native formats; fall back to PowerShell
|
|
47
|
-
return {
|
|
48
|
-
type: "exec",
|
|
49
|
-
cmd: "ffplay",
|
|
50
|
-
args: ffplayArgs,
|
|
51
|
-
fallback: "powershell",
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
return { type: "powershell", absPath };
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Linux
|
|
58
|
-
if (ext === ".wav" && !withFade) {
|
|
59
|
-
return { type: "exec", cmd: "aplay", args: [absPath] };
|
|
60
|
-
}
|
|
61
|
-
return {
|
|
62
|
-
type: "exec",
|
|
63
|
-
cmd: "ffplay",
|
|
64
|
-
args: ffplayArgs,
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
function buildPsCommand(absPath, maxSeconds = 0) {
|
|
69
|
-
const limit = maxSeconds > 0 ? maxSeconds : 30;
|
|
70
|
-
const fadeStart = (limit - FADE_SECONDS) * 10; // in 100ms ticks
|
|
71
|
-
return `
|
|
72
|
-
Add-Type -AssemblyName PresentationCore
|
|
73
|
-
$player = New-Object System.Windows.Media.MediaPlayer
|
|
74
|
-
$player.Open([System.Uri]::new("${absPath.replace(/\\/g, "/")}"))
|
|
75
|
-
Start-Sleep -Milliseconds 300
|
|
76
|
-
$player.Play()
|
|
77
|
-
$player.Volume = 1.0
|
|
78
|
-
$elapsed = 0
|
|
79
|
-
while ($player.Position -lt $player.NaturalDuration.TimeSpan -and $player.NaturalDuration.HasTimeSpan -and $elapsed -lt ${limit * 10}) {
|
|
80
|
-
Start-Sleep -Milliseconds 100
|
|
81
|
-
$elapsed++
|
|
82
|
-
if ($elapsed -gt ${fadeStart} -and ${limit * 10} -gt ${fadeStart}) {
|
|
83
|
-
$remaining = ${limit * 10} - $elapsed
|
|
84
|
-
$total = ${FADE_SECONDS * 10}
|
|
85
|
-
if ($total -gt 0) { $player.Volume = [Math]::Max(0, [double]$remaining / [double]$total) }
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
$player.Stop()
|
|
89
|
-
$player.Close()
|
|
90
|
-
`.trim();
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* Get the duration of a WAV file in seconds by reading its header.
|
|
95
|
-
* Returns null if unable to determine.
|
|
96
|
-
*/
|
|
97
|
-
export async function getWavDuration(filePath) {
|
|
98
|
-
const absPath = resolve(filePath);
|
|
99
|
-
const ext = extname(absPath).toLowerCase();
|
|
100
|
-
|
|
101
|
-
// Try ffprobe first (handles all formats and non-standard WAV headers)
|
|
102
|
-
const ffDuration = await getFFprobeDuration(absPath);
|
|
103
|
-
if (ffDuration != null) return ffDuration;
|
|
104
|
-
|
|
105
|
-
// Fallback: parse WAV header directly
|
|
106
|
-
if (ext === ".wav") {
|
|
107
|
-
return getWavDurationFromHeader(absPath);
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
return null;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
async function getWavDurationFromHeader(absPath) {
|
|
114
|
-
let fh;
|
|
115
|
-
try {
|
|
116
|
-
fh = await open(absPath, "r");
|
|
117
|
-
const header = Buffer.alloc(44);
|
|
118
|
-
await fh.read(header, 0, 44, 0);
|
|
119
|
-
|
|
120
|
-
// Verify RIFF/WAVE
|
|
121
|
-
if (header.toString("ascii", 0, 4) !== "RIFF") return null;
|
|
122
|
-
if (header.toString("ascii", 8, 12) !== "WAVE") return null;
|
|
123
|
-
|
|
124
|
-
// Read fmt chunk (assuming standard PCM at offset 20)
|
|
125
|
-
const channels = header.readUInt16LE(22);
|
|
126
|
-
const sampleRate = header.readUInt32LE(24);
|
|
127
|
-
const bitsPerSample = header.readUInt16LE(34);
|
|
128
|
-
|
|
129
|
-
if (sampleRate === 0 || channels === 0 || bitsPerSample === 0) return null;
|
|
130
|
-
|
|
131
|
-
// Data chunk size is at offset 40 in standard WAV
|
|
132
|
-
const dataSize = header.readUInt32LE(40);
|
|
133
|
-
const bytesPerSecond = sampleRate * channels * (bitsPerSample / 8);
|
|
134
|
-
|
|
135
|
-
if (bytesPerSecond === 0) return null;
|
|
136
|
-
return Math.round((dataSize / bytesPerSecond) * 10) / 10;
|
|
137
|
-
} catch {
|
|
138
|
-
return null;
|
|
139
|
-
} finally {
|
|
140
|
-
if (fh) await fh.close();
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
function getFFprobeDuration(absPath) {
|
|
145
|
-
return new Promise((res) => {
|
|
146
|
-
execFile(
|
|
147
|
-
"ffprobe",
|
|
148
|
-
["-v", "quiet", "-show_entries", "format=duration", "-of", "csv=p=0", absPath],
|
|
149
|
-
{ windowsHide: true, timeout: 5000 },
|
|
150
|
-
(err, stdout) => {
|
|
151
|
-
if (err) return res(null);
|
|
152
|
-
const val = parseFloat(stdout.trim());
|
|
153
|
-
if (isNaN(val)) return res(null);
|
|
154
|
-
res(Math.round(val * 10) / 10);
|
|
155
|
-
}
|
|
156
|
-
);
|
|
157
|
-
});
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* Play a sound file. Returns a promise that resolves when playback starts
|
|
162
|
-
* (not when it finishes — we don't want to block).
|
|
163
|
-
*/
|
|
164
|
-
export function playSound(filePath) {
|
|
165
|
-
const absPath = resolve(filePath);
|
|
166
|
-
const strategy = getPlaybackCommand(absPath);
|
|
167
|
-
|
|
168
|
-
return new Promise((resolvePromise) => {
|
|
169
|
-
if (strategy.type === "exec") {
|
|
170
|
-
const child = spawn(strategy.cmd, strategy.args, {
|
|
171
|
-
stdio: "ignore",
|
|
172
|
-
detached: true,
|
|
173
|
-
windowsHide: true,
|
|
174
|
-
});
|
|
175
|
-
child.unref();
|
|
176
|
-
resolvePromise();
|
|
177
|
-
child.on("error", () => {
|
|
178
|
-
if (strategy.fallback === "powershell") {
|
|
179
|
-
const ps = spawn("powershell.exe", ["-NoProfile", "-Command", buildPsCommand(absPath)], {
|
|
180
|
-
stdio: "ignore", detached: true, windowsHide: true,
|
|
181
|
-
});
|
|
182
|
-
ps.unref();
|
|
183
|
-
}
|
|
184
|
-
});
|
|
185
|
-
} else if (strategy.type === "powershell") {
|
|
186
|
-
const child = spawn("powershell.exe", ["-NoProfile", "-Command", buildPsCommand(absPath)], {
|
|
187
|
-
stdio: "ignore", detached: true, windowsHide: true,
|
|
188
|
-
});
|
|
189
|
-
child.unref();
|
|
190
|
-
resolvePromise();
|
|
191
|
-
}
|
|
192
|
-
});
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/**
|
|
196
|
-
* Play a sound and wait for it to finish (for preview mode).
|
|
197
|
-
* Returns { promise, cancel } — call cancel() to stop playback immediately.
|
|
198
|
-
* Playback is clamped to MAX_PLAY_SECONDS.
|
|
199
|
-
*/
|
|
200
|
-
export function playSoundWithCancel(filePath) {
|
|
201
|
-
const absPath = resolve(filePath);
|
|
202
|
-
const strategy = getPlaybackCommand(absPath, { withFade: true });
|
|
203
|
-
let childProcess = null;
|
|
204
|
-
let timer = null;
|
|
205
|
-
let cancelled = false;
|
|
206
|
-
|
|
207
|
-
function killChild() {
|
|
208
|
-
if (childProcess && !childProcess.killed) {
|
|
209
|
-
try {
|
|
210
|
-
// On Windows, spawned processes need taskkill for the process tree
|
|
211
|
-
if (platform() === "win32") {
|
|
212
|
-
spawn("taskkill", ["/pid", String(childProcess.pid), "/f", "/t"], {
|
|
213
|
-
stdio: "ignore", windowsHide: true,
|
|
214
|
-
});
|
|
215
|
-
} else {
|
|
216
|
-
childProcess.kill("SIGTERM");
|
|
217
|
-
}
|
|
218
|
-
} catch { /* ignore */ }
|
|
219
|
-
}
|
|
220
|
-
if (timer) clearTimeout(timer);
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
const cancel = () => {
|
|
224
|
-
cancelled = true;
|
|
225
|
-
killChild();
|
|
226
|
-
};
|
|
227
|
-
|
|
228
|
-
const promise = new Promise((resolvePromise, reject) => {
|
|
229
|
-
function onDone(err) {
|
|
230
|
-
if (timer) clearTimeout(timer);
|
|
231
|
-
if (cancelled) return resolvePromise(); // cancelled — resolve, don't reject
|
|
232
|
-
if (err) reject(err);
|
|
233
|
-
else resolvePromise();
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
function startExec(cmd, args) {
|
|
237
|
-
childProcess = execFile(cmd, args, { windowsHide: true, timeout: (MAX_PLAY_SECONDS + 2) * 1000 }, (err) => {
|
|
238
|
-
if (err && strategy.fallback && !cancelled) {
|
|
239
|
-
if (strategy.fallback === "powershell") {
|
|
240
|
-
childProcess = execFile(
|
|
241
|
-
"powershell.exe",
|
|
242
|
-
["-NoProfile", "-Command", buildPsCommand(absPath, MAX_PLAY_SECONDS)],
|
|
243
|
-
{ windowsHide: true, timeout: (MAX_PLAY_SECONDS + 2) * 1000 },
|
|
244
|
-
(psErr) => onDone(psErr)
|
|
245
|
-
);
|
|
246
|
-
} else if (strategy.fallback === "afplay") {
|
|
247
|
-
// macOS: ffplay not available, fall back to afplay (no fade)
|
|
248
|
-
childProcess = execFile("afplay", [absPath], { timeout: (MAX_PLAY_SECONDS + 2) * 1000 }, (afErr) => onDone(afErr));
|
|
249
|
-
}
|
|
250
|
-
} else {
|
|
251
|
-
onDone(err);
|
|
252
|
-
}
|
|
253
|
-
});
|
|
254
|
-
|
|
255
|
-
// Set a hard timeout to kill after MAX_PLAY_SECONDS
|
|
256
|
-
timer = setTimeout(() => {
|
|
257
|
-
killChild();
|
|
258
|
-
resolvePromise();
|
|
259
|
-
}, MAX_PLAY_SECONDS * 1000);
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
if (strategy.type === "exec") {
|
|
263
|
-
startExec(strategy.cmd, strategy.args);
|
|
264
|
-
} else if (strategy.type === "powershell") {
|
|
265
|
-
childProcess = execFile(
|
|
266
|
-
"powershell.exe",
|
|
267
|
-
["-NoProfile", "-Command", buildPsCommand(absPath, MAX_PLAY_SECONDS)],
|
|
268
|
-
{ windowsHide: true, timeout: (MAX_PLAY_SECONDS + 2) * 1000 },
|
|
269
|
-
(err) => onDone(err)
|
|
270
|
-
);
|
|
271
|
-
timer = setTimeout(() => {
|
|
272
|
-
killChild();
|
|
273
|
-
resolvePromise();
|
|
274
|
-
}, MAX_PLAY_SECONDS * 1000);
|
|
275
|
-
}
|
|
276
|
-
});
|
|
277
|
-
|
|
278
|
-
return { promise, cancel };
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
/**
|
|
282
|
-
* Play a sound and wait for it to finish (legacy — no cancel support).
|
|
283
|
-
*/
|
|
284
|
-
export function playSoundSync(filePath) {
|
|
285
|
-
return playSoundWithCancel(filePath).promise;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/**
|
|
289
|
-
* Process a sound file with ffmpeg: strip leading silence, clamp to MAX_PLAY_SECONDS,
|
|
290
|
-
* and fade out over the last FADE_SECONDS. Returns the path to the processed WAV file.
|
|
291
|
-
* If ffmpeg is not available or the file is already short enough, returns the original path.
|
|
292
|
-
*/
|
|
293
|
-
export async function processSound(filePath) {
|
|
294
|
-
const absPath = resolve(filePath);
|
|
295
|
-
|
|
296
|
-
// First check duration — skip processing if already short
|
|
297
|
-
const duration = await getWavDuration(absPath);
|
|
298
|
-
if (duration != null && duration <= MAX_PLAY_SECONDS) {
|
|
299
|
-
return absPath; // Already short enough, no processing needed
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
// Build a deterministic output path based on input file hash
|
|
303
|
-
const hash = createHash("md5").update(absPath).digest("hex").slice(0, 12);
|
|
304
|
-
const outDir = join(tmpdir(), "klonk-processed");
|
|
305
|
-
const outName = `${basename(absPath, extname(absPath))}_${hash}.wav`;
|
|
306
|
-
const outPath = join(outDir, outName);
|
|
307
|
-
|
|
308
|
-
// Check if already processed
|
|
309
|
-
try {
|
|
310
|
-
await stat(outPath);
|
|
311
|
-
return outPath; // Already exists
|
|
312
|
-
} catch { /* needs processing */ }
|
|
313
|
-
|
|
314
|
-
await mkdir(outDir, { recursive: true });
|
|
315
|
-
|
|
316
|
-
// Build ffmpeg filter chain: silence strip → fade out → clamp duration
|
|
317
|
-
const fadeStart = MAX_PLAY_SECONDS - FADE_SECONDS;
|
|
318
|
-
const filters = [
|
|
319
|
-
"silenceremove=start_periods=1:start_silence=0.1:start_threshold=-50dB",
|
|
320
|
-
`afade=t=out:st=${fadeStart}:d=${FADE_SECONDS}`,
|
|
321
|
-
].join(",");
|
|
322
|
-
|
|
323
|
-
return new Promise((res) => {
|
|
324
|
-
execFile(
|
|
325
|
-
"ffmpeg",
|
|
326
|
-
[
|
|
327
|
-
"-y", "-i", absPath,
|
|
328
|
-
"-af", filters,
|
|
329
|
-
"-t", String(MAX_PLAY_SECONDS),
|
|
330
|
-
"-ar", "44100", "-ac", "2",
|
|
331
|
-
outPath,
|
|
332
|
-
],
|
|
333
|
-
{ windowsHide: true, timeout: 30000 },
|
|
334
|
-
(err) => {
|
|
335
|
-
if (err) {
|
|
336
|
-
// ffmpeg not available or failed — return original
|
|
337
|
-
res(absPath);
|
|
338
|
-
} else {
|
|
339
|
-
res(outPath);
|
|
340
|
-
}
|
|
341
|
-
},
|
|
342
|
-
);
|
|
343
|
-
});
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
/**
|
|
347
|
-
* Generate the shell command string for use in Claude Code hooks.
|
|
348
|
-
*/
|
|
349
|
-
export function getHookPlayCommand(soundFilePath) {
|
|
350
|
-
const normalized = soundFilePath.replace(/\\/g, "/");
|
|
351
|
-
const ext = extname(normalized).toLowerCase();
|
|
352
|
-
const needsFfplay = !MEDIA_PLAYER_FORMATS.has(ext);
|
|
353
|
-
|
|
354
|
-
if (needsFfplay) {
|
|
355
|
-
return `if command -v ffplay &>/dev/null; then ffplay -nodisp -autoexit -loglevel quiet "${normalized}" & elif [[ "$OSTYPE" == "darwin"* ]]; then afplay "${normalized}" & elif [[ "$OSTYPE" == "msys"* ]] || [[ "$OSTYPE" == "cygwin"* ]]; then powershell.exe -NoProfile -Command "Add-Type -AssemblyName PresentationCore; \\$p = New-Object System.Windows.Media.MediaPlayer; \\$p.Open([System.Uri]::new('$(cygpath -w "${normalized}")')); Start-Sleep -Milliseconds 200; \\$p.Play(); Start-Sleep -Seconds 2" & else aplay "${normalized}" & fi`;
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
return `if [[ "$OSTYPE" == "darwin"* ]]; then afplay "${normalized}" & elif [[ "$OSTYPE" == "msys"* ]] || [[ "$OSTYPE" == "cygwin"* ]]; then powershell.exe -NoProfile -Command "Add-Type -AssemblyName PresentationCore; \\$p = New-Object System.Windows.Media.MediaPlayer; \\$p.Open([System.Uri]::new('$(cygpath -w "${normalized}")')); Start-Sleep -Milliseconds 200; \\$p.Play(); Start-Sleep -Seconds 2" & else aplay "${normalized}" & fi`;
|
|
359
|
-
}
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { platform } from "node:os";
|
|
3
|
+
import { resolve, extname, basename, join } from "node:path";
|
|
4
|
+
import { open, mkdir, stat } from "node:fs/promises";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
|
|
8
|
+
const MAX_PLAY_SECONDS = 10;
|
|
9
|
+
const FADE_SECONDS = 2; // fade out over last 2 seconds
|
|
10
|
+
|
|
11
|
+
// Formats that Windows MediaPlayer (PresentationCore) can play natively
|
|
12
|
+
const MEDIA_PLAYER_FORMATS = new Set([".wav", ".mp3", ".wma", ".aac"]);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Determine the best playback strategy for a file on the current OS.
|
|
16
|
+
*/
|
|
17
|
+
function getPlaybackCommand(absPath, { withFade = false } = {}) {
|
|
18
|
+
const os = platform();
|
|
19
|
+
const ext = extname(absPath).toLowerCase();
|
|
20
|
+
|
|
21
|
+
// ffplay args with optional fade-out and silence-skip
|
|
22
|
+
const ffplayArgs = ["-nodisp", "-autoexit", "-loglevel", "quiet"];
|
|
23
|
+
if (withFade) {
|
|
24
|
+
// silenceremove strips leading silence (below -50dB threshold)
|
|
25
|
+
// afade fades out over last FADE_SECONDS before the MAX_PLAY_SECONDS cut
|
|
26
|
+
const fadeStart = MAX_PLAY_SECONDS - FADE_SECONDS;
|
|
27
|
+
const filters = [
|
|
28
|
+
"silenceremove=start_periods=1:start_silence=0.1:start_threshold=-50dB",
|
|
29
|
+
`afade=t=out:st=${fadeStart}:d=${FADE_SECONDS}`,
|
|
30
|
+
];
|
|
31
|
+
ffplayArgs.push("-af", filters.join(","));
|
|
32
|
+
ffplayArgs.push("-t", String(MAX_PLAY_SECONDS));
|
|
33
|
+
}
|
|
34
|
+
ffplayArgs.push(absPath);
|
|
35
|
+
|
|
36
|
+
if (os === "darwin") {
|
|
37
|
+
// afplay doesn't support filters — use ffplay if fade needed, fall back to afplay
|
|
38
|
+
if (withFade) {
|
|
39
|
+
return { type: "exec", cmd: "ffplay", args: ffplayArgs, fallback: "afplay" };
|
|
40
|
+
}
|
|
41
|
+
return { type: "exec", cmd: "afplay", args: [absPath] };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (os === "win32") {
|
|
45
|
+
if (withFade || !MEDIA_PLAYER_FORMATS.has(ext)) {
|
|
46
|
+
// Prefer ffplay for fade support and non-native formats; fall back to PowerShell
|
|
47
|
+
return {
|
|
48
|
+
type: "exec",
|
|
49
|
+
cmd: "ffplay",
|
|
50
|
+
args: ffplayArgs,
|
|
51
|
+
fallback: "powershell",
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
return { type: "powershell", absPath };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Linux
|
|
58
|
+
if (ext === ".wav" && !withFade) {
|
|
59
|
+
return { type: "exec", cmd: "aplay", args: [absPath] };
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
type: "exec",
|
|
63
|
+
cmd: "ffplay",
|
|
64
|
+
args: ffplayArgs,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function buildPsCommand(absPath, maxSeconds = 0) {
|
|
69
|
+
const limit = maxSeconds > 0 ? maxSeconds : 30;
|
|
70
|
+
const fadeStart = (limit - FADE_SECONDS) * 10; // in 100ms ticks
|
|
71
|
+
return `
|
|
72
|
+
Add-Type -AssemblyName PresentationCore
|
|
73
|
+
$player = New-Object System.Windows.Media.MediaPlayer
|
|
74
|
+
$player.Open([System.Uri]::new("${absPath.replace(/\\/g, "/")}"))
|
|
75
|
+
Start-Sleep -Milliseconds 300
|
|
76
|
+
$player.Play()
|
|
77
|
+
$player.Volume = 1.0
|
|
78
|
+
$elapsed = 0
|
|
79
|
+
while ($player.Position -lt $player.NaturalDuration.TimeSpan -and $player.NaturalDuration.HasTimeSpan -and $elapsed -lt ${limit * 10}) {
|
|
80
|
+
Start-Sleep -Milliseconds 100
|
|
81
|
+
$elapsed++
|
|
82
|
+
if ($elapsed -gt ${fadeStart} -and ${limit * 10} -gt ${fadeStart}) {
|
|
83
|
+
$remaining = ${limit * 10} - $elapsed
|
|
84
|
+
$total = ${FADE_SECONDS * 10}
|
|
85
|
+
if ($total -gt 0) { $player.Volume = [Math]::Max(0, [double]$remaining / [double]$total) }
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
$player.Stop()
|
|
89
|
+
$player.Close()
|
|
90
|
+
`.trim();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Get the duration of a WAV file in seconds by reading its header.
|
|
95
|
+
* Returns null if unable to determine.
|
|
96
|
+
*/
|
|
97
|
+
export async function getWavDuration(filePath) {
|
|
98
|
+
const absPath = resolve(filePath);
|
|
99
|
+
const ext = extname(absPath).toLowerCase();
|
|
100
|
+
|
|
101
|
+
// Try ffprobe first (handles all formats and non-standard WAV headers)
|
|
102
|
+
const ffDuration = await getFFprobeDuration(absPath);
|
|
103
|
+
if (ffDuration != null) return ffDuration;
|
|
104
|
+
|
|
105
|
+
// Fallback: parse WAV header directly
|
|
106
|
+
if (ext === ".wav") {
|
|
107
|
+
return getWavDurationFromHeader(absPath);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function getWavDurationFromHeader(absPath) {
|
|
114
|
+
let fh;
|
|
115
|
+
try {
|
|
116
|
+
fh = await open(absPath, "r");
|
|
117
|
+
const header = Buffer.alloc(44);
|
|
118
|
+
await fh.read(header, 0, 44, 0);
|
|
119
|
+
|
|
120
|
+
// Verify RIFF/WAVE
|
|
121
|
+
if (header.toString("ascii", 0, 4) !== "RIFF") return null;
|
|
122
|
+
if (header.toString("ascii", 8, 12) !== "WAVE") return null;
|
|
123
|
+
|
|
124
|
+
// Read fmt chunk (assuming standard PCM at offset 20)
|
|
125
|
+
const channels = header.readUInt16LE(22);
|
|
126
|
+
const sampleRate = header.readUInt32LE(24);
|
|
127
|
+
const bitsPerSample = header.readUInt16LE(34);
|
|
128
|
+
|
|
129
|
+
if (sampleRate === 0 || channels === 0 || bitsPerSample === 0) return null;
|
|
130
|
+
|
|
131
|
+
// Data chunk size is at offset 40 in standard WAV
|
|
132
|
+
const dataSize = header.readUInt32LE(40);
|
|
133
|
+
const bytesPerSecond = sampleRate * channels * (bitsPerSample / 8);
|
|
134
|
+
|
|
135
|
+
if (bytesPerSecond === 0) return null;
|
|
136
|
+
return Math.round((dataSize / bytesPerSecond) * 10) / 10;
|
|
137
|
+
} catch {
|
|
138
|
+
return null;
|
|
139
|
+
} finally {
|
|
140
|
+
if (fh) await fh.close();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function getFFprobeDuration(absPath) {
|
|
145
|
+
return new Promise((res) => {
|
|
146
|
+
execFile(
|
|
147
|
+
"ffprobe",
|
|
148
|
+
["-v", "quiet", "-show_entries", "format=duration", "-of", "csv=p=0", absPath],
|
|
149
|
+
{ windowsHide: true, timeout: 5000 },
|
|
150
|
+
(err, stdout) => {
|
|
151
|
+
if (err) return res(null);
|
|
152
|
+
const val = parseFloat(stdout.trim());
|
|
153
|
+
if (isNaN(val)) return res(null);
|
|
154
|
+
res(Math.round(val * 10) / 10);
|
|
155
|
+
}
|
|
156
|
+
);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Play a sound file. Returns a promise that resolves when playback starts
|
|
162
|
+
* (not when it finishes — we don't want to block).
|
|
163
|
+
*/
|
|
164
|
+
export function playSound(filePath) {
|
|
165
|
+
const absPath = resolve(filePath);
|
|
166
|
+
const strategy = getPlaybackCommand(absPath);
|
|
167
|
+
|
|
168
|
+
return new Promise((resolvePromise) => {
|
|
169
|
+
if (strategy.type === "exec") {
|
|
170
|
+
const child = spawn(strategy.cmd, strategy.args, {
|
|
171
|
+
stdio: "ignore",
|
|
172
|
+
detached: true,
|
|
173
|
+
windowsHide: true,
|
|
174
|
+
});
|
|
175
|
+
child.unref();
|
|
176
|
+
resolvePromise();
|
|
177
|
+
child.on("error", () => {
|
|
178
|
+
if (strategy.fallback === "powershell") {
|
|
179
|
+
const ps = spawn("powershell.exe", ["-NoProfile", "-Command", buildPsCommand(absPath)], {
|
|
180
|
+
stdio: "ignore", detached: true, windowsHide: true,
|
|
181
|
+
});
|
|
182
|
+
ps.unref();
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
} else if (strategy.type === "powershell") {
|
|
186
|
+
const child = spawn("powershell.exe", ["-NoProfile", "-Command", buildPsCommand(absPath)], {
|
|
187
|
+
stdio: "ignore", detached: true, windowsHide: true,
|
|
188
|
+
});
|
|
189
|
+
child.unref();
|
|
190
|
+
resolvePromise();
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Play a sound and wait for it to finish (for preview mode).
|
|
197
|
+
* Returns { promise, cancel } — call cancel() to stop playback immediately.
|
|
198
|
+
* Playback is clamped to MAX_PLAY_SECONDS.
|
|
199
|
+
*/
|
|
200
|
+
export function playSoundWithCancel(filePath) {
|
|
201
|
+
const absPath = resolve(filePath);
|
|
202
|
+
const strategy = getPlaybackCommand(absPath, { withFade: true });
|
|
203
|
+
let childProcess = null;
|
|
204
|
+
let timer = null;
|
|
205
|
+
let cancelled = false;
|
|
206
|
+
|
|
207
|
+
function killChild() {
|
|
208
|
+
if (childProcess && !childProcess.killed) {
|
|
209
|
+
try {
|
|
210
|
+
// On Windows, spawned processes need taskkill for the process tree
|
|
211
|
+
if (platform() === "win32") {
|
|
212
|
+
spawn("taskkill", ["/pid", String(childProcess.pid), "/f", "/t"], {
|
|
213
|
+
stdio: "ignore", windowsHide: true,
|
|
214
|
+
});
|
|
215
|
+
} else {
|
|
216
|
+
childProcess.kill("SIGTERM");
|
|
217
|
+
}
|
|
218
|
+
} catch { /* ignore */ }
|
|
219
|
+
}
|
|
220
|
+
if (timer) clearTimeout(timer);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const cancel = () => {
|
|
224
|
+
cancelled = true;
|
|
225
|
+
killChild();
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
const promise = new Promise((resolvePromise, reject) => {
|
|
229
|
+
function onDone(err) {
|
|
230
|
+
if (timer) clearTimeout(timer);
|
|
231
|
+
if (cancelled) return resolvePromise(); // cancelled — resolve, don't reject
|
|
232
|
+
if (err) reject(err);
|
|
233
|
+
else resolvePromise();
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function startExec(cmd, args) {
|
|
237
|
+
childProcess = execFile(cmd, args, { windowsHide: true, timeout: (MAX_PLAY_SECONDS + 2) * 1000 }, (err) => {
|
|
238
|
+
if (err && strategy.fallback && !cancelled) {
|
|
239
|
+
if (strategy.fallback === "powershell") {
|
|
240
|
+
childProcess = execFile(
|
|
241
|
+
"powershell.exe",
|
|
242
|
+
["-NoProfile", "-Command", buildPsCommand(absPath, MAX_PLAY_SECONDS)],
|
|
243
|
+
{ windowsHide: true, timeout: (MAX_PLAY_SECONDS + 2) * 1000 },
|
|
244
|
+
(psErr) => onDone(psErr)
|
|
245
|
+
);
|
|
246
|
+
} else if (strategy.fallback === "afplay") {
|
|
247
|
+
// macOS: ffplay not available, fall back to afplay (no fade)
|
|
248
|
+
childProcess = execFile("afplay", [absPath], { timeout: (MAX_PLAY_SECONDS + 2) * 1000 }, (afErr) => onDone(afErr));
|
|
249
|
+
}
|
|
250
|
+
} else {
|
|
251
|
+
onDone(err);
|
|
252
|
+
}
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
// Set a hard timeout to kill after MAX_PLAY_SECONDS
|
|
256
|
+
timer = setTimeout(() => {
|
|
257
|
+
killChild();
|
|
258
|
+
resolvePromise();
|
|
259
|
+
}, MAX_PLAY_SECONDS * 1000);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if (strategy.type === "exec") {
|
|
263
|
+
startExec(strategy.cmd, strategy.args);
|
|
264
|
+
} else if (strategy.type === "powershell") {
|
|
265
|
+
childProcess = execFile(
|
|
266
|
+
"powershell.exe",
|
|
267
|
+
["-NoProfile", "-Command", buildPsCommand(absPath, MAX_PLAY_SECONDS)],
|
|
268
|
+
{ windowsHide: true, timeout: (MAX_PLAY_SECONDS + 2) * 1000 },
|
|
269
|
+
(err) => onDone(err)
|
|
270
|
+
);
|
|
271
|
+
timer = setTimeout(() => {
|
|
272
|
+
killChild();
|
|
273
|
+
resolvePromise();
|
|
274
|
+
}, MAX_PLAY_SECONDS * 1000);
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
return { promise, cancel };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Play a sound and wait for it to finish (legacy — no cancel support).
|
|
283
|
+
*/
|
|
284
|
+
export function playSoundSync(filePath) {
|
|
285
|
+
return playSoundWithCancel(filePath).promise;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Process a sound file with ffmpeg: strip leading silence, clamp to MAX_PLAY_SECONDS,
|
|
290
|
+
* and fade out over the last FADE_SECONDS. Returns the path to the processed WAV file.
|
|
291
|
+
* If ffmpeg is not available or the file is already short enough, returns the original path.
|
|
292
|
+
*/
|
|
293
|
+
export async function processSound(filePath) {
|
|
294
|
+
const absPath = resolve(filePath);
|
|
295
|
+
|
|
296
|
+
// First check duration — skip processing if already short
|
|
297
|
+
const duration = await getWavDuration(absPath);
|
|
298
|
+
if (duration != null && duration <= MAX_PLAY_SECONDS) {
|
|
299
|
+
return absPath; // Already short enough, no processing needed
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// Build a deterministic output path based on input file hash
|
|
303
|
+
const hash = createHash("md5").update(absPath).digest("hex").slice(0, 12);
|
|
304
|
+
const outDir = join(tmpdir(), "klonk-processed");
|
|
305
|
+
const outName = `${basename(absPath, extname(absPath))}_${hash}.wav`;
|
|
306
|
+
const outPath = join(outDir, outName);
|
|
307
|
+
|
|
308
|
+
// Check if already processed
|
|
309
|
+
try {
|
|
310
|
+
await stat(outPath);
|
|
311
|
+
return outPath; // Already exists
|
|
312
|
+
} catch { /* needs processing */ }
|
|
313
|
+
|
|
314
|
+
await mkdir(outDir, { recursive: true });
|
|
315
|
+
|
|
316
|
+
// Build ffmpeg filter chain: silence strip → fade out → clamp duration
|
|
317
|
+
const fadeStart = MAX_PLAY_SECONDS - FADE_SECONDS;
|
|
318
|
+
const filters = [
|
|
319
|
+
"silenceremove=start_periods=1:start_silence=0.1:start_threshold=-50dB",
|
|
320
|
+
`afade=t=out:st=${fadeStart}:d=${FADE_SECONDS}`,
|
|
321
|
+
].join(",");
|
|
322
|
+
|
|
323
|
+
return new Promise((res) => {
|
|
324
|
+
execFile(
|
|
325
|
+
"ffmpeg",
|
|
326
|
+
[
|
|
327
|
+
"-y", "-i", absPath,
|
|
328
|
+
"-af", filters,
|
|
329
|
+
"-t", String(MAX_PLAY_SECONDS),
|
|
330
|
+
"-ar", "44100", "-ac", "2",
|
|
331
|
+
outPath,
|
|
332
|
+
],
|
|
333
|
+
{ windowsHide: true, timeout: 30000 },
|
|
334
|
+
(err) => {
|
|
335
|
+
if (err) {
|
|
336
|
+
// ffmpeg not available or failed — return original
|
|
337
|
+
res(absPath);
|
|
338
|
+
} else {
|
|
339
|
+
res(outPath);
|
|
340
|
+
}
|
|
341
|
+
},
|
|
342
|
+
);
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Generate the shell command string for use in Claude Code hooks.
|
|
348
|
+
*/
|
|
349
|
+
export function getHookPlayCommand(soundFilePath) {
|
|
350
|
+
const normalized = soundFilePath.replace(/\\/g, "/");
|
|
351
|
+
const ext = extname(normalized).toLowerCase();
|
|
352
|
+
const needsFfplay = !MEDIA_PLAYER_FORMATS.has(ext);
|
|
353
|
+
|
|
354
|
+
if (needsFfplay) {
|
|
355
|
+
return `if command -v ffplay &>/dev/null; then ffplay -nodisp -autoexit -loglevel quiet "${normalized}" & elif [[ "$OSTYPE" == "darwin"* ]]; then afplay "${normalized}" & elif [[ "$OSTYPE" == "msys"* ]] || [[ "$OSTYPE" == "cygwin"* ]]; then powershell.exe -NoProfile -Command "Add-Type -AssemblyName PresentationCore; \\$p = New-Object System.Windows.Media.MediaPlayer; \\$p.Open([System.Uri]::new('$(cygpath -w "${normalized}")')); Start-Sleep -Milliseconds 200; \\$p.Play(); Start-Sleep -Seconds 2" & else aplay "${normalized}" & fi`;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
return `if [[ "$OSTYPE" == "darwin"* ]]; then afplay "${normalized}" & elif [[ "$OSTYPE" == "msys"* ]] || [[ "$OSTYPE" == "cygwin"* ]]; then powershell.exe -NoProfile -Command "Add-Type -AssemblyName PresentationCore; \\$p = New-Object System.Windows.Media.MediaPlayer; \\$p.Open([System.Uri]::new('$(cygpath -w "${normalized}")')); Start-Sleep -Milliseconds 200; \\$p.Play(); Start-Sleep -Seconds 2" & else aplay "${normalized}" & fi`;
|
|
359
|
+
}
|