@mthines/reaper-mcp 0.95.1 → 0.96.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.
- package/README.md +45 -45
- package/bridge-ui/mcp_bridge.html +4 -4
- package/claude/knowledge/workflows/vocal-alignment.md +1 -1
- package/main.js +35 -39
- package/package.json +1 -1
- package/reaper/mcp_render_lib.lua +215 -2
|
@@ -37,7 +37,7 @@ The align call plans from the items' source files. What the user hears is the re
|
|
|
37
37
|
2. **Timing check on the render.** `detect_transients` on the guide track and the double track over the aligned range (`limit` high enough for the range, `minGapMs` 60). Pair hits within about 100 ms, using the strong ones first (strength above about 0.4 on either side, or both). Write down each pair's offset (double minus guide, ms).
|
|
38
38
|
3. **Judge.** Most pairs should sit within about ±15 ms (the tool's own after-average is 5-7 ms). Pairs beyond about 20 ms are outliers. List them with time, offset and strength.
|
|
39
39
|
4. **Do not use `measure_track_alignment` to judge a lead against a backing.** The two differ in texture (a scream against a sung line was measured at correlation 0.07-0.11, under the 0.3 it needs), so its delay is not to be trusted. Use onset pairing.
|
|
40
|
-
5. **Detectors can disagree.** `align_audio_to_guide` reads source files; `detect_transients` on a track reads the render. On low-band hits of a loud lead the two once placed the same hit about 100 ms apart. Before moving a marker for an outlier, check that both sides really have that hit (strength, band, a neighbouring pair that agrees). When the detectors disagree and nothing nearby confirms the outlier, do not move it: hand it to the user's ear.
|
|
40
|
+
5. **Detectors can disagree.** `align_audio_to_guide` reads source files; `detect_transients` on a track reads the track's own audio before FX (a render when that can't be read). On low-band hits of a loud lead the two once placed the same hit about 100 ms apart. Before moving a marker for an outlier, check that both sides really have that hit (strength, band, a neighbouring pair that agrees). When the detectors disagree and nothing nearby confirms the outlier, do not move it: hand it to the user's ear.
|
|
41
41
|
A wrong pairing is the usual cause of a real outlier. Look at both source files with `detect_transients` (`path`, `filePosition` = item position minus start offset, `startTime` at or after `filePosition`): a guide hit with a very low `peakDb` (about -40 dB or lower) is a false hit, and the pairing can put the double's real hit on it and shift every hit after it by one (seen: a -53 dB blip took a real hit 80 ms early and stretched the audio after it by 1.4x). The fix is the markers: pin the double's real hit (marker `sourcePosition` = start offset + the hit's item time) on the guide's real hit, and keep the next marker at its natural spacing.
|
|
42
42
|
Two strong hits of the double close together (about 50 ms) against one guide hit are ambiguous (which one is the onset?). Do not guess: report the spot to the user.
|
|
43
43
|
6. **Fix and re-measure.** For a confirmed outlier, move that one hit: `get_stretch_markers`, then `edit_stretch_markers` (position in item seconds; all edits are checked against the whole list first). Re-render and repeat from step 2 on the touched range. At most 3 rounds, then stop and report what is left; never loop on an outlier the markers cannot fix (a hit with no partner, a marker that would cross its neighbour).
|
package/main.js
CHANGED
|
@@ -4598,27 +4598,30 @@ import { randomUUID as randomUUID4 } from "node:crypto";
|
|
|
4598
4598
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
4599
4599
|
import { unlink as unlink2 } from "node:fs/promises";
|
|
4600
4600
|
var renderTimeoutMs = (seconds2) => 3e4 + seconds2 * 400;
|
|
4601
|
-
|
|
4601
|
+
function dryWanted(options) {
|
|
4602
|
+
return options?.dry === true && !/^(0|false|off)$/i.test(process.env["REAPER_MCP_DRY_READ"] ?? "");
|
|
4603
|
+
}
|
|
4604
|
+
async function renderTrack(trackIndex5, startTime, endTime, options) {
|
|
4602
4605
|
const res = await sendCommand(
|
|
4603
4606
|
"render_track_to_wav",
|
|
4604
|
-
{ trackIndex: trackIndex5, startTime, endTime, commandId: randomUUID3() },
|
|
4607
|
+
{ trackIndex: trackIndex5, startTime, endTime, commandId: randomUUID3(), ...dryWanted(options) ? { dry: true } : {} },
|
|
4605
4608
|
renderTimeoutMs(endTime - startTime)
|
|
4606
4609
|
);
|
|
4607
4610
|
if (!res.success) throw new Error(`Render failed: ${res.error}`);
|
|
4608
4611
|
return res.data;
|
|
4609
4612
|
}
|
|
4610
|
-
async function renderTracks(trackIndices, startTime, endTime) {
|
|
4611
|
-
if (trackIndices.length === 1) return [await renderTrack(trackIndices[0], startTime, endTime)];
|
|
4613
|
+
async function renderTracks(trackIndices, startTime, endTime, options) {
|
|
4614
|
+
if (trackIndices.length === 1) return [await renderTrack(trackIndices[0], startTime, endTime, options)];
|
|
4612
4615
|
const res = await sendCommand(
|
|
4613
4616
|
"render_tracks_to_wav",
|
|
4614
|
-
{ trackIndices, startTime, endTime, commandId: randomUUID3() },
|
|
4617
|
+
{ trackIndices, startTime, endTime, commandId: randomUUID3(), ...dryWanted(options) ? { dry: true } : {} },
|
|
4615
4618
|
renderTimeoutMs((endTime - startTime) * trackIndices.length)
|
|
4616
4619
|
);
|
|
4617
4620
|
if (res.success) return res.data.tracks;
|
|
4618
4621
|
if (/Unknown command type/.test(res.error ?? "")) {
|
|
4619
4622
|
const out2 = [];
|
|
4620
4623
|
try {
|
|
4621
|
-
for (const t of trackIndices) out2.push(await renderTrack(t, startTime, endTime));
|
|
4624
|
+
for (const t of trackIndices) out2.push(await renderTrack(t, startTime, endTime, options));
|
|
4622
4625
|
} catch (err) {
|
|
4623
4626
|
await Promise.all(out2.map(discardRender));
|
|
4624
4627
|
throw err;
|
|
@@ -6297,7 +6300,7 @@ function registerOfflineTools(server) {
|
|
|
6297
6300
|
);
|
|
6298
6301
|
server.tool(
|
|
6299
6302
|
"verify_edit",
|
|
6300
|
-
`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, line 1.5 dB, provisional) and transients (smeared attacks). When the pitch moved by what the speed change alone causes (a plain speed change, pitch follows speed), pitch and tone are reported as info, not warned; a pitch move the speed does not explain still warns. Slow-downs below 0.9 also get a dropout check (the deepest dip of the edited loudness under the original, warn from 12 dB, provisional): bigger slow-downs stretch audible artifacts into a vocal that the other checks do not hear, so listen to those either way. 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.`,
|
|
6303
|
+
`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. Both sides are rendered (after track FX, pan and fader), so FX and fader edits show. 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, line 1.5 dB, provisional) and transients (smeared attacks). When the pitch moved by what the speed change alone causes (a plain speed change, pitch follows speed), pitch and tone are reported as info, not warned; a pitch move the speed does not explain still warns. Slow-downs below 0.9 also get a dropout check (the deepest dip of the edited loudness under the original, warn from 12 dB, provisional): bigger slow-downs stretch audible artifacts into a vocal that the other checks do not hear, so listen to those either way. 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.`,
|
|
6301
6304
|
{
|
|
6302
6305
|
trackIndex: z28.coerce.number().int().min(0).describe("Zero-based index of the edited track"),
|
|
6303
6306
|
referenceTrack: z28.coerce.number().int().min(0).optional().describe("Zero-based index of a track holding the audio from before the edit (give this or referencePath)"),
|
|
@@ -6358,13 +6361,11 @@ function registerOfflineTools(server) {
|
|
|
6358
6361
|
|
|
6359
6362
|
// apps/reaper-mcp-server/src/tools/transients.ts
|
|
6360
6363
|
import { z as z29 } from "zod/v4";
|
|
6361
|
-
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
6362
6364
|
var SIDECAR_NOT_INSTALLED_MSG3 = `Audio understanding sidecar not installed. ${SETUP_SIDECAR_HINT}`;
|
|
6363
6365
|
var DEFAULT_TRACK_SECONDS = 60;
|
|
6364
6366
|
var DEFAULT_LIMIT = 200;
|
|
6365
6367
|
var MAX_AUTOMATION_POINTS = 2e4;
|
|
6366
6368
|
var CUT_GAP = 5e-4;
|
|
6367
|
-
var renderTimeoutMs2 = (seconds2) => 3e4 + seconds2 * 400;
|
|
6368
6369
|
var text2 = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
|
|
6369
6370
|
var error2 = (message) => ({ content: [{ type: "text", text: message }], isError: true });
|
|
6370
6371
|
var round = (x, digits = 4) => Math.round(x * 10 ** digits) / 10 ** digits;
|
|
@@ -6461,13 +6462,12 @@ async function detect(args) {
|
|
|
6461
6462
|
end = args.endTime ?? start + DEFAULT_TRACK_SECONDS;
|
|
6462
6463
|
if (end <= start) return "endTime must be greater than startTime";
|
|
6463
6464
|
if (end - start > MAX_OFFLINE_SECONDS) return `Range too long: max ${MAX_OFFLINE_SECONDS} s per call`;
|
|
6464
|
-
|
|
6465
|
-
|
|
6466
|
-
|
|
6467
|
-
|
|
6468
|
-
|
|
6469
|
-
|
|
6470
|
-
const wav = res.data;
|
|
6465
|
+
let wav;
|
|
6466
|
+
try {
|
|
6467
|
+
wav = await renderTrack(trackIndex5, start, end, { dry: true });
|
|
6468
|
+
} catch (err) {
|
|
6469
|
+
return err instanceof Error ? err.message : String(err);
|
|
6470
|
+
}
|
|
6471
6471
|
try {
|
|
6472
6472
|
result = await sidecar.transients({ path: wav.wavPath, ...options });
|
|
6473
6473
|
} finally {
|
|
@@ -6494,7 +6494,7 @@ async function detect(args) {
|
|
|
6494
6494
|
function registerTransientTools(server) {
|
|
6495
6495
|
server.tool(
|
|
6496
6496
|
"detect_transients",
|
|
6497
|
-
"Find the transients (hits/onsets) in a track (
|
|
6497
|
+
"Find the transients (hits/onsets) in a track (read from its own items, before track FX and pan, without a render; the master is rendered) or an audio file on disk: each hit's time in project seconds, strength (0..1, relative to the loudest hits), dominant band (low = kick/bass, mid = snare/vocals/keys, high = hats/cymbals) and peakDb, plus a tempo estimate, hit counts per band and, with sectionSeconds, how busy each part is. Hits are paginated (offset/limit). Use it to sync lighting, video cuts, markers or MIDI to a song; create_transient_automation writes the hits as envelope pulses directly. A file is read as-is (no stretch markers or play rate): for an item warped to the grid, pass its track instead. Requires the Python sidecar.",
|
|
6498
6498
|
{
|
|
6499
6499
|
...sourceSchema,
|
|
6500
6500
|
sectionSeconds: z29.coerce.number().min(1).max(120).optional().describe("Also report hit count and mean strength per section of this length (e.g. 8)"),
|
|
@@ -6536,7 +6536,7 @@ function registerTransientTools(server) {
|
|
|
6536
6536
|
);
|
|
6537
6537
|
server.tool(
|
|
6538
6538
|
"create_transient_automation",
|
|
6539
|
-
`Detect the transients of a track or audio file (same options as detect_transients) and write one pulse per hit onto an existing envelope of a target track \u2014 e.g. a lighting/DMX plugin parameter that should flash on every kick. Each pulse rises from baseValue to the hit level (peakValue, scaled by strength unless scaleByStrength is false) over attackMs, holds holdMs, and falls back over decayMs; a hit before the previous pulse has ended cuts it short. Values are raw envelope values (FX parameters 0..1, Pan -1..1). Create the envelope first with create_track_envelope (it returns envelopeIndex). By default the envelope's points in the range are replaced (replaceExisting). dryRun returns the points without writing. Use bands/minStrength/minGapMs to choose what the lights follow (e.g. bands ["low"], minStrength 0.6 for the kick accents). Requires the Python sidecar.`,
|
|
6539
|
+
`Detect the transients of a track (its own audio, before FX and pan) or audio file (same options as detect_transients) and write one pulse per hit onto an existing envelope of a target track \u2014 e.g. a lighting/DMX plugin parameter that should flash on every kick. Each pulse rises from baseValue to the hit level (peakValue, scaled by strength unless scaleByStrength is false) over attackMs, holds holdMs, and falls back over decayMs; a hit before the previous pulse has ended cuts it short. Values are raw envelope values (FX parameters 0..1, Pan -1..1). Create the envelope first with create_track_envelope (it returns envelopeIndex). By default the envelope's points in the range are replaced (replaceExisting). dryRun returns the points without writing. Use bands/minStrength/minGapMs to choose what the lights follow (e.g. bands ["low"], minStrength 0.6 for the kick accents). Requires the Python sidecar.`,
|
|
6540
6540
|
{
|
|
6541
6541
|
...sourceSchema,
|
|
6542
6542
|
targetTrack: z29.coerce.number().int().min(-1).describe("Track that holds the envelope to write (-1 = master)"),
|
|
@@ -7418,7 +7418,6 @@ function registerAlignTools(server) {
|
|
|
7418
7418
|
|
|
7419
7419
|
// apps/reaper-mcp-server/src/tools/composition.ts
|
|
7420
7420
|
import { z as z33 } from "zod/v4";
|
|
7421
|
-
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
7422
7421
|
import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
|
|
7423
7422
|
import { basename as basename3, extname as extname2 } from "node:path";
|
|
7424
7423
|
import { trace as trace8 } from "@opentelemetry/api";
|
|
@@ -7920,7 +7919,6 @@ var error6 = (message) => ({ content: [{ type: "text", text: message }], isError
|
|
|
7920
7919
|
var MAX_MIDI_FILE_BYTES = 5 * 1024 * 1024;
|
|
7921
7920
|
var MAX_IMPORT_NOTES = 2e4;
|
|
7922
7921
|
var DEFAULT_KEY_SECONDS = 60;
|
|
7923
|
-
var renderTimeoutMs3 = (seconds2) => 3e4 + seconds2 * 400;
|
|
7924
7922
|
var chordModelTimeoutMs = (seconds2) => 6e4 + seconds2 * 500;
|
|
7925
7923
|
var selectionSchema = {
|
|
7926
7924
|
trackIndex: z33.coerce.number().int().min(0).describe("Track index (0-based)"),
|
|
@@ -8096,7 +8094,7 @@ function registerCompositionTools(server) {
|
|
|
8096
8094
|
);
|
|
8097
8095
|
server.tool(
|
|
8098
8096
|
"detect_key",
|
|
8099
|
-
`Detect the musical key (e.g. "A minor") of a track or an audio file: from a track's MIDI notes (note time weighted by velocity, drums on channel 10 ignored) or, for audio, from its
|
|
8097
|
+
`Detect the musical key (e.g. "A minor") of a track or an audio file: from a track's MIDI notes (note time weighted by velocity, drums on channel 10 ignored) or, for audio, from its chroma (Python sidecar; a track is read from its own items, before FX and pan, without a render). Returns the key, confidence 0..1 (how far it stands out from the next candidate that is not its relative key, scaled down for a flat profile and by how well the key fits \u2014 its correlation), the relative key, the top 3 alternatives with their correlation, and the 12-bin chroma (C first). Use it before writing parts, choosing a pitch-correction scale or a harmonizer key.`,
|
|
8100
8098
|
{
|
|
8101
8099
|
trackIndex: z33.coerce.number().int().min(-1).optional().describe("Track to analyze (-1 = master). Give this or path"),
|
|
8102
8100
|
path: z33.string().min(1).optional().describe("Absolute path of an audio file to analyze instead (sidecar)"),
|
|
@@ -8161,13 +8159,12 @@ function registerCompositionTools(server) {
|
|
|
8161
8159
|
} else {
|
|
8162
8160
|
const end = args.endTime ?? start + DEFAULT_KEY_SECONDS;
|
|
8163
8161
|
if (end - start > MAX_OFFLINE_SECONDS) return fail4(`Range too long: max ${MAX_OFFLINE_SECONDS} s per call`);
|
|
8164
|
-
|
|
8165
|
-
|
|
8166
|
-
|
|
8167
|
-
|
|
8168
|
-
|
|
8169
|
-
|
|
8170
|
-
const wav = res.data;
|
|
8162
|
+
let wav;
|
|
8163
|
+
try {
|
|
8164
|
+
wav = await renderTrack(trackIndex5, start, end, { dry: true });
|
|
8165
|
+
} catch (err) {
|
|
8166
|
+
return fail4(err instanceof Error ? err.message : String(err));
|
|
8167
|
+
}
|
|
8171
8168
|
try {
|
|
8172
8169
|
const c = await sidecar.chroma({ path: wav.wavPath });
|
|
8173
8170
|
profile = c.chroma;
|
|
@@ -8200,7 +8197,7 @@ function registerCompositionTools(server) {
|
|
|
8200
8197
|
);
|
|
8201
8198
|
server.tool(
|
|
8202
8199
|
"detect_chords",
|
|
8203
|
-
'Detect the chords of a track, one media item or an audio file, one per bar (default) or beat: from MIDI notes (drums on channel 10 ignored; the lowest held note gives slash chords like C/E) or from
|
|
8200
|
+
'Detect the chords of a track, one media item or an audio file, one per bar (default) or beat: from MIDI notes (drums on channel 10 ignored; the lowest held note gives slash chords like C/E) or from audio (Python sidecar chroma; a track is read from its own items, before FX and pan). Track bars and beats follow the project tempo map; a file uses `bpm` (bar 1 at startTime) or fixed windows. Returns the key, the progression ("Am F C G"), and chord spans (equal neighbours merged): start/end seconds, bar.beat, chord, root, quality (maj, min, 7, maj7, m7, sus2, sus4, dim, aug; the model also dim7, m7b5, 6, m6, 9, maj9, m9, mMaj7, 5, 11, 13), roman numeral in the key, bassMidi (a MIDI note for a bass line, E1-D#2) and a 0..1 fit; "N" = no chord. Paginated (offset/limit). Audio uses the chord model (lv-chordia, slash chords and sevenths from a full mix) when installed (setup-sidecar --with-chords), else chroma templates; `engine` picks. Use it before writing a bass line or other parts to existing guitars, keys or vocals.',
|
|
8204
8201
|
{
|
|
8205
8202
|
trackIndex: z33.coerce.number().int().min(-1).optional().describe("Track to analyze (-1 = master, audio only). Give this or path"),
|
|
8206
8203
|
path: z33.string().min(1).optional().describe("Absolute path of an audio file to analyze instead (sidecar)"),
|
|
@@ -8329,13 +8326,12 @@ function registerCompositionTools(server) {
|
|
|
8329
8326
|
if (end - start > MAX_OFFLINE_SECONDS) return fail4(`Range too long: max ${MAX_OFFLINE_SECONDS} s per call (give startTime/endTime)`);
|
|
8330
8327
|
const model = await useModel();
|
|
8331
8328
|
if (typeof model === "string") return fail4(model);
|
|
8332
|
-
|
|
8333
|
-
|
|
8334
|
-
|
|
8335
|
-
|
|
8336
|
-
|
|
8337
|
-
|
|
8338
|
-
const wav = r.data;
|
|
8329
|
+
let wav;
|
|
8330
|
+
try {
|
|
8331
|
+
wav = await renderTrack(trackIndex5, start, end, { dry: true });
|
|
8332
|
+
} catch (err) {
|
|
8333
|
+
return fail4(err instanceof Error ? err.message : String(err));
|
|
8334
|
+
}
|
|
8339
8335
|
try {
|
|
8340
8336
|
const relative2 = g.segments.map((s) => ({ start: s.start - start, end: s.end - start }));
|
|
8341
8337
|
if (model) {
|
|
@@ -9902,7 +9898,7 @@ function withVst3Lengths(header, state) {
|
|
|
9902
9898
|
}
|
|
9903
9899
|
|
|
9904
9900
|
// libs/extension-api/src/fx-state.ts
|
|
9905
|
-
import { randomUUID as
|
|
9901
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
9906
9902
|
import { readFile as readFile3, writeFile as writeFile3, unlink as unlink3 } from "node:fs/promises";
|
|
9907
9903
|
import { join as join10 } from "node:path";
|
|
9908
9904
|
var STATE_TIMEOUT_MS = 6e4;
|
|
@@ -9912,7 +9908,7 @@ var fail2 = (error7) => ({ ok: false, error: error7 });
|
|
|
9912
9908
|
function createFxStateClient(host) {
|
|
9913
9909
|
async function get(loc) {
|
|
9914
9910
|
const dir = await host.bridgeDir();
|
|
9915
|
-
const outFile = join10(dir, `fxstate_${
|
|
9911
|
+
const outFile = join10(dir, `fxstate_${randomUUID5()}.out`);
|
|
9916
9912
|
try {
|
|
9917
9913
|
const res = await host.bridge("get_fx_state", { trackIndex: loc.trackIndex, fxIndex: loc.fxIndex, outFile }, STATE_TIMEOUT_MS);
|
|
9918
9914
|
if (!res.success) return fail2(res.error ?? "get_fx_state failed");
|
|
@@ -9944,7 +9940,7 @@ function createFxStateClient(host) {
|
|
|
9944
9940
|
return fail2(err instanceof Error ? err.message : String(err));
|
|
9945
9941
|
}
|
|
9946
9942
|
const dir = await host.bridgeDir();
|
|
9947
|
-
const inFile = join10(dir, `fxstate_${
|
|
9943
|
+
const inFile = join10(dir, `fxstate_${randomUUID5()}.in`);
|
|
9948
9944
|
try {
|
|
9949
9945
|
await writeFile3(inFile, `${b64(fixed.header)}
|
|
9950
9946
|
${b64(fixed.state)}
|
package/package.json
CHANGED
|
@@ -22,6 +22,10 @@ M.MAX_BYTES = 1500 * 1024 * 1024
|
|
|
22
22
|
M.TTL = 600 -- seconds
|
|
23
23
|
M.MAX_TRACKS = 16
|
|
24
24
|
M.REAPER_BUNDLE = "com.cockos.reaper"
|
|
25
|
+
M.MAX_DRY_SECONDS = 120 -- a dry read blocks REAPER while it reads: longer ranges go to a real render
|
|
26
|
+
M.DRY_CHUNK = 220500 -- samples per channel read at a time (5 s at 44100), so memory stays small
|
|
27
|
+
M.JUNCTION_MARGIN = 0.5 -- s: an item end this close before the range still counts as inside it
|
|
28
|
+
M.JUNCTION_REACH = 5.5 -- s: how far after an item's end another item makes it a junction (a read is 5 s)
|
|
25
29
|
|
|
26
30
|
local epoch = 0 -- bumped by every command that writes: a parameter set through the API may not move REAPER's counter
|
|
27
31
|
local cache = {} -- oldest first: { key, path, bytes, at, stamp }
|
|
@@ -336,6 +340,181 @@ local function render_group(reaper, env, ctx, group)
|
|
|
336
340
|
return true
|
|
337
341
|
end
|
|
338
342
|
|
|
343
|
+
-- ---------------------------------------------------------------------------
|
|
344
|
+
-- Dry read
|
|
345
|
+
-- ---------------------------------------------------------------------------
|
|
346
|
+
-- A render opens REAPER's progress window, which takes focus and blocks the UI. For tools that only
|
|
347
|
+
-- need the track's own audio, the audio accessor reads it in-process instead: the items as they
|
|
348
|
+
-- play (stretch markers, rate and item edits applied) BEFORE track FX, pan and the fader, with no
|
|
349
|
+
-- window and no focus change. It cannot hear what the track does not carry itself (a folder's
|
|
350
|
+
-- children, audio arriving by send, a MIDI instrument), so those tracks still get a real render.
|
|
351
|
+
|
|
352
|
+
local function has_accessor(reaper)
|
|
353
|
+
return reaper.CreateTrackAudioAccessor and reaper.GetAudioAccessorSamples
|
|
354
|
+
and reaper.DestroyAudioAccessor and reaper.new_array and true or false
|
|
355
|
+
end
|
|
356
|
+
|
|
357
|
+
-- The track's playback offset in seconds (0 when it is off); what a render hears
|
|
358
|
+
local function play_offset_s(reaper, track)
|
|
359
|
+
local flag = reaper.GetMediaTrackInfo_Value(track, "I_PLAY_OFFSET_FLAG")
|
|
360
|
+
if flag & 1 ~= 0 then return 0 end
|
|
361
|
+
local v = reaper.GetMediaTrackInfo_Value(track, "D_PLAY_OFFSET")
|
|
362
|
+
if flag & 2 ~= 0 then
|
|
363
|
+
local srate = reaper.GetSetProjectInfo(0, "PROJECT_SRATE", 0, false)
|
|
364
|
+
if not srate or srate <= 0 then srate = M.SAMPLE_RATE end
|
|
365
|
+
return v / srate
|
|
366
|
+
end
|
|
367
|
+
return v
|
|
368
|
+
end
|
|
369
|
+
|
|
370
|
+
-- Take FX the accessor hears: REAPER's own (JS:, Cockos). A third-party take FX (Melodyne seen live,
|
|
371
|
+
-- REAPER 7.40) can make it return silence, so such an item is left to a real render.
|
|
372
|
+
local function take_fx_readable(reaper, take)
|
|
373
|
+
if not reaper.TakeFX_GetCount then return true end
|
|
374
|
+
for k = 0, reaper.TakeFX_GetCount(take) - 1 do
|
|
375
|
+
local _, name = reaper.TakeFX_GetFXName(take, k, "")
|
|
376
|
+
name = tostring(name or "")
|
|
377
|
+
if not (name:match("^JS:") or name:find("(Cockos)", 1, true)) then return false end
|
|
378
|
+
end
|
|
379
|
+
return true
|
|
380
|
+
end
|
|
381
|
+
|
|
382
|
+
-- Whether a dry read of this track over the range says what the track plays: audio items only,
|
|
383
|
+
-- not a folder parent, not the master, and a range short enough to read in one go
|
|
384
|
+
local function dry_eligible(reaper, t, start, stop)
|
|
385
|
+
if t.master or not has_accessor(reaper) then return false end
|
|
386
|
+
if stop - start > M.MAX_DRY_SECONDS then return false end
|
|
387
|
+
if reaper.GetMediaTrackInfo_Value(t.track, "I_FOLDERDEPTH") == 1 then return false end
|
|
388
|
+
-- audio arriving by send is not in the track's own items
|
|
389
|
+
if reaper.GetTrackNumSends and reaper.GetTrackNumSends(t.track, -1) > 0 then return false end
|
|
390
|
+
local off = play_offset_s(reaper, t.track)
|
|
391
|
+
if start - off < 0 then return false end -- the accessor has no audio before the project start
|
|
392
|
+
local audio = false
|
|
393
|
+
local spans = {}
|
|
394
|
+
for j = 0, reaper.CountTrackMediaItems(t.track) - 1 do
|
|
395
|
+
local item = reaper.GetTrackMediaItem(t.track, j)
|
|
396
|
+
local p = reaper.GetMediaItemInfo_Value(item, "D_POSITION") + off
|
|
397
|
+
local l = reaper.GetMediaItemInfo_Value(item, "D_LENGTH")
|
|
398
|
+
spans[#spans + 1] = { p, p + l }
|
|
399
|
+
if p < stop and p + l > start then
|
|
400
|
+
local take = reaper.GetActiveTake(item)
|
|
401
|
+
if take and not reaper.TakeIsMIDI(take) then audio = true else return false end
|
|
402
|
+
if not take_fx_readable(reaper, take) then return false end
|
|
403
|
+
end
|
|
404
|
+
end
|
|
405
|
+
if not audio then return false end
|
|
406
|
+
-- Where one item ends and another plays on right after it (a split, a crossfade, an overlap), the
|
|
407
|
+
-- accessor can run the first item's source on into a read that crosses its end, with different
|
|
408
|
+
-- audio each time (seen live in REAPER 7.40). Reads that start after the junction, or end before
|
|
409
|
+
-- it, are exact: only a range with such a junction in it is left to a real render.
|
|
410
|
+
for _, a in ipairs(spans) do
|
|
411
|
+
if a[2] > start - M.JUNCTION_MARGIN and a[2] < stop then
|
|
412
|
+
for _, b in ipairs(spans) do
|
|
413
|
+
if b ~= a and b[1] < a[2] + M.JUNCTION_REACH and b[2] > a[2] then return false end
|
|
414
|
+
end
|
|
415
|
+
end
|
|
416
|
+
end
|
|
417
|
+
return true
|
|
418
|
+
end
|
|
419
|
+
|
|
420
|
+
local function pcm24(x)
|
|
421
|
+
if x ~= x then return 0 end
|
|
422
|
+
local v = math.floor(x * 8388607 + 0.5)
|
|
423
|
+
if v > 8388607 then return 8388607 elseif v < -8388608 then return -8388608 end
|
|
424
|
+
return v
|
|
425
|
+
end
|
|
426
|
+
|
|
427
|
+
-- Interleaved float samples -> little-endian 24-bit PCM
|
|
428
|
+
local function pack24(samples, count)
|
|
429
|
+
local parts, i = {}, 1
|
|
430
|
+
while i <= count do
|
|
431
|
+
local m = math.min(1536, count - i + 1)
|
|
432
|
+
local ints = {}
|
|
433
|
+
for k = 1, m do ints[k] = pcm24(samples[i + k - 1]) end
|
|
434
|
+
parts[#parts + 1] = string.pack("<" .. string.rep("i3", m), table.unpack(ints))
|
|
435
|
+
i = i + m
|
|
436
|
+
end
|
|
437
|
+
return table.concat(parts)
|
|
438
|
+
end
|
|
439
|
+
|
|
440
|
+
-- The spans of project time the track's items cover (sorted, merged), moved by the playback offset
|
|
441
|
+
local function item_spans(reaper, track, off)
|
|
442
|
+
local spans = {}
|
|
443
|
+
for j = 0, reaper.CountTrackMediaItems(track) - 1 do
|
|
444
|
+
local item = reaper.GetTrackMediaItem(track, j)
|
|
445
|
+
local p = reaper.GetMediaItemInfo_Value(item, "D_POSITION") + off
|
|
446
|
+
local e = p + reaper.GetMediaItemInfo_Value(item, "D_LENGTH")
|
|
447
|
+
spans[#spans + 1] = { p, e }
|
|
448
|
+
end
|
|
449
|
+
table.sort(spans, function(a, b) return a[1] < b[1] end)
|
|
450
|
+
local merged = {}
|
|
451
|
+
for _, sp in ipairs(spans) do
|
|
452
|
+
local last = merged[#merged]
|
|
453
|
+
if last and sp[1] <= last[2] then
|
|
454
|
+
if sp[2] > last[2] then last[2] = sp[2] end
|
|
455
|
+
else
|
|
456
|
+
merged[#merged + 1] = { sp[1], sp[2] }
|
|
457
|
+
end
|
|
458
|
+
end
|
|
459
|
+
return merged
|
|
460
|
+
end
|
|
461
|
+
|
|
462
|
+
-- Silence the frames of an interleaved stereo chunk that no item covers (the accessor plays on
|
|
463
|
+
-- past the end of an item whose source goes on). t0 = project time of the first frame.
|
|
464
|
+
local function silence_outside(samples, frames, t0, sr, spans)
|
|
465
|
+
local function frame_at(t) return math.max(0, math.min(frames, math.floor((t - t0) * sr + 0.5))) end
|
|
466
|
+
local function zero(a, b) for k = a, b - 1 do samples[k * 2 + 1] = 0; samples[k * 2 + 2] = 0 end end
|
|
467
|
+
local pos = 0
|
|
468
|
+
for _, sp in ipairs(spans) do
|
|
469
|
+
local a, b = frame_at(sp[1]), frame_at(sp[2])
|
|
470
|
+
if a > pos then zero(pos, a) end
|
|
471
|
+
if b > pos then pos = b end
|
|
472
|
+
if pos >= frames then return end
|
|
473
|
+
end
|
|
474
|
+
zero(pos, frames)
|
|
475
|
+
end
|
|
476
|
+
|
|
477
|
+
-- Read [start, stop) of a track's own audio into a 24-bit stereo WAV at SAMPLE_RATE. true, or false + reason
|
|
478
|
+
-- (the half-written file is removed).
|
|
479
|
+
local function dry_read(reaper, env, path, track, start, stop)
|
|
480
|
+
local sr = M.SAMPLE_RATE
|
|
481
|
+
local total = math.floor((stop - start) * sr + 0.5)
|
|
482
|
+
local f = env.io.open(path, "wb")
|
|
483
|
+
if not f then return false, "cannot write " .. path end
|
|
484
|
+
local bytes = total * 6
|
|
485
|
+
f:write("RIFF", string.pack("<I4", 36 + bytes), "WAVEfmt ", string.pack("<I4I2I2I4I4I2I2", 16, 1, 2, sr, sr * 6, 6, 24),
|
|
486
|
+
"data", string.pack("<I4", bytes))
|
|
487
|
+
local acc = reaper.CreateTrackAudioAccessor(track)
|
|
488
|
+
-- What a render also hears: the track's playback offset and polarity switch
|
|
489
|
+
local off = play_offset_s(reaper, track)
|
|
490
|
+
local sign = reaper.GetMediaTrackInfo_Value(track, "B_PHASE") ~= 0 and -1 or 1
|
|
491
|
+
local spans = item_spans(reaper, track, off)
|
|
492
|
+
local ok, err = pcall(function()
|
|
493
|
+
local done = 0
|
|
494
|
+
while done < total do
|
|
495
|
+
local n = math.min(M.DRY_CHUNK, total - done)
|
|
496
|
+
local t0 = start + done / sr
|
|
497
|
+
local buf = reaper.new_array(n * 2)
|
|
498
|
+
local ret = reaper.GetAudioAccessorSamples(acc, sr, 2, t0 - off, n, buf)
|
|
499
|
+
if ret < 0 then error("audio accessor read failed (" .. tostring(ret) .. ")") end
|
|
500
|
+
if ret == 0 then
|
|
501
|
+
-- the accessor has no audio here: silence
|
|
502
|
+
f:write(string.rep("\0", n * 6))
|
|
503
|
+
else
|
|
504
|
+
local samples = buf.table(1, n * 2)
|
|
505
|
+
silence_outside(samples, n, t0, sr, spans)
|
|
506
|
+
if sign < 0 then for k = 1, n * 2 do samples[k] = -samples[k] end end
|
|
507
|
+
f:write(pack24(samples, n * 2))
|
|
508
|
+
end
|
|
509
|
+
done = done + n
|
|
510
|
+
end
|
|
511
|
+
end)
|
|
512
|
+
pcall(reaper.DestroyAudioAccessor, acc)
|
|
513
|
+
f:close()
|
|
514
|
+
if not ok then remove_file(env, path); return false, tostring(err) end
|
|
515
|
+
return true
|
|
516
|
+
end
|
|
517
|
+
|
|
339
518
|
local function playback_info(reaper, t)
|
|
340
519
|
local offset_ms, inverted = 0, false
|
|
341
520
|
if not t.master then
|
|
@@ -374,6 +553,12 @@ function M.render_tracks(reaper, params, e)
|
|
|
374
553
|
if not track then return nil, "Track " .. tostring(idx) .. " not found" end
|
|
375
554
|
targets[i] = { index = idx, track = track, master = master, name = track_name(reaper, track, idx, master) }
|
|
376
555
|
targets[i].key = string.format("%s|%.4f|%.4f", track_id(reaper, targets[i]), params.startTime, params.endTime)
|
|
556
|
+
-- dry: read the track's own audio instead of rendering it, where that says what the track plays.
|
|
557
|
+
-- A dry read is cached under its own key: it is not what a render of the track sounds like.
|
|
558
|
+
if params.dry == true and dry_eligible(reaper, targets[i], params.startTime, params.endTime) then
|
|
559
|
+
targets[i].planned_dry = true
|
|
560
|
+
targets[i].key = targets[i].key .. "|dry"
|
|
561
|
+
end
|
|
377
562
|
end
|
|
378
563
|
|
|
379
564
|
local stamp = stamp_of(reaper)
|
|
@@ -383,13 +568,39 @@ function M.render_tracks(reaper, params, e)
|
|
|
383
568
|
for _, t in ipairs(targets) do
|
|
384
569
|
local hit = stamp and params.fresh ~= true and lookup(env, t.key)
|
|
385
570
|
if hit then
|
|
386
|
-
t.path, t.cached = hit.path, true
|
|
571
|
+
t.path, t.cached, t.dry = hit.path, true, t.planned_dry == true
|
|
387
572
|
cached = cached + 1
|
|
388
573
|
else
|
|
389
574
|
missing[#missing + 1] = t
|
|
390
575
|
end
|
|
391
576
|
end
|
|
392
577
|
|
|
578
|
+
-- Dry reads first: no window, no focus change. A track whose read fails is rendered after all.
|
|
579
|
+
local dry_count = 0
|
|
580
|
+
if #missing > 0 and params.dry == true then
|
|
581
|
+
local rest = {}
|
|
582
|
+
local id = tostring(params.commandId or env.now()):gsub("-", ""):sub(1, 16)
|
|
583
|
+
for _, t in ipairs(missing) do
|
|
584
|
+
local done = false
|
|
585
|
+
if t.planned_dry then
|
|
586
|
+
passes = passes + 1
|
|
587
|
+
local path = temp_dir(reaper, env) .. M.PREFIX .. "dry_" .. id .. "_" .. passes .. ".wav"
|
|
588
|
+
local ok, res = pcall(dry_read, reaper, env, path, t.track, params.startTime, params.endTime)
|
|
589
|
+
if ok and res then
|
|
590
|
+
local info = file_info(env, path)
|
|
591
|
+
t.path, t.dry, done = path, true, true
|
|
592
|
+
dry_count = dry_count + 1
|
|
593
|
+
if stamp and info then store(env, { key = t.key, path = path, bytes = info.bytes, at = env.now(), stamp = stamp }) end
|
|
594
|
+
else
|
|
595
|
+
t.planned_dry = false
|
|
596
|
+
t.key = t.key:gsub("|dry$", "")
|
|
597
|
+
end
|
|
598
|
+
end
|
|
599
|
+
if not done then rest[#rest + 1] = t end
|
|
600
|
+
end
|
|
601
|
+
missing = rest
|
|
602
|
+
end
|
|
603
|
+
|
|
393
604
|
if #missing > 0 then
|
|
394
605
|
local ctx = {
|
|
395
606
|
id = tostring(params.commandId or env.now()):gsub("-", ""):sub(1, 16),
|
|
@@ -471,11 +682,13 @@ function M.render_tracks(reaper, params, e)
|
|
|
471
682
|
playOffsetMs = offset_ms,
|
|
472
683
|
phaseInverted = inverted,
|
|
473
684
|
cached = t.cached == true,
|
|
685
|
+
-- true: the track's own audio before its FX, pan and fader (read, not rendered)
|
|
686
|
+
dry = t.dry == true,
|
|
474
687
|
-- The cache deletes its files itself: callers must leave them alone
|
|
475
688
|
cacheOwned = true,
|
|
476
689
|
}
|
|
477
690
|
end
|
|
478
|
-
return { tracks = out, rendered = #missing, cached = cached }
|
|
691
|
+
return { tracks = out, rendered = #missing, cached = cached, dryRead = dry_count }
|
|
479
692
|
end
|
|
480
693
|
|
|
481
694
|
--- One track: the shape render_track_to_wav has always returned
|