@clipy/cli 0.18.0 → 0.19.0

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.
Files changed (56) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +210 -9
  3. package/dist/context/importCmd.js +1 -1
  4. package/dist/context/ytdlp.js +1 -1
  5. package/dist/context-core/arec.js +1 -1
  6. package/dist/index.js +1042 -88
  7. package/dist/local/arec.js +186 -0
  8. package/dist/local/commands.js +1103 -0
  9. package/dist/local/deps.js +42 -0
  10. package/dist/local/media.js +154 -0
  11. package/dist/local/pipeline.js +530 -0
  12. package/dist/local/ports.js +1 -0
  13. package/dist/local/speechEngine.js +260 -0
  14. package/dist/local/transcriptFile.js +54 -0
  15. package/dist/local/vendor/capture/capture.js +442 -0
  16. package/dist/local/vendor/capture/check.js +103 -0
  17. package/dist/local/vendor/capture/children.js +69 -0
  18. package/dist/local/vendor/capture/ffmpegArgs.js +108 -0
  19. package/dist/local/vendor/capture/index.js +36 -0
  20. package/dist/local/vendor/capture/proc.js +71 -0
  21. package/dist/local/vendor/capture/scripts.js +107 -0
  22. package/dist/local/vendor/capture/sidecar.js +199 -0
  23. package/dist/local/vendor/capture/sources.js +272 -0
  24. package/dist/local/vendor/capture/types.js +1 -0
  25. package/dist/local/vendor/capture/virtualDisplay.js +170 -0
  26. package/dist/local/vendor/capture/xauth.js +68 -0
  27. package/dist/local/vendor/config/errors.js +12 -0
  28. package/dist/local/vendor/config/index.js +241 -0
  29. package/dist/local/vendor/config/paths.js +37 -0
  30. package/dist/local/vendor/config/presets.js +61 -0
  31. package/dist/local/vendor/config/schema.js +66 -0
  32. package/dist/local/vendor/moments/generated/drawStrokes.js +127 -0
  33. package/dist/local/vendor/moments/generated/keyMomentsCursorContext.js +568 -0
  34. package/dist/local/vendor/moments/generated/keyMomentsFusion.js +406 -0
  35. package/dist/local/vendor/moments/generated/localMomentPlan.js +178 -0
  36. package/dist/local/vendor/moments/generated/types.js +1 -0
  37. package/dist/local/vendor/moments/index.js +147 -0
  38. package/dist/local/vendor/moments/llm.js +158 -0
  39. package/dist/local/vendor/transcribe/audio.js +251 -0
  40. package/dist/local/vendor/transcribe/chunking.js +250 -0
  41. package/dist/local/vendor/transcribe/index.js +89 -0
  42. package/dist/local/vendor/transcribe/local.js +221 -0
  43. package/dist/local/vendor/transcribe/localWorker.js +79 -0
  44. package/dist/local/vendor/transcribe/models.js +369 -0
  45. package/dist/local/vendor/transcribe/providers/assemblyai.js +61 -0
  46. package/dist/local/vendor/transcribe/providers/common.js +105 -0
  47. package/dist/local/vendor/transcribe/providers/deepgram.js +59 -0
  48. package/dist/local/vendor/transcribe/providers/elevenlabs.js +43 -0
  49. package/dist/local/vendor/transcribe/providers/gemini.js +102 -0
  50. package/dist/local/vendor/transcribe/providers/http.js +214 -0
  51. package/dist/local/vendor/transcribe/providers/openai.js +48 -0
  52. package/dist/local/vendor/transcribe/tar.js +53 -0
  53. package/dist/local/vendor/transcribe/types.js +1 -0
  54. package/dist/macBridge.js +78 -9
  55. package/dist/skill.js +46 -1
  56. package/package.json +19 -9
@@ -0,0 +1,147 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/moments/src/index.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * @clipy/moments: picks the moments of a screen recording worth a screenshot.
5
+ *
6
+ * The same detectors and planner Clipy's hosted service runs, packaged to run
7
+ * on the user's machine:
8
+ * - Rules (always, offline): hold-to-highlight flares, pen drawings, click
9
+ * clusters and pointer rests from the interaction sidecar.
10
+ * - Spoken cues (optional): a model reads the transcript for "this button",
11
+ * "it breaks here" and similar, using the provider the user configured.
12
+ */
13
+ import { runWithModelProvider } from "./llm.js";
14
+ import { describePlannerError, localMomentInput, planLocalMoments, } from "./generated/localMomentPlan.js";
15
+ export { DEFAULT_OPENROUTER_MODEL, PROVIDER_BASE_URLS, LLMError, MODEL_ERROR, } from "./llm.js";
16
+ export { localMomentInput, describePlannerError, isTransientPlannerError, } from "./generated/localMomentPlan.js";
17
+ /** The planner's limit on interaction events. */
18
+ export const MAX_PLANNER_INTERACTIONS = 8000;
19
+ /** Button, key and annotation edges: the evidence every gesture rule reads. */
20
+ const EDGE_KINDS = new Set(["down", "up", "key_down", "key_up", "annotation"]);
21
+ function evenly(indices, budget) {
22
+ if (budget <= 0)
23
+ return [];
24
+ if (indices.length <= budget)
25
+ return indices;
26
+ const out = [];
27
+ for (let k = 0; k < budget; k++)
28
+ out.push(indices[Math.floor((k * indices.length) / budget)]);
29
+ return out;
30
+ }
31
+ /** macOS Control key codes, the hold-to-highlight key (the local planner reads Mac key codes). */
32
+ const CONTROL_KEYCODES = new Set([59, 62]);
33
+ /** macOS modifier key codes: pressing one during a Control hold does not make it a chord. */
34
+ const isModifierKeycode = (code) => code >= 54 && code <= 63;
35
+ /**
36
+ * Button, key and annotation events thinned to `budget` without changing
37
+ * what the gesture rules see: every Control and annotation event, and every
38
+ * non-modifier key press during a Control hold (it makes a chord), are kept;
39
+ * other key presses and clicks are dropped only as whole down/up pairs.
40
+ */
41
+ function thinEdges(events, edges, budget) {
42
+ if (edges.length <= budget)
43
+ return edges;
44
+ const at = (i) => events[i];
45
+ const time = (i) => (typeof at(i).time_ms === "number" ? at(i).time_ms : 0);
46
+ const ordered = [...edges].sort((a, b) => time(a) - time(b) || a - b);
47
+ const kept = [];
48
+ const units = [];
49
+ const openKeys = new Map();
50
+ const openButtons = new Map();
51
+ let held = 0;
52
+ for (const i of ordered) {
53
+ const e = at(i);
54
+ const code = e.key_code;
55
+ if (e.kind === "annotation") {
56
+ kept.push(i);
57
+ }
58
+ else if ((e.kind === "key_down" || e.kind === "key_up") && typeof code === "number" && CONTROL_KEYCODES.has(code)) {
59
+ kept.push(i);
60
+ held = e.kind === "key_down" ? held + 1 : 0;
61
+ }
62
+ else if (e.kind === "key_down" && held > 0 && typeof code === "number" && !isModifierKeycode(code)) {
63
+ kept.push(i);
64
+ }
65
+ else if (e.kind === "key_down" || e.kind === "down") {
66
+ const open = e.kind === "key_down" ? openKeys : openButtons;
67
+ const id = e.kind === "key_down" ? code : e.button;
68
+ const unit = [i];
69
+ units.push(unit);
70
+ if (!open.has(id))
71
+ open.set(id, []);
72
+ open.get(id).push(units.length - 1);
73
+ }
74
+ else {
75
+ const open = e.kind === "key_up" ? openKeys : openButtons;
76
+ const id = e.kind === "key_up" ? code : e.button;
77
+ const pending = open.get(id);
78
+ const unitIndex = pending?.shift();
79
+ if (unitIndex !== undefined)
80
+ units[unitIndex].push(i);
81
+ else
82
+ units.push([i]);
83
+ }
84
+ }
85
+ if (kept.length >= budget)
86
+ return evenly(kept, budget);
87
+ const room = budget - kept.length;
88
+ const size = (list) => list.reduce((n, u) => n + u.length, 0);
89
+ let count = Math.min(units.length, room);
90
+ let chosen = evenly(units.map((_u, k) => k), count).map((k) => units[k]);
91
+ while (size(chosen) > room && count > 0) {
92
+ count = Math.max(0, count - Math.ceil((size(chosen) - room) / 2));
93
+ chosen = evenly(units.map((_u, k) => k), count).map((k) => units[k]);
94
+ }
95
+ return [...kept, ...chosen.flat()];
96
+ }
97
+ /**
98
+ * Interactions thinned to `limit`, in their original order: button, key and
99
+ * annotation events first (thinned only when they alone pass the limit, see
100
+ * thinEdges), then scrolls, and pointer moves are thinned evenly into what is
101
+ * left. Within the limit the array comes back unchanged. (A 20 Hz pointer
102
+ * track passes 8000 events in under seven minutes.)
103
+ */
104
+ export function boundInteractions(events, limit = MAX_PLANNER_INTERACTIONS) {
105
+ if (events.length <= limit)
106
+ return events;
107
+ const kindOf = (e) => (e && typeof e === "object" ? e.kind : undefined);
108
+ const edges = [];
109
+ const scrolls = [];
110
+ const rest = [];
111
+ events.forEach((e, i) => {
112
+ const kind = kindOf(e);
113
+ if (typeof kind === "string" && EDGE_KINDS.has(kind))
114
+ edges.push(i);
115
+ else if (kind === "scroll")
116
+ scrolls.push(i);
117
+ else
118
+ rest.push(i);
119
+ });
120
+ const keptEdges = thinEdges(events, edges, limit);
121
+ const keptScrolls = evenly(scrolls, limit - keptEdges.length);
122
+ const keptRest = evenly(rest, limit - keptEdges.length - keptScrolls.length);
123
+ const keep = new Set([...keptEdges, ...keptScrolls, ...keptRest]);
124
+ return events.filter((_e, i) => keep.has(i));
125
+ }
126
+ export async function planMoments(input, options = {}) {
127
+ const raw = input;
128
+ const bounded = Array.isArray(raw.interactions) && raw.interactions.length > MAX_PLANNER_INTERACTIONS
129
+ ? { ...input, interactions: boundInteractions(input.interactions) }
130
+ : input;
131
+ const parsed = localMomentInput.parse(bounded);
132
+ const provider = options.provider ?? null;
133
+ const signal = options.signal ?? new AbortController().signal;
134
+ try {
135
+ // Scoped to this call, so concurrent calls with different providers are safe.
136
+ const { result: plan, modelAnswers } = await runWithModelProvider(provider, () => planLocalMoments(parsed, signal));
137
+ // "rules+model" only when a model's answer went into the plan: with an
138
+ // empty transcript the model is never asked, whatever is configured.
139
+ return { plan, planner: modelAnswers > 0 ? "rules+model" : "rules" };
140
+ }
141
+ catch (error) {
142
+ if (!provider || options.onModelFailure !== "rules" || signal.aborted)
143
+ throw error;
144
+ const { result: plan } = await runWithModelProvider(null, () => planLocalMoments(parsed, signal));
145
+ return { plan, planner: "rules", modelFallback: String(describePlannerError(error).kind ?? "error") };
146
+ }
147
+ }
@@ -0,0 +1,158 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/moments/src/llm.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * The model client the generated planner calls (`chatJSON`, `LLMError`), in
5
+ * place of Clipy's server-side OpenRouter client. It talks to any
6
+ * OpenAI-compatible chat completions endpoint: OpenRouter (default), OpenAI,
7
+ * Google Gemini's OpenAI endpoint, Groq, Ollama, LM Studio, or a custom URL.
8
+ *
9
+ * With no provider configured the planner runs on rules only: `chatJSON`
10
+ * answers "no spoken moments", so gestures, clicks and pointer rests are still
11
+ * found and nothing leaves the machine.
12
+ *
13
+ * The provider is scoped to one `planMoments` call through AsyncLocalStorage,
14
+ * not held in module state, so concurrent calls with different providers (or
15
+ * one with a provider and one without) never see each other's settings. The
16
+ * generated planner calls `chatJSON` without a provider argument; this is how
17
+ * `chatJSON` finds the provider of the call it belongs to.
18
+ */
19
+ import { AsyncLocalStorage } from "node:async_hooks";
20
+ /** Ready-made base URLs for the providers the CLI and app offer. */
21
+ export const PROVIDER_BASE_URLS = {
22
+ openrouter: "https://openrouter.ai/api/v1",
23
+ openai: "https://api.openai.com/v1",
24
+ gemini: "https://generativelanguage.googleapis.com/v1beta/openai",
25
+ groq: "https://api.groq.com/openai/v1",
26
+ ollama: "http://127.0.0.1:11434/v1",
27
+ lmstudio: "http://127.0.0.1:1234/v1",
28
+ };
29
+ /** Same model the hosted endpoint uses, so results match when the key is OpenRouter. */
30
+ export const DEFAULT_OPENROUTER_MODEL = "google/gemini-3.1-flash-lite";
31
+ const providerScope = new AsyncLocalStorage();
32
+ /**
33
+ * Run `fn` with `provider` as the model provider for every `chatJSON` call it
34
+ * makes, including calls in promises and timers it starts. null means rules
35
+ * only. Outside such a scope there is no provider.
36
+ */
37
+ export async function withModelProvider(provider, fn) {
38
+ return (await runWithModelProvider(provider, fn)).result;
39
+ }
40
+ /**
41
+ * Like `withModelProvider`, and also says how many model answers the scope
42
+ * used, so a caller can tell "a model picked moments" apart from "a model was
43
+ * configured but never asked" (an empty transcript skips it).
44
+ */
45
+ export async function runWithModelProvider(provider, fn) {
46
+ const scope = { provider, answers: 0 };
47
+ const result = await providerScope.run(scope, fn);
48
+ return { result, modelAnswers: scope.answers };
49
+ }
50
+ /** The provider of the current `withModelProvider` scope, or null. */
51
+ export function currentModelProvider() {
52
+ return providerScope.getStore()?.provider ?? null;
53
+ }
54
+ export class LLMError extends Error {
55
+ transient;
56
+ upstreamStatus;
57
+ constructor(opts) {
58
+ super(opts.message);
59
+ this.name = "LLMError";
60
+ this.transient = opts.transient;
61
+ this.upstreamStatus = opts.upstreamStatus ?? null;
62
+ }
63
+ }
64
+ function stripCodeFence(text) {
65
+ const fenced = /^\s*```(?:json)?\s*([\s\S]*?)\s*```\s*$/i.exec(text);
66
+ return fenced ? fenced[1] : text;
67
+ }
68
+ export async function chatJSON(opts) {
69
+ const scope = providerScope.getStore();
70
+ const provider = scope?.provider ?? null;
71
+ if (!scope || !provider) {
72
+ // Rules only. The planner's schema accepts an empty list.
73
+ return { parsed: { moments: [] }, raw: { text: "" } };
74
+ }
75
+ const res = await fetch(`${provider.baseUrl.replace(/\/+$/, "")}/chat/completions`, {
76
+ method: "POST",
77
+ redirect: "error",
78
+ signal: opts.signal,
79
+ headers: {
80
+ "Content-Type": "application/json",
81
+ ...(provider.apiKey ? { Authorization: `Bearer ${provider.apiKey}` } : {}),
82
+ ...provider.headers,
83
+ },
84
+ body: JSON.stringify({
85
+ model: provider.model,
86
+ messages: opts.messages,
87
+ temperature: opts.temperature,
88
+ max_tokens: opts.maxTokens,
89
+ response_format: { type: "json_object" },
90
+ }),
91
+ });
92
+ if (!res.ok) {
93
+ // The body can echo the transcript, so it is not included in the message.
94
+ throw new LLMError({
95
+ message: `Model provider returned HTTP ${res.status}`,
96
+ transient: res.status === 408 || res.status === 429 || res.status >= 500,
97
+ upstreamStatus: res.status,
98
+ });
99
+ }
100
+ const raw = await readCapped(res, MAX_COMPLETION_BYTES);
101
+ let body;
102
+ try {
103
+ body = JSON.parse(raw);
104
+ }
105
+ catch {
106
+ body = null;
107
+ }
108
+ const text = body?.choices?.[0]?.message?.content;
109
+ if (!text) {
110
+ throw new LLMError({ message: MODEL_ERROR.noCompletion, transient: true, upstreamStatus: res.status });
111
+ }
112
+ let parsed;
113
+ try {
114
+ parsed = JSON.parse(stripCodeFence(text));
115
+ }
116
+ catch {
117
+ throw new LLMError({ message: MODEL_ERROR.unparseable, transient: true, upstreamStatus: res.status });
118
+ }
119
+ scope.answers += 1;
120
+ return { parsed, raw: { text } };
121
+ }
122
+ /** Largest chat completion read into memory; a moment list is a few KB. */
123
+ export const MAX_COMPLETION_BYTES = 2 * 1024 * 1024;
124
+ /**
125
+ * Error messages for a model answer that cannot be used. The generated
126
+ * planner's describePlannerError classifies errors by these prefixes, so keep
127
+ * them in step with the replacements in scripts/sync-from-monorepo.mjs.
128
+ */
129
+ export const MODEL_ERROR = {
130
+ noCompletion: "Model provider returned no completion",
131
+ unparseable: "Model provider JSON parse failed",
132
+ tooLarge: "Model provider answer was too large",
133
+ };
134
+ async function readCapped(res, maxBytes) {
135
+ const tooLarge = () => new LLMError({ message: MODEL_ERROR.tooLarge, transient: false, upstreamStatus: res.status });
136
+ const declared = Number(res.headers.get("content-length"));
137
+ if (Number.isFinite(declared) && declared > maxBytes) {
138
+ await res.body?.cancel().catch(() => undefined);
139
+ throw tooLarge();
140
+ }
141
+ if (!res.body)
142
+ return "";
143
+ const reader = res.body.getReader();
144
+ const chunks = [];
145
+ let total = 0;
146
+ for (;;) {
147
+ const { done, value } = await reader.read();
148
+ if (done)
149
+ break;
150
+ total += value.byteLength;
151
+ if (total > maxBytes) {
152
+ await reader.cancel().catch(() => undefined);
153
+ throw tooLarge();
154
+ }
155
+ chunks.push(value);
156
+ }
157
+ return Buffer.concat(chunks, total).toString("utf8");
158
+ }
@@ -0,0 +1,251 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/transcribe/src/audio.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ import { spawn } from "node:child_process";
4
+ import { open, stat } from "node:fs/promises";
5
+ import { resolve } from "node:path";
6
+ import { parseSilencedetectOutput } from "./chunking.js";
7
+ /** Every engine gets the same audio: 16 kHz, mono, 16-bit PCM WAV. */
8
+ export const SAMPLE_RATE = 16_000;
9
+ export const BYTES_PER_SECOND = SAMPLE_RATE * 2;
10
+ /** `CLIPY_FFMPEG` points at a specific ffmpeg; otherwise the one on PATH. */
11
+ export function ffmpegPath() {
12
+ return process.env.CLIPY_FFMPEG || "ffmpeg";
13
+ }
14
+ function abortError() {
15
+ const err = new Error("Transcription was cancelled");
16
+ err.name = "AbortError";
17
+ return err;
18
+ }
19
+ export function throwIfAborted(signal) {
20
+ if (signal?.aborted)
21
+ throw abortError();
22
+ }
23
+ /** Run ffmpeg, keeping only the tail of stderr. Rejects clearly when ffmpeg is missing. */
24
+ function runFfmpeg(args, signal, keepStderr = 64 * 1024) {
25
+ throwIfAborted(signal);
26
+ return new Promise((resolve, reject) => {
27
+ const proc = spawn(ffmpegPath(), args, { stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
28
+ let stderr = "";
29
+ let settled = false;
30
+ const onAbort = () => {
31
+ proc.kill("SIGKILL");
32
+ finish(() => reject(abortError()));
33
+ };
34
+ const finish = (fn) => {
35
+ if (settled)
36
+ return;
37
+ settled = true;
38
+ signal?.removeEventListener("abort", onAbort);
39
+ fn();
40
+ };
41
+ signal?.addEventListener("abort", onAbort, { once: true });
42
+ proc.stderr.setEncoding("utf8");
43
+ proc.stderr.on("data", (d) => {
44
+ stderr += d;
45
+ if (stderr.length > keepStderr * 2)
46
+ stderr = stderr.slice(-keepStderr);
47
+ });
48
+ proc.on("error", (err) => {
49
+ finish(() => reject(err.code === "ENOENT"
50
+ ? new Error("ffmpeg was not found. Install ffmpeg (https://ffmpeg.org/download.html) " +
51
+ "and make sure it is on your PATH, or set CLIPY_FFMPEG to its full path.")
52
+ : new Error(`ffmpeg could not start: ${err.code ?? err.message}`)));
53
+ });
54
+ proc.on("close", (code) => finish(() => resolve({ code, stderr })));
55
+ });
56
+ }
57
+ /**
58
+ * A local file as an ffmpeg input. Without the `file:` prefix a name such as
59
+ * `take2:final.mp4` is read as protocol `take2`.
60
+ */
61
+ export function ffmpegInput(path) {
62
+ return `file:${resolve(path)}`;
63
+ }
64
+ /** The input has no audio stream, so there is nothing to transcribe. */
65
+ export class NoAudioTrackError extends Error {
66
+ constructor(inputPath) {
67
+ super(`${inputPath} has no audio track to transcribe`);
68
+ this.name = "NoAudioTrackError";
69
+ }
70
+ }
71
+ const DURATION_RE = /Duration:\s*(\d+):(\d{2}):(\d{2}(?:\.\d+)?)/;
72
+ /**
73
+ * How long a media file is and whether it has audio, from ffmpeg's header
74
+ * dump (the same ffmpeg as everything else here, so no ffprobe is needed).
75
+ * A fragmented file with no header duration is decoded to its last
76
+ * timestamp. `durationSec` is null when neither works.
77
+ */
78
+ export async function probeMedia(inputPath, signal) {
79
+ const header = await runFfmpeg(["-hide_banner", "-nostdin", "-i", ffmpegInput(inputPath)], signal, 64 * 1024);
80
+ const hasAudio = /Stream #\d+:\d+[^\n]*: Audio:/.test(header.stderr);
81
+ const m = DURATION_RE.exec(header.stderr);
82
+ if (m)
83
+ return { durationSec: Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]), hasAudio };
84
+ if (/No such file|Invalid data found|Permission denied|Error opening input/i.test(header.stderr)) {
85
+ throw new Error(`ffmpeg could not read ${inputPath}`);
86
+ }
87
+ const decode = await runFfmpeg(["-hide_banner", "-nostdin", "-nostats", "-progress", "pipe:2", "-i", ffmpegInput(inputPath), "-map", "0", "-c", "copy", "-f", "null", "-"], signal, 16 * 1024);
88
+ const times = [...decode.stderr.matchAll(/out_time_us=(\d+)/g)];
89
+ return { durationSec: times.length > 0 ? Number(times[times.length - 1][1]) / 1e6 : null, hasAudio };
90
+ }
91
+ /** ffmpeg: any video/audio file -> 16 kHz mono 16-bit WAV. Throws a clear error if ffmpeg is missing. */
92
+ export async function extractAudio(inputPath, outWavPath, signal) {
93
+ const { code, stderr } = await runFfmpeg([
94
+ "-hide_banner",
95
+ "-nostdin",
96
+ "-y",
97
+ "-i",
98
+ ffmpegInput(inputPath),
99
+ "-vn",
100
+ "-map_metadata",
101
+ "-1",
102
+ "-ac",
103
+ "1",
104
+ "-ar",
105
+ String(SAMPLE_RATE),
106
+ "-c:a",
107
+ "pcm_s16le",
108
+ "-f",
109
+ "wav",
110
+ `file:${resolve(outWavPath)}`,
111
+ ], signal, 4 * 1024);
112
+ if (code !== 0) {
113
+ if (/does not contain any stream|Output file #0 does not contain|matches no streams/i.test(stderr))
114
+ throw new NoAudioTrackError(inputPath);
115
+ throw new Error(`ffmpeg could not read the audio in ${inputPath} (exit ${code})`);
116
+ }
117
+ }
118
+ /** Read a PCM WAV header (RIFF chunks, so extra LIST chunks are skipped). */
119
+ export async function readWavInfo(path) {
120
+ const size = (await stat(path)).size;
121
+ const fh = await open(path, "r");
122
+ try {
123
+ const head = Buffer.alloc(Math.min(size, 64 * 1024));
124
+ await fh.read(head, 0, head.length, 0);
125
+ if (head.toString("ascii", 0, 4) !== "RIFF" || head.toString("ascii", 8, 12) !== "WAVE") {
126
+ throw new Error(`${path} is not a WAV file`);
127
+ }
128
+ let pos = 12;
129
+ let fmt = null;
130
+ while (pos + 8 <= head.length) {
131
+ const id = head.toString("ascii", pos, pos + 4);
132
+ const len = head.readUInt32LE(pos + 4);
133
+ const body = pos + 8;
134
+ if (id === "fmt ") {
135
+ fmt = {
136
+ channels: head.readUInt16LE(body + 2),
137
+ sampleRate: head.readUInt32LE(body + 4),
138
+ bits: head.readUInt16LE(body + 14),
139
+ };
140
+ }
141
+ else if (id === "data") {
142
+ if (!fmt)
143
+ break;
144
+ // A streamed WAV can carry a placeholder length; trust the file size.
145
+ const dataBytes = Math.min(len, size - body);
146
+ const bytesPerSec = fmt.sampleRate * fmt.channels * (fmt.bits / 8);
147
+ return {
148
+ sampleRate: fmt.sampleRate,
149
+ channels: fmt.channels,
150
+ bitsPerSample: fmt.bits,
151
+ dataOffset: body,
152
+ dataBytes,
153
+ durationSec: dataBytes / bytesPerSec,
154
+ };
155
+ }
156
+ pos = body + len + (len % 2);
157
+ }
158
+ throw new Error(`${path} has no PCM data chunk`);
159
+ }
160
+ finally {
161
+ await fh.close();
162
+ }
163
+ }
164
+ /** A complete 16 kHz mono WAV file holding the given PCM bytes. */
165
+ export function wavFromPcm(pcm, sampleRate = SAMPLE_RATE) {
166
+ const header = Buffer.alloc(44);
167
+ header.write("RIFF", 0, "ascii");
168
+ header.writeUInt32LE(36 + pcm.length, 4);
169
+ header.write("WAVE", 8, "ascii");
170
+ header.write("fmt ", 12, "ascii");
171
+ header.writeUInt32LE(16, 16);
172
+ header.writeUInt16LE(1, 20); // PCM
173
+ header.writeUInt16LE(1, 22); // mono
174
+ header.writeUInt32LE(sampleRate, 24);
175
+ header.writeUInt32LE(sampleRate * 2, 28);
176
+ header.writeUInt16LE(2, 32);
177
+ header.writeUInt16LE(16, 34);
178
+ header.write("data", 36, "ascii");
179
+ header.writeUInt32LE(pcm.length, 40);
180
+ return Buffer.concat([header, pcm]);
181
+ }
182
+ /** Cut [startSec, startSec + durSec) out of a 16-bit mono WAV as its own WAV file in memory. */
183
+ export async function readWavSlice(path, info, startSec, durSec) {
184
+ const frame = info.channels * (info.bitsPerSample / 8);
185
+ const startByte = Math.min(info.dataBytes, Math.max(0, Math.round(startSec * info.sampleRate)) * frame);
186
+ const endByte = Math.min(info.dataBytes, Math.round((startSec + durSec) * info.sampleRate) * frame);
187
+ const len = Math.max(0, endByte - startByte);
188
+ const pcm = Buffer.alloc(len);
189
+ const fh = await open(path, "r");
190
+ try {
191
+ await fh.read(pcm, 0, len, info.dataOffset + startByte);
192
+ }
193
+ finally {
194
+ await fh.close();
195
+ }
196
+ return wavFromPcm(pcm, info.sampleRate);
197
+ }
198
+ /** ffmpeg silencedetect over the WAV. Best effort: any failure means "no silences found". */
199
+ export async function detectSilences(wavPath, signal, totalSec, noiseDb = -30, minSilenceSec = 0.4) {
200
+ try {
201
+ const { code, stderr } = await runFfmpeg(["-hide_banner", "-nostats", "-nostdin", "-i", ffmpegInput(wavPath), "-af", `silencedetect=noise=${noiseDb}dB:d=${minSilenceSec}`, "-f", "null", "-"], signal, 16 * 1024 * 1024);
202
+ if (code !== 0)
203
+ return [];
204
+ return parseSilencedetectOutput(stderr, totalSec);
205
+ }
206
+ catch (err) {
207
+ if (err.name === "AbortError")
208
+ throw err;
209
+ return [];
210
+ }
211
+ }
212
+ /** Mean volume of the WAV in dBFS (ffmpeg volumedetect), or null when it cannot be measured. */
213
+ export async function measureMeanVolume(wavPath, signal) {
214
+ try {
215
+ const { code, stderr } = await runFfmpeg(["-hide_banner", "-nostats", "-nostdin", "-i", ffmpegInput(wavPath), "-af", "volumedetect", "-f", "null", "-"], signal, 64 * 1024);
216
+ if (code !== 0)
217
+ return null;
218
+ const m = /mean_volume:\s*(-?[0-9.]+|-inf) dB/.exec(stderr);
219
+ if (!m || m[1] === "-inf")
220
+ return null;
221
+ const db = Number(m[1]);
222
+ return Number.isFinite(db) ? db : null;
223
+ }
224
+ catch (err) {
225
+ if (err.name === "AbortError")
226
+ throw err;
227
+ return null;
228
+ }
229
+ }
230
+ /** A recording whose mean volume is under this is quiet: its silence thresholds follow it down. */
231
+ export const QUIET_MEAN_DB = -35;
232
+ /**
233
+ * Silence thresholds for one recording, from its mean volume.
234
+ *
235
+ * - `quiet`: the mean is under QUIET_MEAN_DB. Normal speech (a mic take
236
+ * averages about -25 dB) is not quiet.
237
+ * - `splitDb` finds the pauses to cut long audio at, and decides that a
238
+ * piece holds nothing worth sending to an engine that invents words in
239
+ * silence. -30 dB, or for a quiet recording 12 dB under its mean, so speech
240
+ * peaking around -31 dBFS is not one long "silence".
241
+ * - `skipDb` decides that a piece holds no speech at all. Skipping loses
242
+ * words when it is wrong, so it is far stricter: at most -50 dB and 30 dB
243
+ * under the mean.
244
+ */
245
+ export function silenceThresholds(meanDb) {
246
+ if (meanDb === null || !Number.isFinite(meanDb))
247
+ return { splitDb: -30, skipDb: -50, quiet: false };
248
+ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
249
+ const quiet = meanDb < QUIET_MEAN_DB;
250
+ return { splitDb: quiet ? clamp(meanDb - 12, -70, -30) : -30, skipDb: clamp(meanDb - 30, -80, -50), quiet };
251
+ }