@mthines/reaper-mcp 0.71.0-beta.83.2 → 0.71.0-beta.85.1

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/main.js CHANGED
@@ -4201,71 +4201,6 @@ function ensureSnapshotActions(kb) {
4201
4201
  const body = kb === "" || kb.endsWith("\n") ? kb : kb + eol;
4202
4202
  return { kb: body + lines.join(eol) + eol, added };
4203
4203
  }
4204
- var AUTOSTART_MARKER = "reaper-mcp: start the bridge with REAPER";
4205
- var AUTOSTART_BEGIN = `-- ${AUTOSTART_MARKER} (begin)`;
4206
- var AUTOSTART_END = `-- ${AUTOSTART_MARKER} (end)`;
4207
- var AUTOSTART_BLOCK = [
4208
- AUTOSTART_BEGIN,
4209
- "-- Written by `reaper-mcp setup`. Turn it off in the bridge window: Settings \u2192 Start with REAPER.",
4210
- "do",
4211
- ' local bridge = reaper.GetResourcePath() .. "/Scripts/mcp_bridge.lua"',
4212
- ' if reaper.GetExtState("MCPBridge", "cfg_autostart") ~= "0" and reaper.file_exists(bridge) then',
4213
- " local id = reaper.AddRemoveReaScript(true, 0, bridge, true)",
4214
- " if id and id > 0 then reaper.Main_OnCommand(id, 0) end",
4215
- " end",
4216
- "end",
4217
- AUTOSTART_END
4218
- ];
4219
- function ensureBridgeAutostart(startup) {
4220
- const eol = startup.includes("\r\n") ? "\r\n" : "\n";
4221
- const block = AUTOSTART_BLOCK.join(eol);
4222
- const lines = startup.split(/\r?\n/);
4223
- const begin = lines.indexOf(AUTOSTART_BEGIN);
4224
- const end = begin === -1 ? -1 : lines.indexOf(AUTOSTART_END, begin);
4225
- let text7;
4226
- if (begin !== -1 && end !== -1) {
4227
- text7 = [...lines.slice(0, begin), ...AUTOSTART_BLOCK, ...lines.slice(end + 1)].join(eol);
4228
- } else if (startup.trim() === "") {
4229
- text7 = block + eol;
4230
- } else {
4231
- text7 = block + eol + eol + startup;
4232
- }
4233
- return { text: text7, changed: text7 !== startup };
4234
- }
4235
- function readExtState(ini, section, key) {
4236
- let inSection = false;
4237
- for (const line of ini.split(/\r?\n/)) {
4238
- const header = /^\s*\[(.*)\]\s*$/.exec(line);
4239
- if (header) {
4240
- inSection = header[1] === section;
4241
- } else if (inSection) {
4242
- const eq = line.indexOf("=");
4243
- if (eq !== -1 && line.slice(0, eq).trim() === key) return line.slice(eq + 1).trim();
4244
- }
4245
- }
4246
- return void 0;
4247
- }
4248
- function autostartCheck(startup, extstate, reaperRunning) {
4249
- const label = "Start with REAPER";
4250
- if (startup === null || !startup.includes(AUTOSTART_MARKER)) {
4251
- return {
4252
- label,
4253
- status: "warn",
4254
- detail: "Not in REAPER's Scripts/__startup.lua: run mcp_bridge.lua by hand in each REAPER session",
4255
- fix: "reaper-mcp setup"
4256
- };
4257
- }
4258
- const saved = reaperRunning ? " (as REAPER last saved it)" : "";
4259
- if (extstate !== null && readExtState(extstate, "MCPBridge", "cfg_autostart") === "0") {
4260
- return {
4261
- label,
4262
- status: "info",
4263
- detail: `Off in the bridge window${saved}: run mcp_bridge.lua by hand in each REAPER session`,
4264
- fix: "turn it back on in the bridge window: Settings \u2192 Start with REAPER"
4265
- };
4266
- }
4267
- return { label, status: "ok", detail: `On \xB7 REAPER's startup script runs the bridge at launch${saved}` };
4268
- }
4269
4204
  var MCP_TOOL_NAMES = [
4270
4205
  // project
4271
4206
  "get_project_info",
@@ -5286,6 +5221,42 @@ function alignmentSummary(data) {
5286
5221
  ...data["warning"] ? { warn: 1 } : {}
5287
5222
  };
5288
5223
  }
5224
+ var VERIFY_CHECKS = ["null", "discontinuity", "pitch", "tone", "transients"];
5225
+ function verifyRow(key, c) {
5226
+ const verdict = typeof c["verdict"] === "string" ? c["verdict"] : "unknown";
5227
+ const f = (v, digits, unit) => num(v) === void 0 ? "" : `${num(v).toFixed(digits)}${unit}`;
5228
+ switch (key) {
5229
+ case "null": {
5230
+ const parts = [
5231
+ num(c["delayMs"]) ? `delay ${f(c["delayMs"], 2, " ms")}` : "",
5232
+ num(c["gainDb"]) ? `gain ${f(c["gainDb"], 1, " dB")}` : "",
5233
+ c["polarityInverted"] === true ? "polarity inverted" : "",
5234
+ typeof c["reason"] === "string" ? c["reason"] : ""
5235
+ ].filter(Boolean);
5236
+ return [key, verdict, f(c["residualDb"], 1, " dB"), parts.join(", ")];
5237
+ }
5238
+ case "discontinuity": {
5239
+ const at = num(c["atSeconds"]);
5240
+ return [key, verdict, f(c["score"], 1, "\xD7"), at === void 0 ? "" : `at ${at.toFixed(2)} s${num(c["channel"]) !== void 0 ? `, channel ${num(c["channel"]) + 1}` : ""}`];
5241
+ }
5242
+ case "pitch":
5243
+ return [key, verdict, f(c["driftCents"], 0, " cents"), typeof c["reason"] === "string" ? c["reason"] : f(c["referenceHz"], 0, " Hz reference")];
5244
+ case "tone":
5245
+ return [key, verdict, f(c["distanceDb"], 2, " dB"), ""];
5246
+ default:
5247
+ return [key, verdict, f(c["fluxLogRatio"], 2, ""), typeof c["reason"] === "string" ? c["reason"] : ""];
5248
+ }
5249
+ }
5250
+ function verifySummary(name, ref, result) {
5251
+ const checks = obj(result["checks"]);
5252
+ return {
5253
+ name,
5254
+ ...ref ? { ref } : {},
5255
+ verdict: result["verdict"],
5256
+ expect: result["expect"],
5257
+ checks: VERIFY_CHECKS.filter((k) => checks[k]).map((k) => verifyRow(k, obj(checks[k])))
5258
+ };
5259
+ }
5289
5260
  function aestheticsSummary(data) {
5290
5261
  return {
5291
5262
  name: data["trackName"],
@@ -5634,7 +5605,7 @@ function registerOfflineTools(server) {
5634
5605
  );
5635
5606
  server.tool(
5636
5607
  "verify_edit",
5637
- `Check the result of an edit you just made, since you cannot hear it: compare the edited track with the audio from before the edit and get a verdict per check. Compensated null: the delay (ms, + = later), gain (dB) and polarity between the two are estimated and removed, and the residual left (dB below the reference) says whether anything else changed (noise, a splice, a different waveform, a swapped stereo channel; it is relative to referenceRmsDb, so with a quiet reference the rounding noise of a 16-bit bounce can set it). Discontinuity: the largest sample-to-sample jump on any channel against the reference's own, with where it happens and which channel (a click or hard splice). Use expect 'identical' (default) for edits that should leave the sound alone apart from level, delay and polarity (alignment, gain, split, crossfade): the residual is judged ok/warn/fail. Use "changed" for EQ, compression and the like: the residual is reported without a verdict. Set timeScale to the stretch factor when the edit changed the timing: the waveform null is then skipped and only the click check runs. The reference is another track (e.g. a copy you kept) or an audio file of the same range from before the edit (a bounce), not an undo. Keep a reference track unmuted so it renders. Pitch, formant and transient checks are not included: they need a baseline per source. A passing result is evidence, not a replacement for listening. Requires the Python sidecar.`,
5608
+ `Check the result of an edit you just made, since you cannot hear it: compare the edited track with the audio from before the edit and get a verdict per check. Compensated null: the delay (ms, + = later), gain (dB) and polarity between the two are estimated and removed, and the residual left (dB below the reference) says whether anything else changed (noise, a splice, a different waveform, a swapped stereo channel; it is relative to referenceRmsDb, so with a quiet reference the rounding noise of a 16-bit bounce can set it). Discontinuity: the largest sample-to-sample jump on any channel against the reference's own, with where it happens and which channel (a click or hard splice). Use expect 'identical' (default) for edits that should leave the sound alone apart from level, delay and polarity (alignment, gain, split, crossfade): the residual is judged ok/warn/fail. Use "changed" for EQ, compression and the like: the residual is reported without a verdict. Set timeScale to the playback rate when the edit changed the timing (1.1 = the edit is 10% shorter): the waveform null is then skipped and the click check runs with three warn-only character checks against the reference warped through that rate: pitch drift in cents (skipped for unpitched material), tone (long-term spectrum distance in dB) and transients (smeared attacks). The reference is another track (e.g. a copy you kept) or an audio file of the same range from before the edit (a bounce), not an undo. Keep a reference track unmuted so it renders. The tone check misses a phase vocoder's smearing and the transient check is blind on drums. A passing result is evidence, not a replacement for listening. Requires the Python sidecar.`,
5638
5609
  {
5639
5610
  trackIndex: z27.coerce.number().int().min(0).describe("Zero-based index of the edited track"),
5640
5611
  referenceTrack: z27.coerce.number().int().min(0).optional().describe("Zero-based index of a track holding the audio from before the edit (give this or referencePath)"),
@@ -5642,7 +5613,7 @@ function registerOfflineTools(server) {
5642
5613
  startTime: z27.coerce.number().min(0).describe("Start of the range in seconds"),
5643
5614
  durationSeconds: z27.coerce.number().min(0.5).max(MAX_VERIFY_SECONDS).optional().default(DEFAULT_VERIFY_SECONDS).describe(`Length in seconds (default ${DEFAULT_VERIFY_SECONDS}, max ${MAX_VERIFY_SECONDS})`),
5644
5615
  expect: z27.enum(["identical", "changed"]).optional().default("identical").describe('"identical": only level, delay and polarity may differ; "changed": report the residual without a verdict'),
5645
- timeScale: z27.coerce.number().min(0.1).max(10).optional().default(1).describe("1 = the edit kept the timing (default). Any other value (a stretch) skips the waveform null"),
5616
+ timeScale: z27.coerce.number().min(0.1).max(10).optional().default(1).describe("Playback rate: 1 = the edit kept the timing (default); 1.1 = the edit is 10% shorter. Any other value skips the waveform null and runs the pitch, tone and transient checks instead"),
5646
5617
  maxLagMs: z27.coerce.number().min(0.1).max(100).optional().default(DEFAULT_MAX_LAG_MS).describe(`Largest delay to search either way in ms (default ${DEFAULT_MAX_LAG_MS})`)
5647
5618
  },
5648
5619
  async (args) => {
@@ -5675,7 +5646,7 @@ function registerOfflineTools(server) {
5675
5646
  maxLagMs: maxLagMs ?? DEFAULT_MAX_LAG_MS
5676
5647
  });
5677
5648
  if (typeof result["error"] === "string") return refuse(result["error"]);
5678
- logToolResult("verify_edit", args, startedAt, null);
5649
+ logToolResult("verify_edit", args, startedAt, verifySummary(edited.trackName, referenceTrack != null ? rendered[0].trackName : void 0, result));
5679
5650
  return text({
5680
5651
  trackIndex: trackIndex5,
5681
5652
  trackName: edited.trackName,
@@ -8987,13 +8958,13 @@ async function setup() {
8987
8958
  }
8988
8959
  const webPort = await enableWebInterface();
8989
8960
  await registerSnapshotActions();
8990
- installBridgeAutostart(scriptsDir);
8991
8961
  console.log("\nSetup complete!\n");
8992
8962
  console.log("Next steps:");
8993
- console.log(" 1. Start REAPER: the bridge starts with it. If REAPER is already open, restart it,");
8994
- console.log(" or run the bridge once by hand: Actions > Show action list > Load ReaScript,");
8995
- console.log(` select ${join12(scriptsDir, "mcp_bridge.lua")} and click Run.`);
8996
- console.log(" 2. Add reaper-mcp to your Claude Code config (see: reaper-mcp doctor)");
8963
+ console.log(" 1. Open REAPER");
8964
+ console.log(" 2. Actions > Show action list > Load ReaScript");
8965
+ console.log(` 3. Select: ${join12(scriptsDir, "mcp_bridge.lua")}`);
8966
+ console.log(" 4. Run the script (it will keep running in background via defer loop)");
8967
+ console.log(" 5. Add reaper-mcp to your Claude Code config (see: reaper-mcp doctor)");
8997
8968
  if (webPort) {
8998
8969
  console.log(`
8999
8970
  The bridge opens its status window on start: http://localhost:${webPort}/${BRIDGE_UI_FILE}`);
@@ -9045,14 +9016,6 @@ async function enableWebInterface() {
9045
9016
  console.log(` Enabled on port ${result.port} (override with REAPER_WEB_PORT)`);
9046
9017
  return result.port;
9047
9018
  }
9048
- function installBridgeAutostart(scriptsDir) {
9049
- console.log("\nStarting the bridge with REAPER...");
9050
- const path = join12(scriptsDir, "__startup.lua");
9051
- const { text: text7, changed } = ensureBridgeAutostart(existsSync7(path) ? readFileSync5(path, "utf-8") : "");
9052
- if (changed) writeFileSync5(path, text7, "utf-8");
9053
- console.log(changed ? " Added to Scripts/__startup.lua (REAPER runs it at launch)" : " Already in Scripts/__startup.lua");
9054
- console.log(" Turn it off in the bridge window: Settings > Start with REAPER.");
9055
- }
9056
9019
  async function registerSnapshotActions() {
9057
9020
  console.log("\nRegistering snapshot actions (quick save, next, previous)...");
9058
9021
  const kbPath = join12(getReaperResourcePath(), "reaper-kb.ini");
@@ -9178,12 +9141,6 @@ async function doctor() {
9178
9141
  core2.push(
9179
9142
  bridgeRunning ? { label: "Lua bridge", status: "ok", detail: "Connected" } : { label: "Lua bridge", status: "fail", detail: "Not detected", fix: "reaper-mcp setup, then run mcp_bridge.lua in REAPER" }
9180
9143
  );
9181
- const readIfExists = (path) => existsSync7(path) ? readFileSync5(path, "utf-8") : null;
9182
- core2.push(autostartCheck(
9183
- readIfExists(join12(getReaperScriptsPath(), "__startup.lua")),
9184
- readIfExists(join12(getReaperResourcePath(), "reaper-extstate.ini")),
9185
- await isReaperRunning()
9186
- ));
9187
9144
  const globalClaudeDir = join12(homedir8(), ".claude");
9188
9145
  const localSkills = existsSync7(join12(process.cwd(), ".claude", "skills", "mixer", "SKILL.md"));
9189
9146
  const globalSkills = existsSync7(join12(globalClaudeDir, "skills", "mixer", "SKILL.md"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mthines/reaper-mcp",
3
- "version": "0.71.0-beta.83.2",
3
+ "version": "0.71.0-beta.85.1",
4
4
  "type": "module",
5
5
  "description": "MCP server for controlling REAPER DAW — real-time mixing, FX control, and frequency analysis for AI agents",
6
6
  "license": "MIT",
@@ -4668,7 +4668,6 @@ end
4668
4668
 
4669
4669
  -- Settings written by the status page through REAPER's web interface (/_/SET/EXTSTATE...).
4670
4670
  -- cfg_paused is in-memory only (resets with REAPER); the others persist in reaper-extstate.ini.
4671
- -- cfg_autostart is read at REAPER's launch by the startup block setup writes into Scripts/__startup.lua.
4672
4671
  local function cfg(key)
4673
4672
  return reaper.GetExtState(STATUS_SECTION, key) == "1"
4674
4673
  end
@@ -4693,7 +4692,7 @@ local _, script_path, _, script_cmd_id = reaper.get_action_context()
4693
4692
  local script_source = script_path and read_file(script_path)
4694
4693
  local HEALTH_INTERVAL = 10
4695
4694
  local last_health_check = -HEALTH_INTERVAL
4696
- local health = { sws = false, jsfx = true, outdated = false, autostart = false }
4695
+ local health = { sws = false, jsfx = true, outdated = false }
4697
4696
  local JSFX_FILES = { "mcp_analyzer.jsfx", "mcp_lufs_meter.jsfx", "mcp_correlation_meter.jsfx", "mcp_crest_factor.jsfx", "mcp_midi_emitter.jsfx" }
4698
4697
 
4699
4698
  local function check_health(now)
@@ -4711,13 +4710,8 @@ local function check_health(now)
4711
4710
  missingJsfx = #missing > 0 and missing or nil,
4712
4711
  -- The installed script changed under us (setup ran): this running copy is stale until restarted
4713
4712
  outdated = script_source ~= nil and installed ~= nil and installed ~= script_source,
4714
- -- REAPER's startup script holds the block `reaper-mcp setup` writes (AUTOSTART_BLOCK in cli.ts), which
4715
- -- starts the bridge with REAPER unless the page's cfg_autostart is "0"
4716
- autostart = ((read_file(reaper.GetResourcePath() .. "/Scripts/__startup.lua") or "")
4717
- :find("reaper-mcp: start the bridge with REAPER", 1, true)) ~= nil,
4718
4713
  }
4719
- if next_health.sws ~= health.sws or next_health.jsfx ~= health.jsfx or next_health.outdated ~= health.outdated
4720
- or next_health.autostart ~= health.autostart then
4714
+ if next_health.sws ~= health.sws or next_health.jsfx ~= health.jsfx or next_health.outdated ~= health.outdated then
4721
4715
  status_dirty = true
4722
4716
  end
4723
4717
  health = next_health
@@ -5300,11 +5294,7 @@ local function publish_status(now, force)
5300
5294
  deferMs = defer_n > 0 and math.floor(defer_sum / defer_n * 100000 + 0.5) / 100 or 0,
5301
5295
  recent = status.recent,
5302
5296
  sessions = session_list(),
5303
- settings = {
5304
- paused = cfg("cfg_paused"), readonly = cfg("cfg_readonly"), openOnStart = open_on_start(), dev = dev_mode(),
5305
- -- Start with REAPER: on unless turned off ("0"); read by the startup block, not by this script
5306
- autostart = reaper.GetExtState(STATUS_SECTION, "cfg_autostart") ~= "0",
5307
- },
5297
+ settings = { paused = cfg("cfg_paused"), readonly = cfg("cfg_readonly"), openOnStart = open_on_start(), dev = dev_mode() },
5308
5298
  health = health,
5309
5299
  web = web_watch.status,
5310
5300
  control = control_status(),
@@ -241,3 +241,77 @@ def test_a_polarity_flip_of_one_channel_fails_instead_of_being_called_silent():
241
241
 
242
242
  def test_empty_audio_is_refused_as_too_short():
243
243
  assert "too short" in verify.verify_edit(np.zeros(0), np.zeros(0), SR)["error"]
244
+
245
+
246
+ # --- stretch character checks (timeScale != 1): pitch drift, tone, transients -------------------
247
+
248
+ def _voice(seconds: float, pitch_scale: float = 1.0, rate: float = 1.0) -> np.ndarray:
249
+ """A harmonic tone with a slow pitch contour. `rate` > 1 plays the same contour faster (shorter) at the same pitch."""
250
+ t = np.arange(int(seconds / rate * SR)) / SR
251
+ f0 = pitch_scale * (150 + 30 * np.sin(2 * np.pi * 0.5 * t * rate))
252
+ phase = 2 * np.pi * np.cumsum(f0) / SR
253
+ return 0.2 * sum(np.sin(h * phase) / h for h in range(1, 10))
254
+
255
+
256
+ def _resampled(x: np.ndarray, rate: float) -> np.ndarray:
257
+ """Varispeed: plays x `rate` times faster, so pitch moves with the speed."""
258
+ return np.interp(np.arange(0, len(x) - 1, rate), np.arange(len(x)), x)
259
+
260
+
261
+ def _character(reference, edited, rate):
262
+ return verify.verify_edit(reference, edited, SR, time_scale=rate)["checks"]
263
+
264
+
265
+ def test_a_stretch_that_keeps_the_pitch_passes_every_character_check():
266
+ checks = _character(_voice(4), _voice(4, rate=1.1), 1.1)
267
+ assert checks["pitch"]["verdict"] == "ok"
268
+ assert abs(checks["pitch"]["driftCents"]) < 10
269
+ assert checks["tone"]["verdict"] == "ok"
270
+ assert checks["transients"]["verdict"] == "ok"
271
+
272
+
273
+ def test_varispeed_is_reported_as_pitch_drift_in_cents():
274
+ reference = _voice(4)
275
+ checks = _character(reference, _resampled(reference, 1.1), 1.1)
276
+ assert checks["pitch"]["verdict"] == "warn"
277
+ assert checks["pitch"]["driftCents"] == pytest.approx(1200 * np.log2(1.1), abs=15)
278
+
279
+
280
+ def test_a_half_semitone_error_is_found():
281
+ checks = _character(_voice(4), _voice(4, pitch_scale=2 ** (0.5 / 12), rate=1.1), 1.1)
282
+ assert checks["pitch"]["verdict"] == "warn"
283
+ assert checks["pitch"]["driftCents"] == pytest.approx(50, abs=12)
284
+
285
+
286
+ def test_unpitched_material_skips_the_pitch_check_and_says_why():
287
+ noise = np.random.default_rng(0).standard_normal(4 * SR) * 0.1
288
+ checks = _character(noise, noise[: int(len(noise) / 1.1)], 1.1)
289
+ assert checks["pitch"]["verdict"] == "skipped"
290
+ assert "pitch" in checks["pitch"]["reason"]
291
+
292
+
293
+ def test_added_noise_changes_the_tone_and_warns():
294
+ reference = _voice(4)
295
+ rng = np.random.default_rng(3)
296
+ noisy = _voice(4, rate=1.1) + rng.standard_normal(len(_voice(4, rate=1.1))) * 0.02
297
+ assert _character(reference, noisy, 1.1)["tone"]["verdict"] == "warn"
298
+
299
+
300
+ def test_smeared_attacks_lower_the_transient_score_and_warn():
301
+ rng = np.random.default_rng(1)
302
+ hits = np.zeros(4 * SR)
303
+ for position in range(0, 4 * SR, SR // 4):
304
+ hits[position:position + 600] = rng.standard_normal(600) * np.exp(-np.arange(600) / 120)
305
+ hits += rng.standard_normal(len(hits)) * 0.002
306
+ smeared = np.convolve(hits, np.hanning(int(0.04 * SR)) / np.hanning(int(0.04 * SR)).sum(), mode="same")
307
+ assert _character(hits, smeared[: int(len(hits) / 1.1)], 1.1)["transients"]["verdict"] == "warn"
308
+
309
+
310
+ def test_character_checks_only_run_when_the_timing_changed(source):
311
+ assert "pitch" not in verify.verify_edit(source, source.copy(), SR)["checks"]
312
+
313
+
314
+ def test_a_character_warning_makes_the_verdict_a_warning_never_a_fail():
315
+ reference = _voice(4)
316
+ result = verify.verify_edit(reference, _resampled(reference, 1.1), SR, time_scale=1.1)
317
+ assert result["verdict"] == "warn"
package/sidecar/verify.py CHANGED
@@ -13,8 +13,16 @@ experiment behind the tool (github.com/mthines/reaper-mcp issue 69):
13
13
  splice or a click scores far above anything a clean edit produces. Judged against
14
14
  the reference's own score, so a source that is naturally spiky is not flagged.
15
15
 
16
- Pitch, formant and transient checks were source-dependent in the experiment (they
17
- need a pitch range and a baseline per source), so they are not part of this module.
16
+ When the timing changed (a stretch, `time_scale` != 1) the null cannot run, so three
17
+ "character" checks compare the edit with the reference warped through the known time
18
+ map instead (experiment: github.com/mthines/reaper-mcp issue 81). They only ever warn:
19
+
20
+ * Pitch drift: median cents between matching voiced frames. The pitch range comes from
21
+ the reference itself; material without a stable pitch is skipped, with the reason.
22
+ * Tone: rms dB difference of the long-term spectrum (40 mel bands, gain removed). Catches
23
+ varispeed, pitch shifts and added noise; blind to a phase vocoder's smearing.
24
+ * Transients: log ratio of spectral-flux peakiness. Only a drop counts (smearing lowers
25
+ it); blind on drum-like material.
18
26
  """
19
27
 
20
28
  from __future__ import annotations
@@ -34,6 +42,13 @@ CLICK_WARN_RATIO = 2.0
34
42
 
35
43
  SILENCE = 1e-6
36
44
 
45
+ # Character checks (only when the timing changed): warn lines from the issue 81 experiment
46
+ PITCH_WARN_CENTS = 20.0
47
+ TONE_WARN_DB = 0.7
48
+ TRANSIENT_WARN_LOG = -0.25
49
+ MIN_VOICED_FRAMES = 12
50
+ MIN_VOICED_SHARE = 0.25
51
+
37
52
 
38
53
  def _mono(audio: np.ndarray) -> np.ndarray:
39
54
  """(channels, samples) or (samples,) to float64 mono."""
@@ -159,6 +174,131 @@ def _worst_channel(reference: np.ndarray, edited: np.ndarray, edge_samples: int)
159
174
  return best or (discontinuity_score(edit_ch[0]), discontinuity_score(ref_ch[0]), None)
160
175
 
161
176
 
177
+ def _stft_power(x: np.ndarray, n_fft: int = 2048, hop: int = 512) -> np.ndarray:
178
+ """(frames, bins) power spectrum with a Hann window; zero-padded to at least one frame."""
179
+ if len(x) < n_fft:
180
+ x = np.pad(x, (0, n_fft - len(x)))
181
+ frames = np.lib.stride_tricks.sliding_window_view(x, n_fft)[::hop]
182
+ return np.abs(np.fft.rfft(frames * np.hanning(n_fft), axis=1)) ** 2
183
+
184
+
185
+ def _normalised(x: np.ndarray) -> np.ndarray:
186
+ """Peak 0.5, so level-dependent measures compare like with like."""
187
+ return x / (np.max(np.abs(x)) + 1e-12) * 0.5
188
+
189
+
190
+ def _f0_track(x: np.ndarray, sample_rate: int, lo: float, hi: float,
191
+ frame: int = 4096, hop: int = 1024) -> tuple[np.ndarray, np.ndarray]:
192
+ """
193
+ Per-frame f0 (Hz) and a voiced mask from the normalised square difference function:
194
+ the first peak within 10% of the highest in the lag range [sr/hi, sr/lo], parabolic
195
+ interpolation, voiced above 0.8. Frames hop by `hop` samples.
196
+ """
197
+ if len(x) < frame:
198
+ x = np.pad(x, (0, frame - len(x)))
199
+ frames = np.lib.stride_tricks.sliding_window_view(x, frame)[::hop] * np.hanning(frame)
200
+ size = 2 * frame
201
+ spec = np.fft.rfft(frames, size, axis=1)
202
+ acf = np.fft.irfft(np.abs(spec) ** 2, size, axis=1)[:, :frame]
203
+ sq = np.cumsum(frames ** 2, axis=1)
204
+ total = sq[:, -1:]
205
+ # m[tau] = sum_{i<N-tau} (x_i^2 + x_{i+tau}^2): the energy left after dropping the last tau and the first tau samples
206
+ head = np.concatenate([np.zeros((len(frames), 1)), sq[:, :-1]], axis=1)
207
+ tail = total - sq[:, ::-1] # sum of the last tau squares, indexed by tau-1
208
+ tail = np.concatenate([np.zeros((len(frames), 1)), tail[:, :-1]], axis=1)
209
+ m = (total - tail) + (total - head)
210
+ nsdf = 2 * acf / (m + 1e-12)
211
+ lag_lo, lag_hi = max(2, int(sample_rate / hi)), min(frame - 2, int(sample_rate / lo))
212
+ window = nsdf[:, lag_lo:lag_hi]
213
+ f0 = np.full(len(frames), np.nan)
214
+ voiced = np.zeros(len(frames), dtype=bool)
215
+ for i, row in enumerate(window):
216
+ top = float(row.max())
217
+ if top < 0.8:
218
+ continue
219
+ peaks = np.where((row[1:-1] > row[:-2]) & (row[1:-1] >= row[2:]) & (row[1:-1] >= 0.9 * top))[0]
220
+ if len(peaks) == 0:
221
+ continue
222
+ k = int(peaks[0]) + 1
223
+ a, b, c = row[k - 1], row[k], row[k + 1]
224
+ denom = a - 2 * b + c
225
+ shift = 0.5 * (a - c) / denom if abs(denom) > 1e-12 else 0.0
226
+ f0[i] = sample_rate / (lag_lo + k + shift)
227
+ voiced[i] = True
228
+ return f0, voiced
229
+
230
+
231
+ def pitch_drift(reference: np.ndarray, edited: np.ndarray, sample_rate: int, rate: float) -> dict[str, Any]:
232
+ """
233
+ Median cents between the edit and the reference at matching voiced frames (`rate` > 1: the edit is
234
+ shorter, so edit time t is reference time t * rate). The range comes from the reference; a pass
235
+ that finds no stable pitch is skipped with the reason.
236
+ """
237
+ wide_f0, wide_voiced = _f0_track(reference, sample_rate, 50.0, 1000.0)
238
+ if wide_voiced.mean() < MIN_VOICED_SHARE or wide_voiced.sum() < MIN_VOICED_FRAMES:
239
+ return {"verdict": "skipped", "reason": "no stable pitch in the reference (unpitched material)"}
240
+ centre = float(np.median(wide_f0[wide_voiced]))
241
+ lo, hi = max(40.0, centre / 2.0), min(1500.0, centre * 2.0)
242
+ if centre < 50.0 * 1.05 or centre > 1000.0 * 0.95:
243
+ return {"verdict": "skipped", "reason": "the pitch tracker stayed at the edge of its range (no reliable pitch)"}
244
+ ref_f0, ref_voiced = _f0_track(reference, sample_rate, lo, hi)
245
+ edit_f0, edit_voiced = _f0_track(edited, sample_rate, lo, hi)
246
+ index = np.round(np.arange(len(edit_f0)) * rate).astype(int)
247
+ inside = index < len(ref_f0)
248
+ index, edit_f0, edit_voiced = index[inside], edit_f0[inside], edit_voiced[inside]
249
+ both = ref_voiced[index] & edit_voiced
250
+ if both.sum() < MIN_VOICED_FRAMES:
251
+ return {"verdict": "skipped", "reason": "too few voiced frames in both to compare"}
252
+ cents = 1200.0 * np.log2(edit_f0[both] / ref_f0[index][both])
253
+ drift = float(np.median(cents))
254
+ return {
255
+ "verdict": "warn" if abs(drift) >= PITCH_WARN_CENTS else "ok",
256
+ "driftCents": round(drift, 1),
257
+ "referenceHz": round(centre, 1),
258
+ "framesCompared": int(both.sum()),
259
+ }
260
+
261
+
262
+ def _mel_filterbank(sample_rate: int, n_fft: int = 2048, bands: int = 40) -> np.ndarray:
263
+ """Triangular mel filters, 60 Hz to 10 kHz (or 95% of Nyquist): (bands, bins)."""
264
+ to_mel = lambda f: 2595.0 * np.log10(1.0 + f / 700.0)
265
+ from_mel = lambda m: 700.0 * (10.0 ** (m / 2595.0) - 1.0)
266
+ points = from_mel(np.linspace(to_mel(60.0), to_mel(min(10000.0, sample_rate / 2.0 * 0.95)), bands + 2))
267
+ freqs = np.fft.rfftfreq(n_fft, 1.0 / sample_rate)
268
+ bank = np.zeros((bands, len(freqs)))
269
+ for i in range(bands):
270
+ left, centre, right = points[i:i + 3]
271
+ bank[i] = np.maximum(0.0, np.minimum((freqs - left) / (centre - left), (right - freqs) / (right - centre)))
272
+ return bank
273
+
274
+
275
+ def _long_term_bands(x: np.ndarray, sample_rate: int) -> np.ndarray:
276
+ """Mean dB per mel band over the frames within 40 dB of the loudest (a mean of dB, so sparse bursts do not dominate)."""
277
+ levels = 10.0 * np.log10(_stft_power(x) @ _mel_filterbank(sample_rate).T + 1e-10)
278
+ frame_level = levels.mean(axis=1)
279
+ return levels[frame_level > frame_level.max() - 40.0].mean(axis=0)
280
+
281
+
282
+ def tone_difference(reference: np.ndarray, edited: np.ndarray, sample_rate: int) -> dict[str, Any]:
283
+ """Rms dB difference of the long-term spectrum, overall gain removed."""
284
+ delta = _long_term_bands(reference, sample_rate) - _long_term_bands(edited, sample_rate)
285
+ distance = float(np.sqrt(np.mean((delta - delta.mean()) ** 2)))
286
+ return {"verdict": "warn" if distance >= TONE_WARN_DB else "ok", "distanceDb": round(distance, 2)}
287
+
288
+
289
+ def _flux_peakiness(x: np.ndarray) -> float:
290
+ power = _stft_power(x, 1024, 256)
291
+ logged = np.log1p(np.sqrt(power) * 20.0)
292
+ flux = np.maximum(np.diff(logged, axis=0), 0.0).sum(axis=1)
293
+ return float(np.percentile(flux, 99) / (np.mean(flux) + 1e-9))
294
+
295
+
296
+ def transient_change(reference: np.ndarray, edited: np.ndarray) -> dict[str, Any]:
297
+ """Log ratio of spectral-flux peakiness, edit over reference; only a drop (smeared attacks) warns."""
298
+ ratio = float(np.log(_flux_peakiness(_normalised(edited)) / _flux_peakiness(_normalised(reference))))
299
+ return {"verdict": "warn" if ratio <= TRANSIENT_WARN_LOG else "ok", "fluxLogRatio": round(ratio, 3)}
300
+
301
+
162
302
  def _click_verdict(edit_score: float | None, ref_score: float | None) -> str:
163
303
  if edit_score is None:
164
304
  return "unknown"
@@ -213,6 +353,10 @@ def verify_edit(reference: np.ndarray, edited: np.ndarray, sample_rate: int, *,
213
353
 
214
354
  if abs(time_scale - 1.0) > 1e-6:
215
355
  checks["null"] = {"verdict": "skipped", "reason": "timing changed (timeScale != 1): a waveform null needs the same timing"}
356
+ ref_mono, edit_mono = _mono(reference), _mono(edited)
357
+ checks["pitch"] = pitch_drift(ref_mono, edit_mono, sample_rate, time_scale)
358
+ checks["tone"] = tone_difference(ref_mono, edit_mono, sample_rate)
359
+ checks["transients"] = transient_change(ref_mono, edit_mono)
216
360
  else:
217
361
  null = compensated_null(reference, edited, sample_rate, max_lag_ms)
218
362
  if "error" in null: