@mthines/reaper-mcp 0.93.1 → 0.93.2

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.
@@ -25,8 +25,29 @@ The ear decides in the end. These steps find the problems the agent can measure
25
25
  1. **Keep the originals.** Copy the guide and each double to new tracks (`T ref`, `T edit` are fine as temporary names, delete them when done) and edit the copies. Never touch the user's items or solo state. Tracks created without a master send are silent in playback but still render, so turn the master send on for tracks the user will audition.
26
26
  2. **Pick the guide.** The louder, tighter take. A quiet backing vocal against a loud lead is a good test: onsets are found per source file, so level does not matter.
27
27
  3. **Dry run.** `align_audio_to_guide` with `dryRun: true`: read the offset before and after (avg and max ms) per double. Start with `strength` around 0.8 and a `maxShiftMs` under the typical phrase gap; raise it only when hits are missed.
28
- 4. **Apply** (same call without `dryRun`), then `verify_edit` against the kept copy with `timeScale: 1` for a pure alignment (stretch markers keep the length) and `expect: "changed"`. Judge it by the `discontinuity` check (no click) and the align call's after-offsets; the null residual is one number for the whole window and under `expect: "changed"` is only reported, so it does not say where audio moved.
29
- 5. **Listen** before accepting: play the aligned range with the guide. The tool checks for damage, not for taste.
28
+ A dry run that reports `replacedMarkers` above 1 means the double already had stretch markers (an earlier alignment or edit by the user): say so before applying, and keep the original on the copy.
29
+ 4. **Apply** (same call without `dryRun`), then run **Verify and iterate** below. Do not tell the user the alignment is done before that loop has finished; the align call's own after-offsets are what the tool planned, not what plays.
30
+ 5. **Listen** before accepting: play the aligned range with the guide. The tool checks for damage, not for taste. Name the spots that are still uncertain.
31
+
32
+ ## Verify and iterate (always, without being asked)
33
+
34
+ The align call plans from the items' source files. What the user hears is the rendered track, so measure that.
35
+
36
+ 1. **Damage check.** `verify_edit` against the kept copy: `timeScale: 1`, `expect: "changed"`. The `discontinuity` check must be ok (no click or hard splice).
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
+ 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
+ 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.
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
+ 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
+ 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).
44
+ 7. **Report** the before and after (average and worst offset on the render, number of outliers), what was fixed, and what is still loose or unconfirmed, with times. Say plainly which numbers come from onset detection rather than a waveform measurement.
45
+
46
+ ## Undoing an alignment
47
+
48
+ - **Before aligning, save the markers:** `snapshot_save { name: "before-align", trackIndices: [<guide track>, <double track>], stretchMarkers: true }`. It keeps the stretch markers of every audio item on those tracks, apart from the track chunk, and `snapshot_restore` puts them back on the same items (found by GUID, else by track, position and length). The reply says how many items it restored, left alone or could not find. Scope it with `trackIndices` in a big project.
49
+ - A scoped snapshot (`trackIndices`, which turns on `fullChunk`) stores each track's whole state chunk, items included, so restoring it also reverts every item edit made since, on tracks REAPER accepts the chunk for. Pass `fullChunk: false` with `stretchMarkers: true` to bring back only the markers. A snapshot without either holds no items, so it cannot undo an alignment. `undo_project` does, one undo point per `align_audio_to_guide` call, as long as nothing was written after it.
50
+ - A `fullChunk` snapshot of the tracks was refused (`SetTrackStateChunk failed`) on tracks whose items carry Melodyne (ARA) take FX; the cause is not confirmed. The restore warns, leaves that track unchanged and still restores the saved stretch markers. For such tracks pass `fullChunk: false` when only the markers matter.
30
51
 
31
52
  ## Stretching a vocal: what the checks mean
32
53
 
@@ -52,8 +52,12 @@ decide what to do. Explain mode is never on otherwise.
52
52
  an EQ on the wrong tracks). `list_tracks` (filtered by `parent`) or
53
53
  `get_track_lanes` right before each batch, and target by name where it is
54
54
  unique. Item indexes also change after every move, import or delete.
55
- 2. **Snapshots do not store items.** `snapshot_save` keeps faders and FX
56
- parameters, so it cannot undo a MIDI or arrangement edit. Before changing
55
+ 2. **Do not count on a snapshot to undo item edits.** A plain snapshot keeps faders and FX
56
+ parameters only. A scoped one (`trackIndices`) also stores each track's whole chunk, items
57
+ included, but REAPER refuses some chunks (tracks whose items carry Melodyne), and a restore
58
+ then reverts every item edit since. For stretch markers alone use `snapshot_save` with
59
+ `stretchMarkers: true` (and `fullChunk: false` to bring back only those). It cannot undo
60
+ a MIDI or arrangement edit. Before changing
57
61
  items, keep the original as a **take** of the item it replaces (see "Keeping
58
62
  the original" below), or as the A lane of a lane pair. **Never mute an
59
63
  original and leave it under or beside the new item**: overlapping muted items
@@ -277,13 +281,25 @@ use `knowledge/workflows/vocal-alignment.md`; load it first. In short:
277
281
  untouched) and delete them when the user is done.
278
282
  2. `align_audio_to_guide` with `dryRun` first, then apply; it reads the items'
279
283
  source files, so take FX such as Melodyne are not heard.
280
- 3. Check the result with `verify_edit` (`timeScale` = the playback rate,
281
- `expect: "changed"` for a stretch), then **tell the user which edits to
282
- listen to**. A plain speed change (rates outside about 0.97x-1.03x) is reported as info (pitch follows speed);
284
+ 3. **Verify and iterate before you say it is done; the user should never have to
285
+ ask.** Run the loop in the workflow's "Verify and iterate": `verify_edit`
286
+ against the kept copy (`timeScale` = the playback rate, `expect: "changed"`
287
+ for a stretch), then pair the hits of the rendered guide and double
288
+ (`detect_transients` on both tracks) and list every pair beyond about 20 ms.
289
+ Fix confirmed outliers one hit at a time with `edit_stretch_markers`,
290
+ re-measure, at most 3 rounds. Do not judge a lead against a backing with
291
+ `measure_track_alignment` (too little correlation). Then **tell the user
292
+ which edits to listen to**. A plain speed change (rates outside about 0.97x-1.03x) is reported as info (pitch follows speed);
283
293
  a pitch-kept slow-down below 0.9x gets stretch artifacts that only the
284
294
  dropout check and the user's ear catch. A pass is evidence, not a verdict.
285
295
  4. Put each copied item straight at its final position; batch-moving items on a
286
296
  track re-sorts their indexes.
297
+ 5. A dry run that reports `replacedMarkers` above 1 means the double already has
298
+ stretch markers: say so before applying. Before applying, `snapshot_save` with
299
+ `stretchMarkers: true` and `trackIndices` of the guide and double tracks: it keeps
300
+ their stretch markers, which `snapshot_restore` puts back (a track-chunk restore
301
+ fails on tracks with Melodyne take FX; the markers still come back). `undo_project`
302
+ works only while nothing was written after.
287
303
 
288
304
  ## Workflow
289
305
 
package/main.js CHANGED
@@ -2212,17 +2212,18 @@ import { z as z10 } from "zod/v4";
2212
2212
  function registerSnapshotTools(server) {
2213
2213
  server.tool(
2214
2214
  "snapshot_save",
2215
- "Save the current mixer state as a named snapshot. Stored in .reaper-mcp/snapshots/ alongside the project file (falls back to global bridge dir for unsaved projects). By default captures ALL tracks' volumes, pans, mutes, solos, FX bypass/offline states, full FX parameter values, preset names, track names/colors, and send levels. Pass trackIndices to scope the snapshot to specific tracks (e.g. just the master bus for an A/B that never touches other tracks). Pass fullChunk (or rely on its default-on when scoped) to capture exact track state chunks, which faithfully reproduce each plugin's internal state on restore \u2014 including plugins whose tone is driven by internal snapshots (e.g. Helix Native) that parameter-value capture cannot reproduce. Response includes storageLocation, scoped, fullChunk, and tracksCaptured.",
2215
+ "Save the current mixer state as a named snapshot. Stored in .reaper-mcp/snapshots/ alongside the project file (falls back to global bridge dir for unsaved projects). By default captures ALL tracks' volumes, pans, mutes, solos, FX bypass/offline states, full FX parameter values, preset names, track names/colors, and send levels. Pass trackIndices to scope the snapshot to specific tracks (e.g. just the master bus for an A/B that never touches other tracks). Pass fullChunk (or rely on its default-on when scoped) to capture exact track state chunks, which faithfully reproduce each plugin's internal state on restore \u2014 including plugins whose tone is driven by internal snapshots (e.g. Helix Native) that parameter-value capture cannot reproduce. Pass stretchMarkers to also keep the stretch markers of every audio item on the captured tracks (an alignment or a stretch edit): they are stored on their own, so they come back even where REAPER refuses to apply a track chunk (seen on tracks whose items carry Melodyne take FX). A fullChunk snapshot also holds each track's items (the whole chunk comes back on restore); without fullChunk a snapshot holds no items, only the stretch markers when asked for. Response includes storageLocation, scoped, fullChunk, tracksCaptured, and stretchMarkerItems.",
2216
2216
  {
2217
2217
  name: z10.string().min(1).describe('Unique snapshot name (e.g. "before-compression", "v1-mix")'),
2218
2218
  description: z10.string().optional().describe("Optional human-readable description"),
2219
2219
  includeFxParams: z10.boolean().optional().default(true).describe("Include FX parameter values in snapshot (default true). Only applies to non-chunk capture."),
2220
2220
  maxParamsPerFx: z10.coerce.number().int().min(1).max(2e3).optional().default(500).describe("Max parameters to capture per FX plugin (default 500). Only applies to non-chunk capture."),
2221
2221
  trackIndices: z10.array(z10.coerce.number().int().min(0)).optional().describe("Restrict the snapshot to these 0-based track indices. Omit to capture all tracks. Restoring a scoped snapshot only affects the listed tracks."),
2222
- fullChunk: z10.boolean().optional().describe("Capture exact track state chunks (complete FX internal state, e.g. Helix Native snapshots) instead of parameter values. Defaults to true when trackIndices is set, false otherwise (whole-project chunk snapshots are large).")
2222
+ fullChunk: z10.boolean().optional().describe("Capture exact track state chunks (complete FX internal state, e.g. Helix Native snapshots) instead of parameter values. Defaults to true when trackIndices is set, false otherwise (whole-project chunk snapshots are large)."),
2223
+ stretchMarkers: z10.boolean().optional().describe("Also keep the stretch markers of every audio item on the captured tracks (default false). Restoring puts them back on the same items (found by GUID, else by track, position and length). Up to 5000 audio items: scope with trackIndices for a big project.")
2223
2224
  },
2224
- async ({ name, description, includeFxParams, maxParamsPerFx, trackIndices, fullChunk }) => {
2225
- const res = await sendCommand("snapshot_save", { name, description, includeFxParams, maxParamsPerFx, trackIndices, fullChunk });
2225
+ async ({ name, description, includeFxParams, maxParamsPerFx, trackIndices, fullChunk, stretchMarkers }) => {
2226
+ const res = await sendCommand("snapshot_save", { name, description, includeFxParams, maxParamsPerFx, trackIndices, fullChunk, stretchMarkers });
2226
2227
  if (!res.success) {
2227
2228
  return { content: [{ type: "text", text: `Error: ${res.error}` }], isError: true };
2228
2229
  }
@@ -2231,14 +2232,15 @@ function registerSnapshotTools(server) {
2231
2232
  );
2232
2233
  server.tool(
2233
2234
  "snapshot_restore",
2234
- "Restore a previously saved mixer snapshot by name. Reads from .reaper-mcp/snapshots/ alongside the project file (falls back to global bridge dir for unsaved projects). For chunk-based snapshots (saved with fullChunk), restores each captured track exactly via its state chunk \u2014 reproducing complete FX internal state (incl. plugin internal snapshots like Helix Native) and affecting only the tracks the snapshot captured. For parameter-based snapshots, restores volumes, pans, mutes, solos, FX bypass states, and FX parameters (parameters only when the plugin name matches, to avoid applying wrong values).",
2235
+ "Restore a previously saved mixer snapshot by name. Reads from .reaper-mcp/snapshots/ alongside the project file (falls back to global bridge dir for unsaved projects). For chunk-based snapshots (saved with fullChunk), restores each captured track exactly via its state chunk \u2014 reproducing complete FX internal state (incl. plugin internal snapshots like Helix Native) and affecting only the tracks the snapshot captured. For parameter-based snapshots, restores volumes, pans, mutes, solos, FX bypass states, and FX parameters (parameters only when the plugin name matches, to avoid applying wrong values). Stretch markers saved with the snapshot are put back on their items afterwards, also when a track chunk could not be applied (the reply field stretchMarkers counts restored, unchanged and missing items).",
2235
2236
  {
2236
2237
  name: z10.string().min(1).describe("Name of the snapshot to restore"),
2237
2238
  restoreTrackMeta: z10.boolean().optional().default(false).describe("Also restore track names and colors (default false)"),
2238
- restoreSendLevels: z10.boolean().optional().default(true).describe("Restore send volume/pan/mute for existing sends (default true)")
2239
+ restoreSendLevels: z10.boolean().optional().default(true).describe("Restore send volume/pan/mute for existing sends (default true)"),
2240
+ restoreStretchMarkers: z10.boolean().optional().default(true).describe("Put back the stretch markers saved with the snapshot (default true; only snapshots saved with stretchMarkers hold any)")
2239
2241
  },
2240
- async ({ name, restoreTrackMeta, restoreSendLevels }) => {
2241
- const res = await sendCommand("snapshot_restore", { name, restoreTrackMeta, restoreSendLevels });
2242
+ async ({ name, restoreTrackMeta, restoreSendLevels, restoreStretchMarkers }) => {
2243
+ const res = await sendCommand("snapshot_restore", { name, restoreTrackMeta, restoreSendLevels, restoreStretchMarkers });
2242
2244
  if (!res.success) {
2243
2245
  return { content: [{ type: "text", text: `Error: ${res.error}` }], isError: true };
2244
2246
  }
@@ -3083,6 +3085,21 @@ function registerSelectionTools(server) {
3083
3085
  return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
3084
3086
  }
3085
3087
  );
3088
+ server.tool(
3089
+ "get_selected_items",
3090
+ 'Get the media items selected right now, as {trackIndex, itemIndex} (the indexes list_media_items and the item tools use) with the track name, position and length in seconds, and mute. Use it when the user says "the selected items", instead of guessing which tracks they mean. Paged: returns {total, hasMore, items}; pass offset to read on.',
3091
+ {
3092
+ offset: z15.coerce.number().int().min(0).optional().default(0).describe("Selected items to skip"),
3093
+ limit: z15.coerce.number().int().min(1).max(1e3).optional().default(200).describe("Most items to return")
3094
+ },
3095
+ async ({ offset, limit }) => {
3096
+ const res = await sendCommand("get_selected_items", { offset, limit });
3097
+ if (!res.success) {
3098
+ return { content: [{ type: "text", text: `Error: ${res.error}` }], isError: true };
3099
+ }
3100
+ return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
3101
+ }
3102
+ );
3086
3103
  server.tool(
3087
3104
  "set_selected_items",
3088
3105
  "Select media items by track and item index (as list_media_items reports them) \u2014 usually before run_action. Every item is resolved first: a missing one changes nothing. Returns the selection afterwards.",
@@ -4319,7 +4336,7 @@ var TOOL_CATEGORIES = {
4319
4336
  selection: {
4320
4337
  name: "selection",
4321
4338
  description: "Selection and navigation: get/set selected tracks and items, get/set time selection range",
4322
- tools: ["get_selected_tracks", "set_selected_tracks", "set_selected_items", "get_time_selection", "set_time_selection"]
4339
+ tools: ["get_selected_tracks", "set_selected_tracks", "get_selected_items", "set_selected_items", "get_time_selection", "set_time_selection"]
4323
4340
  },
4324
4341
  recording: {
4325
4342
  name: "recording",
@@ -4533,8 +4550,8 @@ var PROFILES = {
4533
4550
  minimal: ["project", "tracks", "fx", "transport", "discovery", "selection"],
4534
4551
  /** Mixing and mastering: measure, set levels and FX, route, automate, snapshot, render. */
4535
4552
  mixing: ["project", "tracks", "fx", "fx_files", "transport", "discovery", "selection", "routing", "plan", "analysis", "snapshots", "envelopes", "actions", "knowledge", "recording"],
4536
- /** Writing and editing music and arrangements (no takes or actions). Adding categories or an extension, e.g. `mixing,composition`, can push a profile past 128. */
4537
- music: ["project", "tracks", "fx", "transport", "discovery", "selection", "midi", "media", "arrange", "markers", "tempo", "envelopes", "plan"],
4553
+ /** Writing and editing music and arrangements (no takes, actions or envelopes). Adding categories or an extension, e.g. `mixing,composition`, can push a profile past 128. */
4554
+ music: ["project", "tracks", "fx", "transport", "discovery", "selection", "midi", "media", "arrange", "markers", "tempo", "plan"],
4538
4555
  /** Inspect and measure; the tracks and project categories still hold a few writers, so this is not read-only. */
4539
4556
  analysis: ["project", "tracks", "transport", "discovery", "selection", "routing", "markers", "tempo", "analysis", "knowledge"]
4540
4557
  };
@@ -4908,6 +4925,7 @@ var MCP_TOOL_NAMES = [
4908
4925
  "process_items",
4909
4926
  // selection & navigation
4910
4927
  "get_selected_tracks",
4928
+ "get_selected_items",
4911
4929
  "get_time_selection",
4912
4930
  "set_time_selection",
4913
4931
  // markers & regions
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mthines/reaper-mcp",
3
- "version": "0.93.1",
3
+ "version": "0.93.2",
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",
@@ -371,5 +371,34 @@ function M.set_selected_items(api, items, mode)
371
371
  return { selected = selected }
372
372
  end
373
373
 
374
+ -- The items selected right now: where each sits (track and item index as list_media_items reports them),
375
+ -- its track's name, start, length and mute. Read-only.
376
+ function M.get_selected_items(api, offset, limit)
377
+ offset = math.max(0, math.floor(tonumber(offset) or 0))
378
+ limit = math.max(1, math.floor(tonumber(limit) or 200))
379
+ local items, total = {}, 0
380
+ for i = 0, api.CountTracks(0) - 1 do
381
+ local tr = api.GetTrack(0, i)
382
+ local _, track_name = api.GetTrackName(tr)
383
+ for j = 0, api.CountTrackMediaItems(tr) - 1 do
384
+ local it = api.GetTrackMediaItem(tr, j)
385
+ if api.IsMediaItemSelected(it) then
386
+ total = total + 1
387
+ if total > offset and #items < limit then
388
+ items[#items + 1] = {
389
+ trackIndex = i,
390
+ trackName = track_name,
391
+ itemIndex = j,
392
+ position = api.GetMediaItemInfo_Value(it, "D_POSITION"),
393
+ length = api.GetMediaItemInfo_Value(it, "D_LENGTH"),
394
+ muted = api.GetMediaItemInfo_Value(it, "B_MUTE") == 1,
395
+ }
396
+ end
397
+ end
398
+ end
399
+ end
400
+ return { total = total, offset = offset, hasMore = offset + #items < total, items = items }
401
+ end
402
+
374
403
  M.section_id = section_id
375
404
  return M
@@ -1520,6 +1520,17 @@ function handlers.snapshot_save(params)
1520
1520
  trackIndices = params.trackIndices,
1521
1521
  fullChunk = params.fullChunk,
1522
1522
  })
1523
+ -- Stretch markers of the audio items on the captured tracks, kept apart from the track chunk (REAPER
1524
+ -- refuses to apply a chunk on tracks whose items carry Melodyne take FX)
1525
+ local marker_items = 0
1526
+ if params.stretchMarkers == true then
1527
+ local captured = {}
1528
+ for _, t in ipairs(mixer_state.tracks) do captured[#captured + 1] = t.index end
1529
+ local entries, err = ext.mix.run("capture_stretch_markers", captured)
1530
+ if not entries then return nil, err end
1531
+ mixer_state.stretchMarkers = entries
1532
+ marker_items = #entries
1533
+ end
1523
1534
  -- Metadata first, mixerState last: a lister can read name/description/trackCount from the
1524
1535
  -- head of the file (mcp_snapshot_lib.lua's read_snapshot_meta reads only that prefix)
1525
1536
  local content = "{" .. table.concat({
@@ -1547,6 +1558,7 @@ function handlers.snapshot_save(params)
1547
1558
  scoped = mixer_state.scoped == true,
1548
1559
  fullChunk = mixer_state.fullChunk == true,
1549
1560
  tracksCaptured = #mixer_state.tracks,
1561
+ stretchMarkerItems = params.stretchMarkers == true and marker_items or nil,
1550
1562
  }
1551
1563
  end
1552
1564
 
@@ -1607,7 +1619,10 @@ function handlers.snapshot_restore(params)
1607
1619
  if reaper.SetTrackStateChunk(track, base64_decode(track_state.chunkB64), false) then
1608
1620
  restored = restored + 1
1609
1621
  else
1610
- warnings[#warnings + 1] = "Track " .. track_state.index .. ": SetTrackStateChunk failed"
1622
+ warnings[#warnings + 1] = "Track " .. track_state.index .. " '" .. tostring(track_state.name)
1623
+ .. "': REAPER refused the saved track state (SetTrackStateChunk failed), the track is unchanged"
1624
+ .. (state.stretchMarkers and params.restoreStretchMarkers ~= false and "; its stretch markers are restored separately" or
1625
+ "; tracks with Melodyne (ARA) take FX can do this: save with stretchMarkers for their item edits")
1611
1626
  end
1612
1627
  else
1613
1628
  -- Basic mixer state (all versions)
@@ -1685,6 +1700,25 @@ function handlers.snapshot_restore(params)
1685
1700
  end
1686
1701
  end
1687
1702
 
1703
+ -- Stretch markers saved with the snapshot (snapshot_save stretchMarkers): put back after the tracks,
1704
+ -- also on tracks whose chunk could not be applied
1705
+ local marker_result
1706
+ if params.restoreStretchMarkers ~= false and state.stretchMarkers then
1707
+ local entries = state.stretchMarkers
1708
+ if type(entries) == "string" then entries = json_decode_array(entries) end
1709
+ if type(entries) == "table" then
1710
+ local res, err = ext.mix.run("restore_stretch_markers", entries)
1711
+ if res then
1712
+ marker_result = res
1713
+ if res.missing > 0 then
1714
+ warnings[#warnings + 1] = res.missing .. " saved item(s) no longer exist, their stretch markers were not restored"
1715
+ end
1716
+ else
1717
+ warnings[#warnings + 1] = "Stretch markers not restored: " .. tostring(err)
1718
+ end
1719
+ end
1720
+ end
1721
+
1688
1722
  reaper.Undo_EndBlock("MCP: Restore snapshot '" .. name .. "'", -1)
1689
1723
 
1690
1724
  reaper.TrackList_AdjustWindows(false)
@@ -1696,6 +1730,7 @@ function handlers.snapshot_restore(params)
1696
1730
  timestamp = snapshot.timestamp,
1697
1731
  tracksRestored = restored,
1698
1732
  version = version,
1733
+ stretchMarkers = marker_result,
1699
1734
  }
1700
1735
  if #warnings > 0 then result.warnings = warnings end
1701
1736
  return result
@@ -3529,6 +3564,12 @@ function handlers.set_selected_tracks(params)
3529
3564
  end)
3530
3565
  end
3531
3566
 
3567
+ function handlers.get_selected_items(params)
3568
+ return with_actions_lib(function()
3569
+ return actions_lib.get_selected_items(reaper, params.offset, params.limit)
3570
+ end)
3571
+ end
3572
+
3532
3573
  function handlers.set_selected_items(params)
3533
3574
  return with_actions_lib(function()
3534
3575
  local items, err = decode_list(params.items, "items")
@@ -787,6 +787,135 @@ local function write_markers(api, t, list)
787
787
  end
788
788
  end
789
789
 
790
+ -- Snapshot support: the stretch markers of every audio item on some tracks, and putting them back.
791
+ -- A track chunk can hold them too, but REAPER refused to apply a chunk (SetTrackStateChunk) on tracks
792
+ -- whose items carry Melodyne (ARA) take FX, so a snapshot keeps the markers on their own.
793
+ M.MAX_SNAPSHOT_ITEMS = 5000
794
+
795
+ local function num_text(n) return string.format("%.10g", n) end
796
+
797
+ local function item_guid(api, it)
798
+ if not api.GetSetMediaItemInfo_String then return "" end
799
+ local ok, guid = api.GetSetMediaItemInfo_String(it, "GUID", "", false)
800
+ if ok and type(guid) == "string" then return guid end
801
+ return ""
802
+ end
803
+
804
+ -- One entry per audio item (the active take): {trackIndex, guid, position, length, markers}, with the
805
+ -- markers as one flat string "pos,src,slope;pos,src,slope" in raw take time (what get_stretch_markers
806
+ -- lists). A flat string, because the bridge's JSON fallback cannot read nested arrays back. An item
807
+ -- with no markers is kept too (markers = ""), so a restore clears markers added since.
808
+ -- `trackIndices`: 0-based list, nil = every track.
809
+ function M.capture_stretch_markers(api, trackIndices)
810
+ local list = trackIndices
811
+ if not list then
812
+ list = {}
813
+ for i = 0, api.CountTracks(0) - 1 do list[#list + 1] = i end
814
+ end
815
+ local entries = {}
816
+ for _, ti in ipairs(list) do
817
+ local tr = api.GetTrack(0, ti)
818
+ if tr then
819
+ for ii = 0, api.CountTrackMediaItems(tr) - 1 do
820
+ local it = api.GetTrackMediaItem(tr, ii)
821
+ local take = it and api.GetActiveTake(it)
822
+ if take and not api.TakeIsMIDI(take) then
823
+ if #entries >= M.MAX_SNAPSHOT_ITEMS then
824
+ return nil, "more than " .. M.MAX_SNAPSHOT_ITEMS .. " audio items: pass trackIndices to scope the snapshot"
825
+ end
826
+ local parts = {}
827
+ for m = 0, api.GetTakeNumStretchMarkers(take) - 1 do
828
+ local _, pos, src = api.GetTakeStretchMarker(take, m)
829
+ local slope = api.GetTakeStretchMarkerSlope and api.GetTakeStretchMarkerSlope(take, m) or 0
830
+ parts[#parts + 1] = num_text(pos) .. "," .. num_text(src) .. "," .. num_text(slope)
831
+ end
832
+ entries[#entries + 1] = {
833
+ trackIndex = ti, guid = item_guid(api, it),
834
+ position = api.GetMediaItemInfo_Value(it, "D_POSITION"),
835
+ length = api.GetMediaItemInfo_Value(it, "D_LENGTH"),
836
+ markers = table.concat(parts, ";"),
837
+ }
838
+ end
839
+ end
840
+ end
841
+ end
842
+ return entries
843
+ end
844
+
845
+ local function parse_marker_text(text)
846
+ local list = {}
847
+ for pos, src, slope in tostring(text or ""):gmatch("([^,;]+),([^,;]+),([^,;]+)") do
848
+ local p, s, sl = tonumber(pos), tonumber(src), tonumber(slope)
849
+ if p and s then list[#list + 1] = { pos = p, src = s, slope = sl or 0 } end
850
+ end
851
+ return list
852
+ end
853
+
854
+ local function same_markers(api, take, list)
855
+ if api.GetTakeNumStretchMarkers(take) ~= #list then return false end
856
+ for i, m in ipairs(list) do
857
+ local _, pos, src = api.GetTakeStretchMarker(take, i - 1)
858
+ local slope = api.GetTakeStretchMarkerSlope and api.GetTakeStretchMarkerSlope(take, i - 1) or 0
859
+ if math.abs(pos - m.pos) > 1e-6 or math.abs(src - m.src) > 1e-6 or math.abs(slope - m.slope) > 1e-6 then
860
+ return false
861
+ end
862
+ end
863
+ return true
864
+ end
865
+
866
+ -- Puts the saved markers back on the items they were saved from: found by GUID, else by track, position
867
+ -- and length (an item split or re-created since has a new GUID). Items already as saved are left alone;
868
+ -- an item that is gone is counted in `missing`. No undo block of its own: the caller opens one.
869
+ function M.restore_stretch_markers(api, entries)
870
+ local by_guid, on_track = {}, {}
871
+ for ti = 0, api.CountTracks(0) - 1 do
872
+ local tr = api.GetTrack(0, ti)
873
+ local items = {}
874
+ for ii = 0, api.CountTrackMediaItems(tr) - 1 do
875
+ local it = api.GetTrackMediaItem(tr, ii)
876
+ local take = it and api.GetActiveTake(it)
877
+ if take and not api.TakeIsMIDI(take) then
878
+ local rec = { it = it, take = take }
879
+ items[#items + 1] = rec
880
+ local guid = item_guid(api, it)
881
+ if guid ~= "" then by_guid[guid] = rec end
882
+ end
883
+ end
884
+ on_track[ti] = items
885
+ end
886
+
887
+ local used = {}
888
+ local function find(e)
889
+ local rec = e.guid and e.guid ~= "" and by_guid[e.guid]
890
+ if rec and not used[rec] then return rec end
891
+ for _, r in ipairs(on_track[tonumber(e.trackIndex)] or {}) do
892
+ if not used[r] and math.abs(api.GetMediaItemInfo_Value(r.it, "D_POSITION") - tonumber(e.position)) < 0.001
893
+ and math.abs(api.GetMediaItemInfo_Value(r.it, "D_LENGTH") - tonumber(e.length)) < 0.001 then
894
+ return r
895
+ end
896
+ end
897
+ end
898
+
899
+ local restored, unchanged, missing = 0, 0, 0
900
+ for _, e in ipairs(entries or {}) do
901
+ local rec = find(e)
902
+ if not rec then
903
+ missing = missing + 1
904
+ else
905
+ used[rec] = true
906
+ local list = parse_marker_text(e.markers)
907
+ if same_markers(api, rec.take, list) then
908
+ unchanged = unchanged + 1
909
+ else
910
+ write_markers(api, { take = rec.take }, list)
911
+ api.UpdateItemInProject(rec.it)
912
+ restored = restored + 1
913
+ end
914
+ end
915
+ end
916
+ return { restored = restored, unchanged = unchanged, missing = missing }
917
+ end
918
+
790
919
  -- Edits existing markers by index: {index, position?, sourcePosition?, slope?}. Positions are item
791
920
  -- seconds. Every edit is checked against the whole list first (an edit that folds time, i.e. puts a
792
921
  -- marker out of order in position or source, refuses the call); markers are then rewritten in one undo point.