@nodetool-ai/timeline 0.8.19 → 0.8.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (321) hide show
  1. package/dist/.nodetool-build-stamp +1 -1
  2. package/dist/autoCrossfade.d.ts +30 -0
  3. package/dist/autoCrossfade.d.ts.map +1 -0
  4. package/dist/autoCrossfade.js +130 -0
  5. package/dist/autoCrossfade.js.map +1 -0
  6. package/dist/automation.d.ts +32 -1
  7. package/dist/automation.d.ts.map +1 -1
  8. package/dist/automation.js +78 -1
  9. package/dist/automation.js.map +1 -1
  10. package/dist/automationRanges.d.ts +375 -0
  11. package/dist/automationRanges.d.ts.map +1 -0
  12. package/dist/automationRanges.js +375 -0
  13. package/dist/automationRanges.js.map +1 -0
  14. package/dist/clipAudio.d.ts +3 -1
  15. package/dist/clipAudio.d.ts.map +1 -1
  16. package/dist/clipAudio.js.map +1 -1
  17. package/dist/clipLoop.d.ts +67 -0
  18. package/dist/clipLoop.d.ts.map +1 -0
  19. package/dist/clipLoop.js +339 -0
  20. package/dist/clipLoop.js.map +1 -0
  21. package/dist/clipSpeed.d.ts.map +1 -1
  22. package/dist/clipSpeed.js +7 -0
  23. package/dist/clipSpeed.js.map +1 -1
  24. package/dist/defaults.d.ts.map +1 -1
  25. package/dist/defaults.js +9 -0
  26. package/dist/defaults.js.map +1 -1
  27. package/dist/dropResolve.d.ts.map +1 -1
  28. package/dist/dropResolve.js +56 -17
  29. package/dist/dropResolve.js.map +1 -1
  30. package/dist/harmony/chordChart.d.ts +25 -0
  31. package/dist/harmony/chordChart.d.ts.map +1 -0
  32. package/dist/harmony/chordChart.js +99 -0
  33. package/dist/harmony/chordChart.js.map +1 -0
  34. package/dist/harmony/chordRange.d.ts +9 -0
  35. package/dist/harmony/chordRange.d.ts.map +1 -0
  36. package/dist/harmony/chordRange.js +32 -0
  37. package/dist/harmony/chordRange.js.map +1 -0
  38. package/dist/harmony/chordSymbols.d.ts +28 -0
  39. package/dist/harmony/chordSymbols.d.ts.map +1 -0
  40. package/dist/harmony/chordSymbols.js +147 -0
  41. package/dist/harmony/chordSymbols.js.map +1 -0
  42. package/dist/harmony/chordTrack.d.ts +13 -0
  43. package/dist/harmony/chordTrack.d.ts.map +1 -0
  44. package/dist/harmony/chordTrack.js +11 -0
  45. package/dist/harmony/chordTrack.js.map +1 -0
  46. package/dist/harmony/detect.d.ts +35 -0
  47. package/dist/harmony/detect.d.ts.map +1 -0
  48. package/dist/harmony/detect.js +138 -0
  49. package/dist/harmony/detect.js.map +1 -0
  50. package/dist/harmony/detectAudio.d.ts +62 -0
  51. package/dist/harmony/detectAudio.d.ts.map +1 -0
  52. package/dist/harmony/detectAudio.js +226 -0
  53. package/dist/harmony/detectAudio.js.map +1 -0
  54. package/dist/harmony/expand.d.ts +7 -12
  55. package/dist/harmony/expand.d.ts.map +1 -1
  56. package/dist/harmony/expand.js +63 -11
  57. package/dist/harmony/expand.js.map +1 -1
  58. package/dist/harmony/index.d.ts +7 -0
  59. package/dist/harmony/index.d.ts.map +1 -1
  60. package/dist/harmony/index.js +7 -0
  61. package/dist/harmony/index.js.map +1 -1
  62. package/dist/harmony/progressionLibrary.d.ts +33 -0
  63. package/dist/harmony/progressionLibrary.d.ts.map +1 -0
  64. package/dist/harmony/progressionLibrary.js +71 -0
  65. package/dist/harmony/progressionLibrary.js.map +1 -0
  66. package/dist/harmony/summary.d.ts +4 -0
  67. package/dist/harmony/summary.d.ts.map +1 -0
  68. package/dist/harmony/summary.js +22 -0
  69. package/dist/harmony/summary.js.map +1 -0
  70. package/dist/index.d.ts +3 -0
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +3 -0
  73. package/dist/index.js.map +1 -1
  74. package/dist/interchange.d.ts.map +1 -1
  75. package/dist/interchange.js +3 -0
  76. package/dist/interchange.js.map +1 -1
  77. package/dist/loopWindow.d.ts +17 -0
  78. package/dist/loopWindow.d.ts.map +1 -0
  79. package/dist/loopWindow.js +34 -0
  80. package/dist/loopWindow.js.map +1 -0
  81. package/dist/midi/cacheKey.d.ts +11 -2
  82. package/dist/midi/cacheKey.d.ts.map +1 -1
  83. package/dist/midi/cacheKey.js +69 -9
  84. package/dist/midi/cacheKey.js.map +1 -1
  85. package/dist/midi/controllerEdit.d.ts +35 -0
  86. package/dist/midi/controllerEdit.d.ts.map +1 -0
  87. package/dist/midi/controllerEdit.js +94 -0
  88. package/dist/midi/controllerEdit.js.map +1 -0
  89. package/dist/midi/controllerRange.d.ts +13 -0
  90. package/dist/midi/controllerRange.d.ts.map +1 -0
  91. package/dist/midi/controllerRange.js +13 -0
  92. package/dist/midi/controllerRange.js.map +1 -0
  93. package/dist/midi/controllers.d.ts +95 -0
  94. package/dist/midi/controllers.d.ts.map +1 -0
  95. package/dist/midi/controllers.js +421 -0
  96. package/dist/midi/controllers.js.map +1 -0
  97. package/dist/midi/curveCut.d.ts +17 -0
  98. package/dist/midi/curveCut.d.ts.map +1 -0
  99. package/dist/midi/curveCut.js +45 -0
  100. package/dist/midi/curveCut.js.map +1 -0
  101. package/dist/midi/edit.d.ts +13 -1
  102. package/dist/midi/edit.d.ts.map +1 -1
  103. package/dist/midi/edit.js +19 -3
  104. package/dist/midi/edit.js.map +1 -1
  105. package/dist/midi/engines/bl1.d.ts +10 -1
  106. package/dist/midi/engines/bl1.d.ts.map +1 -1
  107. package/dist/midi/engines/bl1.js +26 -6
  108. package/dist/midi/engines/bl1.js.map +1 -1
  109. package/dist/midi/engines/dr1.d.ts +11 -1
  110. package/dist/midi/engines/dr1.d.ts.map +1 -1
  111. package/dist/midi/engines/dr1.js +21 -3
  112. package/dist/midi/engines/dr1.js.map +1 -1
  113. package/dist/midi/engines/dsp.d.ts +1 -1
  114. package/dist/midi/engines/dsp.d.ts.map +1 -1
  115. package/dist/midi/engines/dsp.js +10 -2
  116. package/dist/midi/engines/dsp.js.map +1 -1
  117. package/dist/midi/engines/wt1.d.ts +10 -1
  118. package/dist/midi/engines/wt1.d.ts.map +1 -1
  119. package/dist/midi/engines/wt1.js +28 -5
  120. package/dist/midi/engines/wt1.js.map +1 -1
  121. package/dist/midi/events.d.ts +13 -4
  122. package/dist/midi/events.d.ts.map +1 -1
  123. package/dist/midi/events.js +33 -6
  124. package/dist/midi/events.js.map +1 -1
  125. package/dist/midi/expression.d.ts +25 -0
  126. package/dist/midi/expression.d.ts.map +1 -0
  127. package/dist/midi/expression.js +69 -0
  128. package/dist/midi/expression.js.map +1 -0
  129. package/dist/midi/index.d.ts +8 -0
  130. package/dist/midi/index.d.ts.map +1 -1
  131. package/dist/midi/index.js +8 -0
  132. package/dist/midi/index.js.map +1 -1
  133. package/dist/midi/instrument.d.ts.map +1 -1
  134. package/dist/midi/instrument.js +4 -0
  135. package/dist/midi/instrument.js.map +1 -1
  136. package/dist/midi/noteFunctions.d.ts +29 -0
  137. package/dist/midi/noteFunctions.d.ts.map +1 -0
  138. package/dist/midi/noteFunctions.js +213 -0
  139. package/dist/midi/noteFunctions.js.map +1 -0
  140. package/dist/midi/notes.d.ts +7 -1
  141. package/dist/midi/notes.d.ts.map +1 -1
  142. package/dist/midi/notes.js +43 -1
  143. package/dist/midi/notes.js.map +1 -1
  144. package/dist/midi/notesEdit.d.ts +13 -0
  145. package/dist/midi/notesEdit.d.ts.map +1 -1
  146. package/dist/midi/notesEdit.js +73 -2
  147. package/dist/midi/notesEdit.js.map +1 -1
  148. package/dist/midi/presets.d.ts +1 -1
  149. package/dist/midi/regionParams.d.ts +41 -0
  150. package/dist/midi/regionParams.d.ts.map +1 -0
  151. package/dist/midi/regionParams.js +164 -0
  152. package/dist/midi/regionParams.js.map +1 -0
  153. package/dist/midi/sampler.d.ts +2 -2
  154. package/dist/midi/sampler.d.ts.map +1 -1
  155. package/dist/midi/sampler.js +99 -21
  156. package/dist/midi/sampler.js.map +1 -1
  157. package/dist/midi/stepEditor.d.ts +50 -0
  158. package/dist/midi/stepEditor.d.ts.map +1 -0
  159. package/dist/midi/stepEditor.js +118 -0
  160. package/dist/midi/stepEditor.js.map +1 -0
  161. package/dist/midi/stepPattern.d.ts +173 -0
  162. package/dist/midi/stepPattern.d.ts.map +1 -0
  163. package/dist/midi/stepPattern.js +1390 -0
  164. package/dist/midi/stepPattern.js.map +1 -0
  165. package/dist/midi/stepPatternExpand.d.ts +149 -0
  166. package/dist/midi/stepPatternExpand.d.ts.map +1 -0
  167. package/dist/midi/stepPatternExpand.js +1068 -0
  168. package/dist/midi/stepPatternExpand.js.map +1 -0
  169. package/dist/midi/stepPatternLibrary.d.ts +65 -0
  170. package/dist/midi/stepPatternLibrary.d.ts.map +1 -0
  171. package/dist/midi/stepPatternLibrary.js +640 -0
  172. package/dist/midi/stepPatternLibrary.js.map +1 -0
  173. package/dist/midi/tempo.d.ts.map +1 -1
  174. package/dist/midi/tempo.js +3 -0
  175. package/dist/midi/tempo.js.map +1 -1
  176. package/dist/midi/voice.d.ts +51 -5
  177. package/dist/midi/voice.d.ts.map +1 -1
  178. package/dist/midi/voice.js +191 -21
  179. package/dist/midi/voice.js.map +1 -1
  180. package/dist/model3dCameraDescription.d.ts +11 -6
  181. package/dist/model3dCameraDescription.d.ts.map +1 -1
  182. package/dist/model3dCameraDescription.js +112 -30
  183. package/dist/model3dCameraDescription.js.map +1 -1
  184. package/dist/model3dReference.d.ts +25 -4
  185. package/dist/model3dReference.d.ts.map +1 -1
  186. package/dist/model3dReference.js +19 -6
  187. package/dist/model3dReference.js.map +1 -1
  188. package/dist/music/align.d.ts +111 -0
  189. package/dist/music/align.d.ts.map +1 -0
  190. package/dist/music/align.js +282 -0
  191. package/dist/music/align.js.map +1 -0
  192. package/dist/music/cut.d.ts +33 -0
  193. package/dist/music/cut.d.ts.map +1 -0
  194. package/dist/music/cut.js +50 -0
  195. package/dist/music/cut.js.map +1 -0
  196. package/dist/music/frames.d.ts +51 -0
  197. package/dist/music/frames.d.ts.map +1 -0
  198. package/dist/music/frames.js +110 -0
  199. package/dist/music/frames.js.map +1 -0
  200. package/dist/music/gain.d.ts +24 -0
  201. package/dist/music/gain.d.ts.map +1 -0
  202. package/dist/music/gain.js +38 -0
  203. package/dist/music/gain.js.map +1 -0
  204. package/dist/music/index.d.ts +9 -0
  205. package/dist/music/index.d.ts.map +1 -0
  206. package/dist/music/index.js +9 -0
  207. package/dist/music/index.js.map +1 -0
  208. package/dist/music/plan.d.ts +106 -0
  209. package/dist/music/plan.d.ts.map +1 -0
  210. package/dist/music/plan.js +304 -0
  211. package/dist/music/plan.js.map +1 -0
  212. package/dist/music/process.d.ts +9 -0
  213. package/dist/music/process.d.ts.map +1 -0
  214. package/dist/music/process.js +9 -0
  215. package/dist/music/process.js.map +1 -0
  216. package/dist/music/roles.d.ts +14 -0
  217. package/dist/music/roles.d.ts.map +1 -0
  218. package/dist/music/roles.js +30 -0
  219. package/dist/music/roles.js.map +1 -0
  220. package/dist/music/splice.d.ts +37 -0
  221. package/dist/music/splice.d.ts.map +1 -0
  222. package/dist/music/splice.js +67 -0
  223. package/dist/music/splice.js.map +1 -0
  224. package/dist/music/tempoRules.d.ts +41 -0
  225. package/dist/music/tempoRules.d.ts.map +1 -0
  226. package/dist/music/tempoRules.js +59 -0
  227. package/dist/music/tempoRules.js.map +1 -0
  228. package/dist/ops/apply.d.ts.map +1 -1
  229. package/dist/ops/apply.js +845 -232
  230. package/dist/ops/apply.js.map +1 -1
  231. package/dist/ops/automation.d.ts +6 -0
  232. package/dist/ops/automation.d.ts.map +1 -0
  233. package/dist/ops/automation.js +217 -0
  234. package/dist/ops/automation.js.map +1 -0
  235. package/dist/ops/barTime.d.ts +14 -0
  236. package/dist/ops/barTime.d.ts.map +1 -0
  237. package/dist/ops/barTime.js +33 -0
  238. package/dist/ops/barTime.js.map +1 -0
  239. package/dist/ops/chords.d.ts +43 -0
  240. package/dist/ops/chords.d.ts.map +1 -0
  241. package/dist/ops/chords.js +691 -0
  242. package/dist/ops/chords.js.map +1 -0
  243. package/dist/ops/groupBake.d.ts +24 -0
  244. package/dist/ops/groupBake.d.ts.map +1 -0
  245. package/dist/ops/groupBake.js +81 -0
  246. package/dist/ops/groupBake.js.map +1 -0
  247. package/dist/ops/index.d.ts +7 -0
  248. package/dist/ops/index.d.ts.map +1 -1
  249. package/dist/ops/index.js +5 -0
  250. package/dist/ops/index.js.map +1 -1
  251. package/dist/ops/join.d.ts +20 -0
  252. package/dist/ops/join.d.ts.map +1 -0
  253. package/dist/ops/join.js +265 -0
  254. package/dist/ops/join.js.map +1 -0
  255. package/dist/ops/loop.d.ts +29 -0
  256. package/dist/ops/loop.d.ts.map +1 -0
  257. package/dist/ops/loop.js +107 -0
  258. package/dist/ops/loop.js.map +1 -0
  259. package/dist/ops/midiMix.d.ts +41 -0
  260. package/dist/ops/midiMix.d.ts.map +1 -0
  261. package/dist/ops/midiMix.js +522 -0
  262. package/dist/ops/midiMix.js.map +1 -0
  263. package/dist/ops/op.d.ts +61 -11
  264. package/dist/ops/op.d.ts.map +1 -1
  265. package/dist/ops/op.js +60 -1
  266. package/dist/ops/op.js.map +1 -1
  267. package/dist/ops/parse.d.ts.map +1 -1
  268. package/dist/ops/parse.js +308 -4
  269. package/dist/ops/parse.js.map +1 -1
  270. package/dist/ops/pasteRange.d.ts +46 -0
  271. package/dist/ops/pasteRange.d.ts.map +1 -0
  272. package/dist/ops/pasteRange.js +276 -0
  273. package/dist/ops/pasteRange.js.map +1 -0
  274. package/dist/ops/plugin.d.ts +57 -0
  275. package/dist/ops/plugin.d.ts.map +1 -0
  276. package/dist/ops/plugin.js +875 -0
  277. package/dist/ops/plugin.js.map +1 -0
  278. package/dist/ops/sections.d.ts +98 -0
  279. package/dist/ops/sections.d.ts.map +1 -0
  280. package/dist/ops/sections.js +930 -0
  281. package/dist/ops/sections.js.map +1 -0
  282. package/dist/ops/serialize.d.ts +79 -1
  283. package/dist/ops/serialize.d.ts.map +1 -1
  284. package/dist/ops/serialize.js +85 -3
  285. package/dist/ops/serialize.js.map +1 -1
  286. package/dist/ops/stepPattern.d.ts +44 -0
  287. package/dist/ops/stepPattern.d.ts.map +1 -0
  288. package/dist/ops/stepPattern.js +2106 -0
  289. package/dist/ops/stepPattern.js.map +1 -0
  290. package/dist/ops/stepPatternFolders.d.ts +54 -0
  291. package/dist/ops/stepPatternFolders.d.ts.map +1 -0
  292. package/dist/ops/stepPatternFolders.js +299 -0
  293. package/dist/ops/stepPatternFolders.js.map +1 -0
  294. package/dist/ops/types.d.ts +238 -2
  295. package/dist/ops/types.d.ts.map +1 -1
  296. package/dist/rippleEdit.d.ts +5 -1
  297. package/dist/rippleEdit.d.ts.map +1 -1
  298. package/dist/rippleEdit.js +24 -9
  299. package/dist/rippleEdit.js.map +1 -1
  300. package/dist/splitClip.d.ts +29 -1
  301. package/dist/splitClip.d.ts.map +1 -1
  302. package/dist/splitClip.js +231 -1
  303. package/dist/splitClip.js.map +1 -1
  304. package/dist/testing/host-ops.js +3 -3
  305. package/dist/testing/host-ops.js.map +1 -1
  306. package/dist/testing/ops.d.ts +6 -1
  307. package/dist/testing/ops.d.ts.map +1 -1
  308. package/dist/testing/ops.js +823 -11
  309. package/dist/testing/ops.js.map +1 -1
  310. package/dist/timeRemap.d.ts +2 -2
  311. package/dist/timeRemap.d.ts.map +1 -1
  312. package/dist/timeRemap.js +18 -0
  313. package/dist/timeRemap.js.map +1 -1
  314. package/dist/trimClip.d.ts +1 -1
  315. package/dist/trimClip.d.ts.map +1 -1
  316. package/dist/trimClip.js +41 -7
  317. package/dist/trimClip.js.map +1 -1
  318. package/dist/types.d.ts +303 -15
  319. package/dist/types.d.ts.map +1 -1
  320. package/dist/types.js.map +1 -1
  321. package/package.json +11 -5
package/dist/ops/apply.js CHANGED
@@ -12,7 +12,15 @@
12
12
  * `src/render` or `@nodetool-ai/gpu`, so editing needs no renderer (AS2).
13
13
  */
14
14
  import { isShortResourceId } from "@nodetool-ai/protocol";
15
- import { buildEffect, buildMask, buildTimeRemap, buildTransition, resolveDeleteTrackArgs, resolveMoveTrackArgs, resolveShapeArg, textStyleParams } from "@nodetool-ai/protocol/api-schemas/timeline-tool-params.js";
15
+ import { BLEND_MODE_TUPLE } from "@nodetool-ai/protocol/blend-modes";
16
+ import { buildEffect, buildMask, buildTimeRemap, buildTransition, captionStyleParams, resolveDeleteTrackArgs, resolveMoveTrackArgs, resolveShapeArg, shapeStyleParams, textStyleParams, textStylePatchParams } from "@nodetool-ai/protocol/api-schemas/timeline-tool-params.js";
17
+ import { runApplyProgression, runClearChords, runDetectChords, runFitNotesToChords, runListHarmonyPresets, runListProgressions, runSetChords, runSetClipHarmony, runTransposeChords, keyLabel, signatureLabel } from "./chords.js";
18
+ import { runJoinClips } from "./join.js";
19
+ import { onlySelected, runSetMaster, runSetNotes, runSetTrackMix, selectNotes } from "./midiMix.js";
20
+ import { runAutomationEdit } from "./automation.js";
21
+ import { runLoopClip, unrollLoopedInScope } from "./loop.js";
22
+ import { runPasteRange } from "./pasteRange.js";
23
+ import { runDeleteTime, runDuplicateRange, runInsertTime } from "./sections.js";
16
24
  import { staggerClipAnimations } from "../animation/beat.js";
17
25
  import { ANIMATION_PRESETS, buildBakedAnimation, CUSTOM_ANIMATION_CONTRACT, CUSTOM_ANIMATION_PRESET_ID, normalizeCustomCurves, resolveCustomMask, typewriterTiming } from "../animation/index.js";
18
26
  import { paramCurvesForEffects } from "../paramCurves.js";
@@ -25,12 +33,13 @@ import { assertAuthorableFontFamily } from "../fonts/catalog.js";
25
33
  import { selectGeneratedMatteVersion } from "../generatedMatte.js";
26
34
  import { groupDescendantIds, isGroupClip, moveUnitIds, trimGroup, ungroup } from "../group.js";
27
35
  import { isMediaTrackStale, splitClipMediaTracks, resliceTracksForTrimmedClip } from "../mediaTrack.js";
28
- import { quantizeNotes, scaleVelocity, transposeNotes } from "../midi/edit.js";
36
+ import { QUANTIZE_DIVISIONS, quantizeNotes, scaleVelocity, transposeNotes } from "../midi/edit.js";
29
37
  import { DEFAULT_MIDI_INSTRUMENT } from "../midi/instrument.js";
30
38
  import { createMidiNote, sortNotes, validateNotes } from "../midi/notes.js";
31
39
  import { findInstrumentPreset, listMidiInstruments, MIDI_INSTRUMENT_PRESETS } from "../midi/presets.js";
40
+ import { isSourceAnchoredAnimation, resliceSourceAnimations } from "../animation/sourceCurves.js";
32
41
  import { DEFAULT_TEMPO, rescaleClipsForTempo, resolveTempo } from "../midi/tempo.js";
33
- import { msToTicks } from "../midi/ticks.js";
42
+ import { msToTicks, ticksToMs } from "../midi/ticks.js";
34
43
  import { computeModel3DBakeHash } from "../model3dBake.js";
35
44
  import { describeModel3DCameraMove } from "../model3dCameraDescription.js";
36
45
  import { DEFAULT_MODEL3D_REFERENCE_PASS, computeModel3DReferenceHash, model3dReferenceStatus } from "../model3dReference.js";
@@ -41,15 +50,22 @@ import { MODEL3D_MAX_DOLLY_FRACTION, applyModel3DCameraMove, model3dCameraMoveSp
41
50
  import { addReframeKeyframe, clearReframe, mediaTrackCanDriveReframe } from "../reframe.js";
42
51
  import { adaptSequenceFormat } from "../retarget.js";
43
52
  import { sourceRate } from "../sourceRate.js";
53
+ import { activeLoopMs } from "../clipLoop.js";
54
+ import { autoCrossfadeMsOf } from "../autoCrossfade.js";
55
+ import { tempoChangeRefusal } from "../music/tempoRules.js";
44
56
  import { splitClip } from "../splitClip.js";
57
+ import { resolveBarTime } from "./barTime.js";
45
58
  import { activeTakeIdOf, deleteTake as deleteTakeOnClip, renameTake as renameTakeOnClip, selectTake } from "../takes.js";
46
59
  import { moveTrackOrder } from "../trackOrder.js";
47
60
  import { applyTransitionAtCutCandidate, transitionGrowthMs, transitionGrowthUnit, transitionLengthAtCut, planTransitionAtCut } from "../transitionAtCut.js";
48
61
  import { closeGap, findGap, rippleDelete } from "../rippleEdit.js";
49
62
  import { removeFillers, rippleDeleteRange } from "../transcriptOps.js";
50
63
  import { retimeCaption, trimClip } from "../trimClip.js";
64
+ import { assertNotTimeRemapped } from "../timeRemap.js";
51
65
  import { retimeClipSpeed } from "../clipSpeed.js";
52
- import { serializeClip, serializeMediaTrack, serializeTrack } from "./serialize.js";
66
+ import { midiClipDetail, serializeClip, serializeMaster, serializeMediaTrack, serializeTrack, trackDetail } from "./serialize.js";
67
+ import { STEP_PATTERN_OP_HANDLERS } from "./stepPattern.js";
68
+ import { PLUGIN_OP_HANDLERS } from "./plugin.js";
53
69
  /** Units a failed lookup names before it stops and points at get_state. */
54
70
  const MAX_LISTED_UNITS = 12;
55
71
  /**
@@ -156,6 +172,7 @@ const CLIP_PARAM_KEYS = [
156
172
  "durationMs",
157
173
  "inPointMs",
158
174
  "outPointMs",
175
+ "maxSourceDurationMs",
159
176
  "opacity",
160
177
  "transform",
161
178
  "speedMultiplier",
@@ -171,6 +188,10 @@ const CLIP_PARAM_KEYS = [
171
188
  "hidden",
172
189
  "muted",
173
190
  "locked",
191
+ "labelColor",
192
+ "transpose",
193
+ "velocityOffset",
194
+ "quantize",
174
195
  "fontSizePx",
175
196
  "textStyle",
176
197
  "shapeStyle",
@@ -179,15 +200,64 @@ const CLIP_PARAM_KEYS = [
179
200
  function capitalize(s) {
180
201
  return s.length > 0 ? s[0].toUpperCase() + s.slice(1) : s;
181
202
  }
203
+ const TRANSFORM_SCALAR_KEYS = new Set([
204
+ "rotation",
205
+ "rotationX",
206
+ "rotationY",
207
+ "perspective"
208
+ ]);
209
+ const TRANSFORM_POINT_KEYS = new Set(["position", "scale", "anchor"]);
210
+ function validateTransformPoint(name, value, current, fallback) {
211
+ if (value === undefined) {
212
+ return {
213
+ x: current?.x ?? fallback,
214
+ y: current?.y ?? fallback
215
+ };
216
+ }
217
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
218
+ throw new Error(`transform.${name} must be an object.`);
219
+ }
220
+ const obj = value;
221
+ for (const axis of ["x", "y"]) {
222
+ const coord = obj[axis];
223
+ if (coord !== undefined &&
224
+ (typeof coord !== "number" || !Number.isFinite(coord))) {
225
+ throw new Error(`transform.${name}.${axis} must be a finite number.`);
226
+ }
227
+ }
228
+ return {
229
+ x: obj.x ?? current?.x ?? fallback,
230
+ y: obj.y ?? current?.y ?? fallback
231
+ };
232
+ }
182
233
  function mergeClipTransform(current, patch) {
234
+ if (typeof patch !== "object" || patch === null || Array.isArray(patch)) {
235
+ throw new Error("transform must be an object.");
236
+ }
237
+ for (const [key, value] of Object.entries(patch)) {
238
+ if (value === undefined)
239
+ continue;
240
+ if (TRANSFORM_POINT_KEYS.has(key))
241
+ continue;
242
+ if (!TRANSFORM_SCALAR_KEYS.has(key)) {
243
+ throw new Error(`Invalid transform field "${key}".`);
244
+ }
245
+ if (typeof value !== "number" ||
246
+ !Number.isFinite(value) ||
247
+ (key === "perspective" && value <= 0)) {
248
+ throw new Error(key === "perspective"
249
+ ? "transform.perspective must be a positive finite number."
250
+ : `transform.${key} must be a finite number.`);
251
+ }
252
+ }
183
253
  return {
184
- position: { x: 0, y: 0, ...current?.position, ...patch.position },
185
- scale: { x: 1, y: 1, ...current?.scale, ...patch.scale },
254
+ position: validateTransformPoint("position", patch.position, current?.position, 0),
255
+ scale: validateTransformPoint("scale", patch.scale, current?.scale, 1),
186
256
  rotation: patch.rotation ?? current?.rotation ?? 0,
187
257
  rotationX: patch.rotationX ?? current?.rotationX,
188
258
  rotationY: patch.rotationY ?? current?.rotationY,
189
259
  perspective: patch.perspective ?? current?.perspective,
190
- anchor: { x: 0.5, y: 0.5, ...current?.anchor, ...patch.anchor }
260
+ anchor: validateTransformPoint("anchor", patch.anchor, current?.anchor, 0.5)
191
261
  };
192
262
  }
193
263
  /**
@@ -235,7 +305,7 @@ class OpScope {
235
305
  const track = makeTrack({
236
306
  id: this.ctx.newId("track"),
237
307
  type,
238
- name: name ?? `${capitalize(type)} ${index + 1}`,
308
+ name: name ?? `${type === "midi" ? type : capitalize(type)} ${index + 1}`,
239
309
  index
240
310
  });
241
311
  if (type === "midi") {
@@ -324,7 +394,11 @@ class OpScope {
324
394
  pitch: n.pitch,
325
395
  velocity: n.velocity,
326
396
  startTick: n.start_tick,
327
- durationTick: n.duration_tick
397
+ durationTick: n.duration_tick,
398
+ muted: n.muted,
399
+ channel: n.channel,
400
+ releaseVelocity: n.release_velocity,
401
+ expression: n.expression
328
402
  }));
329
403
  const problems = validateNotes(notes);
330
404
  if (problems.length) {
@@ -408,6 +482,29 @@ class OpScope {
408
482
  }
409
483
  return known !== undefined && known > 0 ? known : undefined;
410
484
  }
485
+ /**
486
+ * Per-clip source limits for `clip` and every clip in its move/link unit.
487
+ * For a slip-only edit (`inPointMs` alone), uses `knownSourceMs` so an
488
+ * imported clip whose asset length is unknown is not artificially capped at
489
+ * its current out-point.
490
+ */
491
+ async sourceLimitsFor(clip, options = {}) {
492
+ const unit = moveUnitIds(this.clips, [clip.id], {
493
+ followLinks: this.ctx.followLinks !== false
494
+ });
495
+ const limits = new Map();
496
+ for (const member of this.clips) {
497
+ if (!unit.has(member.id))
498
+ continue;
499
+ const limit = options.slipOnly
500
+ ? await this.knownSourceMs(member)
501
+ : await this.sourceLimitMs(member);
502
+ if (limit !== undefined) {
503
+ limits.set(member.id, limit);
504
+ }
505
+ }
506
+ return limits;
507
+ }
411
508
  /**
412
509
  * The body of `trim_clip`, shared with `set_clip_params`: a caller that
413
510
  * sends `durationMs` alongside a style change means the same edit either
@@ -419,119 +516,244 @@ class OpScope {
419
516
  patch.outPointMs === undefined) {
420
517
  return clip;
421
518
  }
422
- if (patch.inPointMs !== undefined && patch.inPointMs < 0) {
519
+ if (patch.inPointMs !== undefined &&
520
+ (!Number.isFinite(patch.inPointMs) || patch.inPointMs < 0)) {
423
521
  throw new Error("inPointMs cannot be negative.");
424
522
  }
425
- const prospective = patch.durationMs !== undefined && !isGroupClip(clip)
426
- ? trimSourceBounded(clip, patch.durationMs - clip.durationMs, maxSourceMs)
427
- : clip;
428
- const sourceIn = patch.inPointMs ?? prospective.inPointMs ?? 0;
429
- const sourceOut = patch.outPointMs ?? prospective.outPointMs;
430
- if (sourceOut !== undefined && sourceOut <= sourceIn) {
431
- throw new Error("outPointMs must be greater than inPointMs.");
432
- }
433
- if (maxSourceMs !== undefined &&
434
- patch.outPointMs !== undefined &&
435
- patch.outPointMs > maxSourceMs) {
436
- throw new Error(`outPointMs ${patch.outPointMs} is past the end of the source (${maxSourceMs}ms).`);
437
- }
438
- if (isGroupClip(clip) &&
439
- (patch.inPointMs !== undefined || patch.outPointMs !== undefined)) {
523
+ if (patch.outPointMs !== undefined &&
524
+ (!Number.isFinite(patch.outPointMs) || patch.outPointMs < 0)) {
525
+ throw new Error("outPointMs cannot be negative.");
526
+ }
527
+ if (patch.durationMs !== undefined &&
528
+ (!Number.isFinite(patch.durationMs) || patch.durationMs <= 0)) {
529
+ throw new Error(`durationMs must be greater than 0 (got ${patch.durationMs}); delete the clip instead of trimming it to nothing`);
530
+ }
531
+ const sourceEdit = patch.inPointMs !== undefined || patch.outPointMs !== undefined;
532
+ if (isGroupClip(clip) && sourceEdit) {
440
533
  throw new Error("Groups carry no source media; trim their duration instead.");
441
534
  }
442
535
  const targets = this.editTargets(clip);
443
- // An in-point alone is a slip: the window keeps its length and moves
444
- // through the source, so the out-point moves with it — and a linked
445
- // partner slips by the same timeline amount, or picture and sound part.
446
- if (patch.inPointMs !== undefined &&
447
- patch.durationMs === undefined &&
448
- patch.outPointMs === undefined) {
449
- const slipMs = (patch.inPointMs - (clip.inPointMs ?? 0)) / sourceRate(clip);
450
- const slipped = targets.map((target) => {
451
- const inPointMs = target.id === clip.id
452
- ? patch.inPointMs
453
- : (target.inPointMs ?? 0) + slipMs * sourceRate(target);
454
- if (inPointMs < 0) {
455
- throw new Error(`Linked clip "${target.name}" has no source before its in-point to slip into.`);
536
+ const limitFor = (id) => typeof maxSourceMs === "number" ? maxSourceMs : maxSourceMs?.get(id);
537
+ const followLinks = this.ctx.followLinks !== false;
538
+ const link = followLinks ? clip.linkId : undefined;
539
+ const deltaDuration = patch.durationMs !== undefined ? patch.durationMs - clip.durationMs : 0;
540
+ const bpm = resolveTempo(this.state).bpm;
541
+ // A group carries what it holds (D4): shortening one pulls its children
542
+ // inside the window that leaves, and carries any child's linked media with
543
+ // it rather than separating linked A/V.
544
+ if (isGroupClip(clip)) {
545
+ const unit = new Set(targets.map((target) => target.id));
546
+ const members = this.clips;
547
+ let trimmed = [...members];
548
+ // Trim linked roots by the same delta, and keep each group's descendants inside it.
549
+ for (let j = 0; j < members.length; j += 1) {
550
+ const member = members[j];
551
+ if (member.id !== clip.id &&
552
+ (link === undefined || member.linkId !== link)) {
553
+ continue;
456
554
  }
457
- return { target, inPointMs };
458
- });
459
- for (const { target, inPointMs } of slipped) {
460
- target.inPointMs = inPointMs;
461
- target.outPointMs = inPointMs + target.durationMs * sourceRate(target);
462
- // Words are timed on the clip's clock; the media moved under it.
463
- if (target.caption) {
464
- target.caption = retimeCaption(target.caption, -slipMs);
555
+ if (trimmed[j] !== member)
556
+ continue;
557
+ if (isGroupClip(member)) {
558
+ trimmed = trimGroup(trimmed, member.id, "end", deltaDuration);
465
559
  }
466
- this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, target);
467
- this.touch(target.id);
468
- }
469
- return clip;
470
- }
471
- if (targets.length > 1 &&
472
- patch.durationMs !== undefined &&
473
- !isGroupClip(clip)) {
474
- const delta = patch.durationMs - clip.durationMs;
475
- const trimmedTargets = targets.map((target) => {
476
- if (target.durationMs + delta <= 0) {
477
- throw new Error("Linked trim would remove a clip. Shorten the trim or unlink it first.");
560
+ else {
561
+ if (member.durationMs + deltaDuration <= 0) {
562
+ throw new Error("Linked trim would remove a clip. Shorten the trim or unlink it first.");
563
+ }
564
+ trimmed[j] = trimClip(member, "end", deltaDuration, undefined, bpm);
478
565
  }
479
- const trimmed = target.id === clip.id
480
- ? trimSourceBounded(target, delta, maxSourceMs)
481
- : trimClip(target, "end", delta);
482
- if (target.id === clip.id) {
483
- if (patch.inPointMs !== undefined) {
484
- trimmed.inPointMs = patch.inPointMs;
566
+ }
567
+ if (followLinks) {
568
+ const byLink = new Map();
569
+ const pending = [];
570
+ const propagated = new Set();
571
+ for (let j = 0; j < members.length; j += 1) {
572
+ const memberLink = members[j].linkId;
573
+ if (memberLink !== undefined) {
574
+ const bucket = byLink.get(memberLink);
575
+ if (bucket)
576
+ bucket.push(j);
577
+ else
578
+ byLink.set(memberLink, [j]);
485
579
  }
486
- if (patch.outPointMs !== undefined) {
487
- trimmed.outPointMs = patch.outPointMs;
580
+ if (trimmed[j] !== members[j]) {
581
+ pending.push(j);
488
582
  }
489
583
  }
490
- return { target, trimmed };
491
- });
492
- for (const { target, trimmed } of trimmedTargets) {
493
- this.replaceClip(target, trimmed);
494
- this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, trimmed);
495
- this.touch(trimmed.id);
584
+ // A child trimmed by the group carries its linked media with it too.
585
+ for (let cursor = 0; cursor < pending.length; cursor += 1) {
586
+ const index = pending[cursor];
587
+ const memberLink = members[index].linkId;
588
+ if (memberLink === undefined || propagated.has(memberLink))
589
+ continue;
590
+ propagated.add(memberLink);
591
+ const beforeMember = members[index];
592
+ const afterMember = trimmed[index];
593
+ const headDelta = beforeMember.startMs - afterMember.startMs;
594
+ const tailDelta = afterMember.startMs +
595
+ afterMember.durationMs -
596
+ (beforeMember.startMs + beforeMember.durationMs);
597
+ for (const peer of byLink.get(memberLink) ?? []) {
598
+ if (trimmed[peer] !== members[peer])
599
+ continue;
600
+ const peerMember = members[peer];
601
+ if (isGroupClip(peerMember)) {
602
+ const before = [...trimmed];
603
+ if (headDelta !== 0) {
604
+ trimmed = trimGroup(trimmed, peerMember.id, "start", headDelta);
605
+ }
606
+ if (tailDelta !== 0) {
607
+ trimmed = trimGroup(trimmed, peerMember.id, "end", tailDelta);
608
+ }
609
+ for (let k = 0; k < trimmed.length; k += 1) {
610
+ if (trimmed[k] !== before[k]) {
611
+ pending.push(k);
612
+ }
613
+ }
614
+ }
615
+ else {
616
+ let nextPeer = trimmed[peer];
617
+ if (headDelta !== 0) {
618
+ nextPeer = trimClip(nextPeer, "start", headDelta, undefined, bpm);
619
+ }
620
+ if (tailDelta !== 0) {
621
+ nextPeer = trimClip(nextPeer, "end", tailDelta, undefined, bpm);
622
+ }
623
+ trimmed[peer] = nextPeer;
624
+ pending.push(peer);
625
+ }
626
+ }
627
+ }
628
+ }
629
+ for (let j = 0; j < trimmed.length; j += 1) {
630
+ const member = trimmed[j];
631
+ if (!unit.has(member.id))
632
+ continue;
633
+ const limit = limitFor(member.id);
634
+ if (limit !== undefined &&
635
+ outPointOf(member) > limit + SOURCE_BOUND_TOLERANCE_MS) {
636
+ throw new Error(`Clip "${member.name}" cannot be longer than its source: the source ends at ${limit}ms.`);
637
+ }
638
+ }
639
+ this.clips = trimmed;
640
+ for (let j = 0; j < trimmed.length; j += 1) {
641
+ if (trimmed[j] !== members[j]) {
642
+ const changedClip = trimmed[j];
643
+ this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, changedClip);
644
+ this.touch(changedClip.id);
645
+ }
496
646
  }
497
647
  return this.resolveClip(clip.id);
498
648
  }
499
- // A group carries what it holds (D4): shortening one pulls its children
500
- // inside the window that leaves, rather than leaving them hanging past an
501
- // edge nothing draws.
502
- if (isGroupClip(clip) && patch.durationMs !== undefined) {
503
- this.clips = trimGroup(this.clips, clip.id, "end", patch.durationMs - clip.durationMs);
504
- const next = this.clips.find((c) => c.id === clip.id);
505
- for (const target of targets) {
506
- const trimmed = this.resolveClip(target.id);
507
- this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, trimmed);
508
- this.touch(trimmed.id);
649
+ const effectiveIn = (member) => (member.inPointMs ?? 0) +
650
+ (member.pattern !== undefined
651
+ ? ticksToMs(member.patternPhaseTicks ?? 0, bpm)
652
+ : 0);
653
+ const sourceShiftMs = patch.inPointMs !== undefined
654
+ ? (patch.inPointMs - effectiveIn(clip)) / sourceRate(clip)
655
+ : 0;
656
+ const members = this.clips;
657
+ const nextClips = [...members];
658
+ const touchedIndices = [];
659
+ for (let j = 0; j < members.length; j += 1) {
660
+ const original = members[j];
661
+ const primary = original.id === clip.id;
662
+ if (!primary &&
663
+ (link === undefined ||
664
+ original.linkId !== link ||
665
+ (patch.inPointMs === undefined && patch.durationMs === undefined))) {
666
+ continue;
509
667
  }
510
- this.touch(next.id);
511
- return next;
512
- }
513
- // Through the engine, not a raw duration write: `trimClip` refuses a
514
- // time-remapped clip (D13) and carries the source out-point with the edge.
515
- let next = clip;
516
- if (patch.durationMs !== undefined) {
517
- if (patch.durationMs <= 0) {
518
- throw new Error(`durationMs must be greater than 0 (got ${patch.durationMs}); delete the clip instead of trimming it to nothing`);
668
+ if (isGroupClip(original)) {
669
+ throw new Error("Source edits require unlocked media clips.");
519
670
  }
520
- next = this.replaceClip(clip, trimSourceBounded(clip, patch.durationMs - clip.durationMs, maxSourceMs));
521
- }
522
- if (patch.inPointMs !== undefined) {
523
- next.inPointMs = patch.inPointMs;
524
- }
525
- if (patch.outPointMs !== undefined) {
526
- next.outPointMs = patch.outPointMs;
671
+ if (sourceEdit) {
672
+ assertNotTimeRemapped(original, "set_clip_params");
673
+ }
674
+ let member = { ...original };
675
+ const originalAnimations = original.animations;
676
+ const oldIn = effectiveIn(member);
677
+ let nextIn = patch.inPointMs === undefined
678
+ ? (member.inPointMs ?? 0)
679
+ : primary
680
+ ? patch.inPointMs
681
+ : oldIn + sourceShiftMs * sourceRate(member);
682
+ if (!Number.isFinite(nextIn) || nextIn < -SOURCE_BOUND_TOLERANCE_MS) {
683
+ throw new Error(`Linked clip "${member.name}" has no source before its in-point to slip into.`);
684
+ }
685
+ nextIn = Math.max(0, nextIn);
686
+ if (patch.inPointMs !== undefined) {
687
+ member.inPointMs = nextIn;
688
+ // A looped clip's window is one repeat, not its whole length.
689
+ const windowMs = activeLoopMs(member) ?? member.durationMs;
690
+ member.outPointMs = nextIn + windowMs * sourceRate(member);
691
+ // Words are timed on the clip's clock; the media moved under it.
692
+ if (member.caption) {
693
+ member.caption = retimeCaption(member.caption, -(nextIn - oldIn) / sourceRate(member));
694
+ }
695
+ }
696
+ if (patch.durationMs !== undefined) {
697
+ if (member.durationMs + deltaDuration <= 0) {
698
+ throw new Error(primary
699
+ ? `durationMs must be greater than 0 (got ${patch.durationMs}); delete the clip instead of trimming it to nothing`
700
+ : "Linked trim would remove a clip. Shorten the trim or unlink it first.");
701
+ }
702
+ member = trimClip(member, "end", deltaDuration, undefined, bpm);
703
+ }
704
+ if (primary && patch.outPointMs !== undefined) {
705
+ member.outPointMs = patch.outPointMs;
706
+ }
707
+ if (member.outPointMs !== undefined && member.outPointMs <= nextIn) {
708
+ throw new Error("outPointMs must be greater than inPointMs.");
709
+ }
710
+ const limit = limitFor(member.id);
711
+ if (limit !== undefined) {
712
+ const outMs = outPointOf(member);
713
+ if (outMs > limit + SOURCE_BOUND_TOLERANCE_MS) {
714
+ if (primary &&
715
+ patch.outPointMs !== undefined &&
716
+ patch.durationMs === undefined) {
717
+ throw new Error(`outPointMs ${patch.outPointMs} is past the end of the source (${limit}ms).`);
718
+ }
719
+ throw new Error(`Clip "${member.name}" cannot be longer than its source: the source ends at ${limit}ms.`);
720
+ }
721
+ if (member.outPointMs !== undefined &&
722
+ member.outPointMs > limit &&
723
+ member.outPointMs - limit <= SOURCE_BOUND_TOLERANCE_MS) {
724
+ member.outPointMs = limit;
725
+ }
726
+ }
727
+ if (member.pattern !== undefined && patch.inPointMs !== undefined) {
728
+ const phase = Math.round(msToTicks(nextIn, bpm));
729
+ if (phase > 0)
730
+ member.patternPhaseTicks = phase;
731
+ else
732
+ delete member.patternPhaseTicks;
733
+ member.outPointMs = outPointOf(member) - nextIn;
734
+ member.inPointMs = 0;
735
+ }
736
+ if (sourceEdit && originalAnimations && member.animations) {
737
+ const finalIn = member.inPointMs ?? 0;
738
+ const finalOut = outPointOf(member);
739
+ member.animations = member.animations.map((anim, idx) => {
740
+ const origAnim = originalAnimations[idx];
741
+ if (origAnim && isSourceAnchoredAnimation(origAnim)) {
742
+ return resliceSourceAnimations([origAnim], finalIn, finalOut, member.durationMs)[0];
743
+ }
744
+ return anim;
745
+ });
746
+ }
747
+ nextClips[j] = member;
748
+ touchedIndices.push(j);
527
749
  }
528
- if (patch.durationMs !== undefined ||
529
- patch.inPointMs !== undefined ||
530
- patch.outPointMs !== undefined) {
531
- this.touch(next.id);
750
+ this.clips = nextClips;
751
+ for (const idx of touchedIndices) {
752
+ const updated = nextClips[idx];
753
+ this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, updated);
754
+ this.touch(updated.id);
532
755
  }
533
- this.mediaTracks = resliceTracksForTrimmedClip(this.mediaTracks, next);
534
- return next;
756
+ return this.resolveClip(clip.id);
535
757
  }
536
758
  /**
537
759
  * Move a clip's head by `deltaMs` (positive grows it earlier), for the clip
@@ -539,16 +761,26 @@ class OpScope {
539
761
  * carries its children with the edge (D4).
540
762
  */
541
763
  applyHeadTrim(clip, deltaMs) {
542
- const targets = this.editTargets(clip);
764
+ // A looped clip is written out as plain copies first (CE3); the first
765
+ // copy keeps the id and takes the trim.
766
+ const unrolled = (c) => {
767
+ if (isGroupClip(c) || activeLoopMs(c) === undefined)
768
+ return c;
769
+ this.assertWritable([c]);
770
+ return unrollLoopedInScope(this, c)[0];
771
+ };
772
+ clip = unrolled(clip);
773
+ const targets = this.editTargets(clip).map((t) => t.id === clip.id ? t : unrolled(t));
543
774
  if (isGroupClip(clip)) {
544
775
  this.clips = trimGroup(this.clips, clip.id, "start", deltaMs);
545
776
  }
546
777
  else {
547
778
  // Every partner is trimmed before any is written, so one that runs out
548
779
  // of source leaves the whole group as it was.
780
+ const bpm = resolveTempo(this.state).bpm;
549
781
  const trimmed = targets.map((target) => ({
550
782
  target,
551
- next: trimClip(target, "start", deltaMs)
783
+ next: trimClip(target, "start", deltaMs, undefined, bpm)
552
784
  }));
553
785
  for (const { target, next } of trimmed) {
554
786
  this.replaceClip(target, next);
@@ -670,6 +902,12 @@ class OpScope {
670
902
  return serializeTrack(this.state, track);
671
903
  }
672
904
  }
905
+ const SOURCE_BOUND_TOLERANCE_MS = 1e-6;
906
+ function outPointOf(clip) {
907
+ const inPointMs = clip.inPointMs ?? 0;
908
+ return (clip.outPointMs ??
909
+ inPointMs + (activeLoopMs(clip) ?? clip.durationMs) * sourceRate(clip));
910
+ }
673
911
  /**
674
912
  * The keyframe helpers mint their own id for a keyframe animation they
675
913
  * create. An op takes every id from its context, so a new animation is
@@ -681,21 +919,44 @@ function withContextAnimationIds(scope, clip, animations) {
681
919
  ? animation
682
920
  : { ...animation, id: scope.ctx.newId("anim") });
683
921
  }
684
- /**
685
- * `trimClip` on the end edge, capped at the source length when one is known.
686
- * The refusal names the limit, which the engine's own message does not.
687
- */
688
- function trimSourceBounded(clip, deltaMs, maxSourceMs) {
689
- try {
690
- return trimClip(clip, "end", deltaMs, maxSourceMs);
922
+ /** CE6: set or clear the midi region parameters (D53). Null clears. */
923
+ function applyMidiRegionPatch(clip, patch) {
924
+ const keys = ["transpose", "velocityOffset", "quantize"];
925
+ if (!keys.some((k) => patch[k] !== undefined))
926
+ return;
927
+ if (clip.mediaType !== "midi") {
928
+ throw new Error(`Clip "${clip.name}" is a ${clip.mediaType} clip. transpose, velocityOffset and quantize apply to a midi clip.`);
691
929
  }
692
- catch (error) {
693
- if (maxSourceMs !== undefined &&
694
- error instanceof Error &&
695
- error.message.includes("beyond source out-point")) {
696
- throw new Error(`Clip "${clip.name}" cannot be longer than its source: the source ends at ${maxSourceMs}ms.`);
697
- }
698
- throw error;
930
+ const num = (key, max) => {
931
+ const v = patch[key];
932
+ if (v === undefined || v === null)
933
+ return v;
934
+ if (typeof v !== "number" || !Number.isInteger(v) || Math.abs(v) > max) {
935
+ throw new Error(`${key} must be a whole number from -${max} to ${max}.`);
936
+ }
937
+ return v;
938
+ };
939
+ const transpose = num("transpose", 48);
940
+ if (transpose === null || transpose === 0)
941
+ delete clip.transpose;
942
+ else if (transpose !== undefined)
943
+ clip.transpose = transpose;
944
+ const offset = num("velocityOffset", 127);
945
+ if (offset === null || offset === 0)
946
+ delete clip.velocityOffset;
947
+ else if (offset !== undefined)
948
+ clip.velocityOffset = offset;
949
+ const q = patch.quantize;
950
+ if (q === null)
951
+ delete clip.quantize;
952
+ else if (q !== undefined) {
953
+ const { grid, strength } = q;
954
+ if (!QUANTIZE_DIVISIONS.includes(grid) ||
955
+ typeof strength !== "number" ||
956
+ !(strength >= 0 && strength <= 100)) {
957
+ throw new Error(`quantize needs a grid (${QUANTIZE_DIVISIONS.join(", ")}) and a strength from 0 to 100.`);
958
+ }
959
+ clip.quantize = { grid: grid, strength };
699
960
  }
700
961
  }
701
962
  function rejectUnknownClipParams(patch) {
@@ -829,7 +1090,10 @@ function runMidiNoteEdit(scope, op) {
829
1090
  const clip = scope.resolveMidiClip(op.clip);
830
1091
  scope.assertWritable([clip]);
831
1092
  const before = clip.notes ?? [];
832
- const notes = op.op === "transpose_clip"
1093
+ const selection = op.note_ids
1094
+ ? new Set(selectNotes(clip, op.note_ids, undefined))
1095
+ : undefined;
1096
+ const whole = op.op === "transpose_clip"
833
1097
  ? transposeNotes(before, op.semitones)
834
1098
  : op.op === "scale_velocity"
835
1099
  ? scaleVelocity(before, op.factor)
@@ -837,21 +1101,32 @@ function runMidiNoteEdit(scope, op) {
837
1101
  division: op.division,
838
1102
  strength: op.strength,
839
1103
  target: op.target,
1104
+ swing: op.swing,
1105
+ noteIds: selection,
840
1106
  // The grid is anchored at `tempo.offsetMs`, as the editor draws it.
841
1107
  phaseTick: msToTicks(resolveTempo(scope.state).offsetMs -
842
1108
  clip.startMs +
843
1109
  (clip.inPointMs ?? 0), resolveTempo(scope.state).bpm)
844
1110
  });
845
- clip.notes = notes;
1111
+ // transpose and velocity scaling touch every note, so a selection keeps the
1112
+ // edit on its own notes. quantize already honours `noteIds`.
1113
+ const notes = selection && op.op !== "quantize_notes"
1114
+ ? onlySelected(before, whole, selection)
1115
+ : whole;
1116
+ const movedNoteCount = op.op === "quantize_notes"
1117
+ ? notes.filter((note, i) => note.startTick !== before[i]?.startTick ||
1118
+ note.durationTick !== before[i]?.durationTick).length
1119
+ : undefined;
1120
+ const sorted = sortNotes(notes);
1121
+ clip.notes = sorted;
846
1122
  scope.touch(clip.id);
847
1123
  const result = {
848
1124
  ok: true,
849
1125
  clip: scope.clipOut(clip),
850
- noteCount: notes.length
1126
+ noteCount: sorted.length
851
1127
  };
852
- if (op.op === "quantize_notes") {
853
- result.movedNoteCount = notes.filter((note, i) => note.startTick !== before[i]?.startTick ||
854
- note.durationTick !== before[i]?.durationTick).length;
1128
+ if (movedNoteCount !== undefined) {
1129
+ result.movedNoteCount = movedNoteCount;
855
1130
  }
856
1131
  return result;
857
1132
  }
@@ -926,11 +1201,23 @@ function commitRipple(scope, next) {
926
1201
  scope.touch(...movedClipIds, ...removedClipIds, ...next.filter((c) => !before.has(c.id)).map((c) => c.id));
927
1202
  return { movedClipIds, removedClipIds };
928
1203
  }
1204
+ function runNamedAutomation(scope, op) {
1205
+ const track = scope.resolveTrack(op.track_id);
1206
+ const { op: edit, track_id: _track, ...payload } = op;
1207
+ runAutomationEdit(track, { ...payload, edit }, () => scope.ctx.newId("lane"));
1208
+ return { ok: true, track: scope.trackOut(track) };
1209
+ }
929
1210
  const OP_HANDLERS = {
930
- get_state: (scope) => {
1211
+ "automation.addPoints": runNamedAutomation,
1212
+ "automation.movePoints": runNamedAutomation,
1213
+ "automation.deletePoints": runNamedAutomation,
1214
+ "automation.clearLane": runNamedAutomation,
1215
+ "automation.setLaneEnabled": runNamedAutomation,
1216
+ setTrackAutomationMode: runNamedAutomation,
1217
+ get_state: (scope, op) => {
931
1218
  const state = scope.state;
932
1219
  const durationMs = scope.clips.reduce((m, c) => Math.max(m, c.startMs + c.durationMs), 0);
933
- return {
1220
+ const result = {
934
1221
  ok: true,
935
1222
  fps: state.fps,
936
1223
  width: state.width,
@@ -939,11 +1226,22 @@ const OP_HANDLERS = {
939
1226
  playheadMs: state.playheadMs,
940
1227
  selectedClipIds: [...state.selectedClipIds],
941
1228
  tempo: state.tempo,
1229
+ music: state.music,
1230
+ autoCrossfadeMs: autoCrossfadeMsOf(state),
1231
+ key: keyLabel(resolveTempo(state)) ?? null,
1232
+ signature: signatureLabel(resolveTempo(state)),
1233
+ master: serializeMaster(state.master),
1234
+ trackFolders: state.trackFolders ?? [],
942
1235
  tracks: scope.tracks.map((t) => scope.trackOut(t)),
943
1236
  clips: scope.clips.map((c) => scope.clipOut(c)),
944
1237
  mediaTracks: scope.mediaTracks.map(serializeMediaTrack),
945
1238
  markers: state.markers.map((m) => ({ ...m }))
946
1239
  };
1240
+ if (op.clip !== undefined)
1241
+ result.clipDetail = midiClipDetail(scope.resolveMidiClip(op.clip));
1242
+ if (op.track !== undefined)
1243
+ result.trackDetail = trackDetail(scope.resolveTrack(op.track));
1244
+ return result;
947
1245
  },
948
1246
  add_track: runTrackOp,
949
1247
  move_track: runTrackOp,
@@ -1015,7 +1313,8 @@ const OP_HANDLERS = {
1015
1313
  id: scope.ctx.newId("clip"),
1016
1314
  trackId: track.id,
1017
1315
  name: op.name ?? found.name,
1018
- startMs: op.startMs ?? scope.trackEndMs(track.id),
1316
+ startMs: resolveBarTime(state, op, op.startMs, "startMs") ??
1317
+ scope.trackEndMs(track.id),
1019
1318
  durationMs: op.durationMs ?? found.durationMs ?? DEFAULT_MEDIA_CLIP_DURATION_MS,
1020
1319
  mediaType,
1021
1320
  sourceType: "imported",
@@ -1292,7 +1591,12 @@ const OP_HANDLERS = {
1292
1591
  height: state.height
1293
1592
  };
1294
1593
  const dependencyHash = computeModel3DReferenceHash(clip, sequence, pass);
1295
- if (model3dReferenceStatus(clip, sequence, pass) === "current") {
1594
+ // The set is saved in place, so only the asset's revision shows an edit
1595
+ // to it. A host that cannot read the asset skips that check.
1596
+ const assetRevision = (await scope.ctx.model3dAssetRevision?.(clip.currentAssetId)) ?? undefined;
1597
+ if (!op.force &&
1598
+ model3dReferenceStatus(clip, sequence, { pass, assetRevision }) ===
1599
+ "current") {
1296
1600
  return {
1297
1601
  ok: true,
1298
1602
  clip: scope.clipOut(clip),
@@ -1315,7 +1619,12 @@ const OP_HANDLERS = {
1315
1619
  pass,
1316
1620
  dependencyHash
1317
1621
  });
1318
- const reference = { assetId: rendered.assetId, dependencyHash, pass };
1622
+ const reference = {
1623
+ assetId: rendered.assetId,
1624
+ dependencyHash,
1625
+ pass,
1626
+ ...(assetRevision !== undefined && { assetRevision })
1627
+ };
1319
1628
  clip.model3dStyle = { ...style, reference };
1320
1629
  scope.touch(clip.id);
1321
1630
  return {
@@ -1409,25 +1718,88 @@ const OP_HANDLERS = {
1409
1718
  },
1410
1719
  split_clip: (scope, op) => {
1411
1720
  const state = scope.state;
1412
- const clip = scope.resolveClip(op.target);
1413
- const at = op.atMs ?? state.playheadMs;
1721
+ let clip = scope.resolveClip(op.target);
1722
+ const at = resolveBarTime(state, op, op.atMs, "atMs") ?? state.playheadMs;
1414
1723
  if (at <= clip.startMs || at >= clip.startMs + clip.durationMs) {
1415
1724
  throw new Error(`Split time ${at}ms is outside clip "${clip.name}".`);
1416
1725
  }
1417
- const targets = scope
1418
- .editTargets(clip)
1726
+ // A looped clip is written out as plain copies first (CE3), so the cut
1727
+ // lands in one repeat and nothing keeps a loop it no longer matches.
1728
+ // Later repeats lose the link, so the partners are found first.
1729
+ let partners = [];
1730
+ // Unrolled copies that end or start on the cut, and so join its link halves.
1731
+ const leftEdge = [];
1732
+ const rightEdge = [];
1733
+ const noteEdges = (copies) => {
1734
+ for (const c of copies) {
1735
+ if (Math.abs(c.startMs + c.durationMs - at) < 1e-6)
1736
+ leftEdge.push(c);
1737
+ if (Math.abs(c.startMs - at) < 1e-6)
1738
+ rightEdge.push(c);
1739
+ }
1740
+ };
1741
+ let onBoundary = false;
1742
+ const unrolled = [];
1743
+ if (activeLoopMs(clip) !== undefined) {
1744
+ partners = scope.editTargets(clip).filter((t) => t.id !== clip.id);
1745
+ scope.assertWritable([clip]);
1746
+ const copies = unrollLoopedInScope(scope, clip);
1747
+ unrolled.push(...copies);
1748
+ const hit = copies.find((c) => at > c.startMs && at < c.startMs + c.durationMs);
1749
+ if (!hit) {
1750
+ // The cut falls on a repeat boundary: the unroll is the split, and the
1751
+ // partners that span the boundary are cut there too.
1752
+ onBoundary = true;
1753
+ noteEdges(copies);
1754
+ }
1755
+ else {
1756
+ clip = hit;
1757
+ }
1758
+ }
1759
+ // A looped linked partner is written out as plain copies too, and the cut
1760
+ // lands in the copy that holds it.
1761
+ const targets = [
1762
+ ...(onBoundary ? [] : [clip]),
1763
+ ...(partners.length > 0
1764
+ ? partners
1765
+ : scope.editTargets(clip).filter((t) => t.id !== clip.id))
1766
+ ]
1767
+ .flatMap((target) => {
1768
+ if (target.id === clip.id || activeLoopMs(target) === undefined) {
1769
+ return [target];
1770
+ }
1771
+ scope.assertWritable([target]);
1772
+ const copies = unrollLoopedInScope(scope, target);
1773
+ unrolled.push(...copies);
1774
+ noteEdges(copies);
1775
+ return copies.filter((c) => at > c.startMs && at < c.startMs + c.durationMs);
1776
+ })
1419
1777
  .filter((target) => at > target.startMs && at < target.startMs + target.durationMs);
1420
- const leftLink = targets.length > 1 ? scope.ctx.newId("link") : undefined;
1421
- const rightLink = targets.length > 1 ? scope.ctx.newId("link") : undefined;
1778
+ const leftLink = targets.length + leftEdge.length > 1 ? scope.ctx.newId("link") : undefined;
1779
+ const rightLink = targets.length + rightEdge.length > 1 ? scope.ctx.newId("link") : undefined;
1780
+ for (const edge of leftEdge) {
1781
+ if (leftLink !== undefined)
1782
+ edge.linkId = leftLink;
1783
+ scope.touch(edge.id);
1784
+ }
1785
+ for (const edge of rightEdge) {
1786
+ if (rightLink !== undefined)
1787
+ edge.linkId = rightLink;
1788
+ scope.touch(edge.id);
1789
+ }
1422
1790
  const halves = [];
1423
1791
  for (const target of targets) {
1424
- const [cutLeft, cutRight] = splitClip(target, at);
1792
+ const [cutLeft, cutRight] = splitClip(target, at, {
1793
+ bpm: resolveTempo(state).bpm,
1794
+ gridOffsetMs: resolveTempo(state).offsetMs,
1795
+ crossing: op.crossing
1796
+ });
1425
1797
  cutLeft.id = scope.ctx.newId("clip");
1426
1798
  cutRight.id = scope.ctx.newId("clip");
1427
- if (targets.length > 1) {
1799
+ if (leftLink !== undefined)
1428
1800
  cutLeft.linkId = leftLink;
1801
+ if (rightLink !== undefined)
1429
1802
  cutRight.linkId = rightLink;
1430
- }
1431
1803
  const split = splitClipMediaTracks(scope.mediaTracks, target.id, cutLeft, cutRight, () => scope.ctx.newId("track"));
1432
1804
  const { left, right } = split;
1433
1805
  scope.mediaTracks = split.mediaTracks;
@@ -1437,21 +1809,59 @@ const OP_HANDLERS = {
1437
1809
  scope.touch(target.id, left.id, right.id);
1438
1810
  halves.push(left, right);
1439
1811
  }
1812
+ // Unrolled repeats lose the link, so a survivor can hold a link alone.
1813
+ const linkIds = new Set([...partners, ...targets, ...unrolled].flatMap((t) => t.linkId ? [t.linkId] : []));
1814
+ for (const id of linkIds) {
1815
+ const holders = scope.clips.filter((c) => c.linkId === id);
1816
+ if (holders.length === 1) {
1817
+ delete holders[0].linkId;
1818
+ scope.touch(holders[0].id);
1819
+ }
1820
+ }
1821
+ if (onBoundary) {
1822
+ return {
1823
+ ok: true,
1824
+ clips: [...unrolled, ...halves].map((c) => scope.clipOut(c))
1825
+ };
1826
+ }
1440
1827
  return { ok: true, clips: halves.map((half) => scope.clipOut(half)) };
1441
1828
  },
1442
1829
  trim_clip: async (scope, op) => {
1443
1830
  const clip = scope.resolveClip(op.target);
1831
+ const endMs = resolveBarTime(scope.state, op, undefined, "durationMs");
1832
+ if (endMs !== undefined && op.durationMs !== undefined) {
1833
+ throw new Error("Send `durationMs` or `atBar`, not both.");
1834
+ }
1835
+ if (op.startMs !== undefined) {
1836
+ if (op.durationMs !== undefined ||
1837
+ op.inPointMs !== undefined ||
1838
+ op.outPointMs !== undefined ||
1839
+ endMs !== undefined) {
1840
+ throw new Error("Send `startMs` alone to head-trim a clip, without durationMs, inPointMs, outPointMs, or atBar.");
1841
+ }
1842
+ const headTrimmed = scope.applyHeadTrim(clip, clip.startMs - op.startMs);
1843
+ return { ok: true, clip: scope.clipOut(headTrimmed) };
1844
+ }
1845
+ const durationMs = endMs === undefined ? op.durationMs : endMs - clip.startMs;
1846
+ const slipOnly = op.inPointMs !== undefined &&
1847
+ durationMs === undefined &&
1848
+ op.outPointMs === undefined;
1444
1849
  const trimmed = scope.applyTrim(clip, {
1445
- durationMs: op.durationMs,
1850
+ durationMs,
1446
1851
  inPointMs: op.inPointMs,
1447
1852
  outPointMs: op.outPointMs
1448
- }, await scope.sourceLimitMs(clip));
1853
+ }, await scope.sourceLimitsFor(clip, { slipOnly }));
1449
1854
  scope.mediaTracks = resliceTracksForTrimmedClip(scope.mediaTracks, trimmed);
1855
+ // A trim to a length at or under the loop window leaves nothing to repeat.
1856
+ if (trimmed.loopLengthMs !== undefined &&
1857
+ activeLoopMs(trimmed) === undefined) {
1858
+ delete trimmed.loopLengthMs;
1859
+ }
1450
1860
  return { ok: true, clip: scope.clipOut(trimmed) };
1451
1861
  },
1452
1862
  move_clip: (scope, op) => {
1453
1863
  const moved = scope.applyMove(scope.resolveClip(op.target), {
1454
- startMs: op.startMs,
1864
+ startMs: resolveBarTime(scope.state, op, op.startMs, "startMs"),
1455
1865
  trackId: op.trackId
1456
1866
  });
1457
1867
  return { ok: true, clip: scope.clipOut(moved) };
@@ -1484,8 +1894,15 @@ const OP_HANDLERS = {
1484
1894
  },
1485
1895
  duplicate_clip: (scope, op) => {
1486
1896
  const src = scope.resolveClip(op.target);
1487
- const offsetMs = src.durationMs + (op.gapMs ?? 0);
1488
- if (!Number.isFinite(offsetMs) || src.startMs + offsetMs < 0) {
1897
+ const count = op.count ?? 1;
1898
+ if (!Number.isInteger(count) || count < 1 || count > 64) {
1899
+ throw new Error(`count must be a whole number from 1 to 64. Got ${count}.`);
1900
+ }
1901
+ const atMs = resolveBarTime(scope.state, op, undefined, "gapMs");
1902
+ // Copies sit back to back; `gapMs` is the space between neighbours.
1903
+ const stepMs = src.durationMs + (op.gapMs ?? 0);
1904
+ const firstStartMs = atMs ?? src.startMs + stepMs;
1905
+ if (!Number.isFinite(stepMs) || firstStartMs < 0) {
1489
1906
  throw new Error(`gapMs ${op.gapMs} would place the copy of "${src.name}" before zero.`);
1490
1907
  }
1491
1908
  // A group's copy carries copies of what it holds, at the same offset, so
@@ -1500,89 +1917,136 @@ const OP_HANDLERS = {
1500
1917
  for (const clip of sources) {
1501
1918
  scope.assertWritable([], clip.trackId);
1502
1919
  }
1503
- const freshIds = new Map(sources.map((clip) => [clip.id, scope.ctx.newId("clip")]));
1504
- // A link whose members are all copied stays a link among the copies,
1505
- // under a fresh id; a lone half is copied unlinked.
1506
- const linkCounts = new Map();
1507
- for (const clip of sources) {
1508
- if (clip.linkId !== undefined && clip.id !== src.id) {
1509
- linkCounts.set(clip.linkId, (linkCounts.get(clip.linkId) ?? 0) + 1);
1510
- }
1511
- }
1512
- const freshLinks = new Map();
1513
- const copies = sources.map((clip) => {
1514
- const copy = structuredClone(clip);
1515
- copy.id = freshIds.get(clip.id);
1516
- copy.startMs += offsetMs;
1517
- copy.locked = false;
1518
- if (copy.parentId !== undefined && clip.id !== src.id) {
1519
- copy.parentId = freshIds.get(copy.parentId) ?? copy.parentId;
1520
- }
1521
- const linkId = clip.linkId;
1522
- if (linkId !== undefined &&
1523
- clip.id !== src.id &&
1524
- (linkCounts.get(linkId) ?? 0) >= 2) {
1525
- let fresh = freshLinks.get(linkId);
1526
- if (fresh === undefined) {
1527
- fresh = scope.ctx.newId("link");
1528
- freshLinks.set(linkId, fresh);
1920
+ // Every copy must land at or after zero, the last one included.
1921
+ const earliestMs = Math.min(...sources.map((clip) => clip.startMs));
1922
+ for (const n of [0, count - 1]) {
1923
+ const offsetMs = firstStartMs + n * stepMs - src.startMs;
1924
+ if (earliestMs + offsetMs < 0) {
1925
+ throw new Error(`gapMs ${op.gapMs} would place copy ${n + 1} of "${src.name}" before zero.`);
1926
+ }
1927
+ }
1928
+ const all = [];
1929
+ const firsts = [];
1930
+ for (let n = 0; n < count; n += 1) {
1931
+ const offsetMs = firstStartMs + n * stepMs - src.startMs;
1932
+ const freshIds = new Map(sources.map((clip) => [clip.id, scope.ctx.newId("clip")]));
1933
+ // A link whose members are all copied stays a link among the copies,
1934
+ // under a fresh id; a lone half is copied unlinked.
1935
+ const linkCounts = new Map();
1936
+ for (const clip of sources) {
1937
+ if (clip.linkId !== undefined && clip.id !== src.id) {
1938
+ linkCounts.set(clip.linkId, (linkCounts.get(clip.linkId) ?? 0) + 1);
1529
1939
  }
1530
- copy.linkId = fresh;
1531
1940
  }
1532
- else {
1533
- delete copy.linkId;
1534
- }
1535
- // A generated clip's copy is a variation to regenerate, so it starts
1536
- // as a draft. Imported media keeps its asset and draws the same frames.
1537
- if (clip.sourceType === "generated") {
1538
- copy.status = "draft";
1539
- copy.versions = [];
1540
- delete copy.currentAssetId;
1541
- delete copy.lastGeneratedHash;
1542
- delete copy.activeTakeId;
1543
- }
1544
- copy.animations = copy.animations?.map((animation) => ({
1545
- ...animation,
1546
- id: scope.ctx.newId("anim")
1547
- }));
1548
- return copy;
1549
- });
1550
- scope.clips.push(...copies);
1551
- scope.touch(...copies.map((copy) => copy.id));
1941
+ const freshLinks = new Map();
1942
+ const copies = sources.map((clip) => {
1943
+ const copy = structuredClone(clip);
1944
+ copy.id = freshIds.get(clip.id);
1945
+ copy.startMs += offsetMs;
1946
+ copy.locked = false;
1947
+ if (copy.parentId !== undefined && clip.id !== src.id) {
1948
+ copy.parentId = freshIds.get(copy.parentId) ?? copy.parentId;
1949
+ }
1950
+ const linkId = clip.linkId;
1951
+ if (linkId !== undefined &&
1952
+ clip.id !== src.id &&
1953
+ (linkCounts.get(linkId) ?? 0) >= 2) {
1954
+ let fresh = freshLinks.get(linkId);
1955
+ if (fresh === undefined) {
1956
+ fresh = scope.ctx.newId("link");
1957
+ freshLinks.set(linkId, fresh);
1958
+ }
1959
+ copy.linkId = fresh;
1960
+ }
1961
+ else {
1962
+ delete copy.linkId;
1963
+ }
1964
+ // A generated clip's copy is a variation to regenerate, so it starts
1965
+ // as a draft. Imported media keeps its asset and draws the same frames.
1966
+ if (clip.sourceType === "generated") {
1967
+ copy.status = "draft";
1968
+ copy.versions = [];
1969
+ delete copy.currentAssetId;
1970
+ delete copy.lastGeneratedHash;
1971
+ delete copy.activeTakeId;
1972
+ }
1973
+ copy.animations = copy.animations?.map((animation) => ({
1974
+ ...animation,
1975
+ id: scope.ctx.newId("anim")
1976
+ }));
1977
+ return copy;
1978
+ });
1979
+ all.push(...copies);
1980
+ firsts.push(copies[0]);
1981
+ }
1982
+ scope.clips.push(...all);
1983
+ scope.touch(...all.map((copy) => copy.id));
1552
1984
  const result = {
1553
1985
  ok: true,
1554
- clip: scope.clipOut(copies[0])
1986
+ clip: scope.clipOut(firsts[0])
1555
1987
  };
1556
- if (copies.length > 1) {
1557
- result.children = copies.slice(1).map((copy) => copy.id);
1988
+ if (count > 1) {
1989
+ result.clips = firsts.map((copy) => scope.clipOut(copy));
1990
+ }
1991
+ if (sources.length > 1) {
1992
+ result.children = all
1993
+ .filter((copy) => !firsts.includes(copy))
1994
+ .map((copy) => copy.id);
1558
1995
  }
1559
1996
  return result;
1560
1997
  },
1561
1998
  set_clip_params: async (scope, op) => {
1562
1999
  let clip = scope.resolveClip(op.target);
1563
2000
  const patch = { ...op.patch };
2001
+ const rawOpMaxSource = op.maxSourceDurationMs;
2002
+ const rawPatchMaxSource = patch.maxSourceDurationMs;
2003
+ for (const rawLimit of [rawOpMaxSource, rawPatchMaxSource]) {
2004
+ if (rawLimit !== undefined &&
2005
+ (typeof rawLimit !== "number" ||
2006
+ !Number.isFinite(rawLimit) ||
2007
+ rawLimit <= 0)) {
2008
+ throw new Error("maxSourceDurationMs must be finite and positive.");
2009
+ }
2010
+ }
2011
+ const explicitMaxSourceMs = rawOpMaxSource ??
2012
+ rawPatchMaxSource;
2013
+ delete patch.maxSourceDurationMs;
1564
2014
  rejectUnknownClipParams(patch);
1565
2015
  // Timing belongs to move_clip and trim_clip, but a caller sending it here
1566
2016
  // means one edit either way — so apply it through the same code rather
1567
2017
  // than dropping it or making them call twice.
2018
+ const hasTrimPatch = patch.durationMs !== undefined ||
2019
+ patch.inPointMs !== undefined ||
2020
+ patch.outPointMs !== undefined;
2021
+ const slipOnly = patch.inPointMs !== undefined &&
2022
+ patch.durationMs === undefined &&
2023
+ patch.outPointMs === undefined;
1568
2024
  clip = scope.applyTrim(clip, {
1569
2025
  durationMs: patch.durationMs,
1570
2026
  inPointMs: patch.inPointMs,
1571
2027
  outPointMs: patch.outPointMs
1572
- }, patch.durationMs === undefined && patch.outPointMs === undefined
1573
- ? undefined
1574
- : await scope.sourceLimitMs(clip));
2028
+ }, hasTrimPatch
2029
+ ? (explicitMaxSourceMs ??
2030
+ (await scope.sourceLimitsFor(clip, { slipOnly })))
2031
+ : undefined);
1575
2032
  clip = scope.applyMove(clip, {
1576
2033
  startMs: patch.startMs,
1577
2034
  trackId: patch.trackId
1578
2035
  });
1579
2036
  if (patch.fontSizePx !== undefined) {
2037
+ if (typeof patch.fontSizePx !== "number" ||
2038
+ !Number.isFinite(patch.fontSizePx) ||
2039
+ patch.fontSizePx <= 0) {
2040
+ throw new Error("fontSizePx must be a positive finite number.");
2041
+ }
1580
2042
  // Shorthand for the one text field callers reach for by name.
1581
- const style = patch.textStyle ?? clip.textStyle;
1582
- if (!style) {
2043
+ if (!patch.textStyle && !clip.textStyle) {
1583
2044
  throw new Error(`Clip "${clip.name}" carries no text to size; fontSizePx applies to a text clip's textStyle.`);
1584
2045
  }
1585
- patch.textStyle = { ...style, fontSizePx: patch.fontSizePx };
2046
+ patch.textStyle = {
2047
+ ...(patch.textStyle ?? {}),
2048
+ fontSizePx: patch.fontSizePx
2049
+ };
1586
2050
  }
1587
2051
  if (patch.name !== undefined) {
1588
2052
  clip.name = patch.name;
@@ -1622,9 +2086,22 @@ const OP_HANDLERS = {
1622
2086
  clip.audioEffects = patch.audioEffects;
1623
2087
  }
1624
2088
  if (patch.blendMode !== undefined) {
1625
- clip.blendMode = patch.blendMode;
2089
+ if (patch.blendMode === null) {
2090
+ delete clip.blendMode;
2091
+ }
2092
+ else {
2093
+ if (!BLEND_MODE_TUPLE.includes(patch.blendMode)) {
2094
+ throw new Error(`Invalid blendMode "${patch.blendMode}". Valid modes: ${BLEND_MODE_TUPLE.join(", ")}.`);
2095
+ }
2096
+ clip.blendMode = patch.blendMode;
2097
+ }
1626
2098
  }
1627
2099
  if (patch.borderRadius !== undefined) {
2100
+ if (typeof patch.borderRadius !== "number" ||
2101
+ !Number.isFinite(patch.borderRadius) ||
2102
+ patch.borderRadius < 0) {
2103
+ throw new Error("borderRadius must be a non-negative finite number.");
2104
+ }
1628
2105
  clip.borderRadius = patch.borderRadius;
1629
2106
  }
1630
2107
  if (patch.crop !== undefined) {
@@ -1641,6 +2118,18 @@ const OP_HANDLERS = {
1641
2118
  clip.crop = patch.crop;
1642
2119
  }
1643
2120
  }
2121
+ if (patch.labelColor !== undefined) {
2122
+ if (patch.labelColor === null) {
2123
+ delete clip.labelColor;
2124
+ }
2125
+ else {
2126
+ clip.labelColor = patch.labelColor;
2127
+ }
2128
+ }
2129
+ if (["transpose", "velocityOffset", "quantize"].some((k) => patch[k] !== undefined)) {
2130
+ scope.assertWritable([clip]);
2131
+ }
2132
+ applyMidiRegionPatch(clip, patch);
1644
2133
  if (patch.hidden !== undefined) {
1645
2134
  clip.hidden = patch.hidden;
1646
2135
  }
@@ -1651,19 +2140,52 @@ const OP_HANDLERS = {
1651
2140
  clip.locked = patch.locked;
1652
2141
  }
1653
2142
  if (patch.textStyle !== undefined) {
1654
- const parsed = textStyleParams.safeParse({
1655
- color: DEFAULT_TEXT_CLIP_COLOR,
1656
- ...clip.textStyle,
1657
- ...patch.textStyle
1658
- });
1659
- if (!parsed.success) {
1660
- throw new Error(`Clip "${clip.name}" has no text style yet, so this patch still needs ${parsed.error.issues.map((issue) => issue.path.join(".")).join(", ")}.`);
2143
+ const parsedPatch = textStylePatchParams.safeParse(patch.textStyle);
2144
+ if (!parsedPatch.success) {
2145
+ throw new Error(`Invalid textStyle on clip "${clip.name}": ${parsedPatch.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`);
2146
+ }
2147
+ if (typeof parsedPatch.data.fontFamily === "string") {
2148
+ assertAuthorableFontFamily(parsedPatch.data.fontFamily);
2149
+ }
2150
+ if (!clip.textStyle) {
2151
+ const created = {
2152
+ color: DEFAULT_TEXT_CLIP_COLOR
2153
+ };
2154
+ for (const [key, value] of Object.entries(parsedPatch.data)) {
2155
+ if (value !== undefined && value !== null) {
2156
+ created[key] = value;
2157
+ }
2158
+ }
2159
+ const parsedFull = textStyleParams.safeParse(created);
2160
+ if (!parsedFull.success) {
2161
+ throw new Error(`Clip "${clip.name}" has no text style yet, so this patch still needs ${parsedFull.error.issues.map((issue) => issue.path.join(".")).join(", ")}.`);
2162
+ }
2163
+ clip.textStyle = parsedFull.data;
2164
+ }
2165
+ else {
2166
+ const merged = {
2167
+ ...clip.textStyle
2168
+ };
2169
+ for (const key of Object.keys(parsedPatch.data)) {
2170
+ const value = parsedPatch.data[key];
2171
+ if (value === undefined)
2172
+ continue;
2173
+ if (value === null) {
2174
+ delete merged[key];
2175
+ }
2176
+ else {
2177
+ Object.assign(merged, { [key]: value });
2178
+ }
2179
+ }
2180
+ clip.textStyle = merged;
1661
2181
  }
1662
- assertAuthorableFontFamily(parsed.data.fontFamily);
1663
- clip.textStyle = parsed.data;
1664
2182
  }
1665
2183
  if (patch.shapeStyle !== undefined) {
1666
- clip.shapeStyle = shapeStyleWithDefaults(patch.shapeStyle);
2184
+ const parsed = shapeStyleParams.safeParse(patch.shapeStyle);
2185
+ if (!parsed.success) {
2186
+ throw new Error(`Invalid shapeStyle on clip "${clip.name}": ${parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`);
2187
+ }
2188
+ clip.shapeStyle = shapeStyleWithDefaults(parsed.data);
1667
2189
  }
1668
2190
  if (patch.captionStyle !== undefined) {
1669
2191
  // The style rides on the clip's caption, so a clip with no words to
@@ -1672,7 +2194,20 @@ const OP_HANDLERS = {
1672
2194
  if (!clip.caption) {
1673
2195
  throw new Error(`Clip "${clip.name}" carries no caption to style.`);
1674
2196
  }
1675
- clip.caption = { ...clip.caption, style: patch.captionStyle };
2197
+ const parsedPatch = captionStyleParams.safeParse(patch.captionStyle);
2198
+ if (!parsedPatch.success) {
2199
+ throw new Error(`Invalid captionStyle on clip "${clip.name}": ${parsedPatch.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`);
2200
+ }
2201
+ if (parsedPatch.data.fontFamily !== undefined) {
2202
+ assertAuthorableFontFamily(parsedPatch.data.fontFamily);
2203
+ }
2204
+ const merged = { ...clip.caption.style };
2205
+ for (const [key, value] of Object.entries(parsedPatch.data)) {
2206
+ if (value !== undefined) {
2207
+ merged[key] = value;
2208
+ }
2209
+ }
2210
+ clip.caption = { ...clip.caption, style: merged };
1676
2211
  }
1677
2212
  scope.touch(clip.id);
1678
2213
  return { ok: true, clip: scope.clipOut(clip) };
@@ -2142,6 +2677,10 @@ const OP_HANDLERS = {
2142
2677
  // Through the same ops the caller would use: a group carries its
2143
2678
  // children (D4) and a trim carries the source points, neither of
2144
2679
  // which a raw startMs/durationMs write does.
2680
+ // A failed snap leaves the document as it was, an unroll included.
2681
+ const savedClips = [...scope.clips];
2682
+ const savedMediaTracks = scope.mediaTracks;
2683
+ const savedChanged = new Set(scope.changed);
2145
2684
  try {
2146
2685
  if (entry.after.durationMs === entry.before.durationMs) {
2147
2686
  scope.applyMove(clip, { startMs: entry.after.startMs });
@@ -2163,6 +2702,10 @@ const OP_HANDLERS = {
2163
2702
  }
2164
2703
  }
2165
2704
  catch (error) {
2705
+ scope.clips = savedClips;
2706
+ scope.mediaTracks = savedMediaTracks;
2707
+ scope.changed.clear();
2708
+ savedChanged.forEach((id) => scope.changed.add(id));
2166
2709
  return {
2167
2710
  ...entry,
2168
2711
  snapped: false,
@@ -2436,17 +2979,29 @@ const OP_HANDLERS = {
2436
2979
  scope.touch(clip.id);
2437
2980
  return { ok: true, clip: scope.clipOut(clip) };
2438
2981
  },
2439
- set_notes: (scope, op) => {
2440
- const clip = scope.resolveMidiClip(op.clip);
2441
- scope.assertWritable([clip]);
2442
- clip.notes = scope.buildNotes(op.notes, clip.name);
2443
- scope.touch(clip.id);
2444
- return { ok: true, clip: scope.clipOut(clip) };
2445
- },
2982
+ set_notes: (scope, op) => runSetNotes(scope, op),
2446
2983
  set_track: (scope, op) => {
2984
+ if (op.automationEdit) {
2985
+ if (Object.entries(op).some(([key, value]) => !["op", "track", "automationEdit"].includes(key) &&
2986
+ value !== undefined)) {
2987
+ throw new Error("automationEdit must be sent alone with track.");
2988
+ }
2989
+ const track = scope.resolveTrack(op.track);
2990
+ runAutomationEdit(track, op.automationEdit, () => scope.ctx.newId("lane"));
2991
+ return { ok: true, track: scope.trackOut(track) };
2992
+ }
2993
+ // `master` names the master bus, unless a track carries that id or name.
2994
+ const lowerTrack = op.track.toLowerCase();
2995
+ const hasMatchingTrack = scope.tracks.some((t) => t.id === op.track || t.name.toLowerCase() === lowerTrack);
2996
+ if (lowerTrack === "master" && !hasMatchingTrack) {
2997
+ return runSetMaster(scope, op);
2998
+ }
2447
2999
  const track = scope.resolveTrack(op.track);
2448
3000
  // Unlocking is the one change a locked track takes; everything else waits for it.
2449
- const others = Object.keys(op).filter((key) => key !== "op" && key !== "track" && key !== "locked");
3001
+ const others = Object.keys(op).filter((key) => key !== "op" &&
3002
+ key !== "track" &&
3003
+ key !== "locked" &&
3004
+ op[key] !== undefined);
2450
3005
  if (track.locked && op.locked !== false && others.length > 0) {
2451
3006
  throw new Error(`Track "${track.name}" is locked. Send locked: false first, then change ${others.join(", ")}.`);
2452
3007
  }
@@ -2469,6 +3024,7 @@ const OP_HANDLERS = {
2469
3024
  track.pan = op.pan;
2470
3025
  if (op.heightPx !== undefined)
2471
3026
  track.heightPx = Math.round(op.heightPx);
3027
+ runSetTrackMix(scope, track, op);
2472
3028
  return { ok: true, track: scope.trackOut(track) };
2473
3029
  },
2474
3030
  ripple_delete: (scope, op) => {
@@ -2537,28 +3093,63 @@ const OP_HANDLERS = {
2537
3093
  return { ok: true, ...commitRipple(scope, out.clips) };
2538
3094
  },
2539
3095
  set_tempo: (scope, op) => {
3096
+ const hasTempoField = op.bpm !== undefined ||
3097
+ op.offset_ms !== undefined ||
3098
+ op.beats_per_bar !== undefined ||
3099
+ op.beat_unit !== undefined ||
3100
+ op.key !== undefined;
3101
+ if (!hasTempoField && op.auto_crossfade_ms === undefined) {
3102
+ throw new Error("Send bpm, offset_ms, beats_per_bar, beat_unit, key, or auto_crossfade_ms.");
3103
+ }
2540
3104
  const previous = resolveTempo(scope.state);
2541
3105
  const tempo = {
2542
- bpm: op.bpm,
3106
+ bpm: op.bpm ?? previous.bpm,
2543
3107
  offsetMs: op.offset_ms ?? previous.offsetMs,
2544
3108
  timeSignature: {
2545
3109
  beatsPerBar: op.beats_per_bar ?? previous.timeSignature.beatsPerBar,
2546
3110
  beatUnit: op.beat_unit ?? previous.timeSignature.beatUnit
2547
- }
3111
+ },
3112
+ // A tempo change keeps the project key unless `key` names another.
3113
+ ...(op.key === undefined
3114
+ ? previous.key
3115
+ ? { key: previous.key }
3116
+ : {}
3117
+ : op.key === null
3118
+ ? {}
3119
+ : { key: op.key })
2548
3120
  };
2549
- scope.clips = rescaleClipsForTempo(scope.clips, scope.tracks, previous, tempo);
2550
- scope.state.tempo = tempo;
2551
- const rescaledClipIds = scope.clips
2552
- .filter((c) => c.mediaType === "midi")
2553
- .map((c) => c.id);
2554
- scope.touch(...rescaledClipIds);
3121
+ const refusal = tempoChangeRefusal({ tempo: scope.state.tempo, music: scope.state.music, clips: scope.clips }, tempo);
3122
+ if (refusal) {
3123
+ throw new Error(refusal);
3124
+ }
3125
+ if (op.auto_crossfade_ms !== undefined && !scope.state.music) {
3126
+ throw new Error("auto_crossfade_ms only applies to a music project.");
3127
+ }
3128
+ const timingRescaled = previous.bpm !== tempo.bpm || previous.offsetMs !== tempo.offsetMs;
3129
+ let rescaledClipIds = [];
3130
+ if (timingRescaled) {
3131
+ scope.clips = rescaleClipsForTempo(scope.clips, scope.tracks, previous, tempo);
3132
+ rescaledClipIds = scope.clips
3133
+ .filter((c) => c.mediaType === "midi")
3134
+ .map((c) => c.id);
3135
+ scope.touch(...rescaledClipIds);
3136
+ }
3137
+ if (hasTempoField) {
3138
+ scope.state.tempo = tempo;
3139
+ }
3140
+ if (op.auto_crossfade_ms !== undefined && scope.state.music) {
3141
+ scope.state.music = {
3142
+ ...scope.state.music,
3143
+ autoCrossfadeMs: op.auto_crossfade_ms
3144
+ };
3145
+ }
2555
3146
  return { ok: true, tempo, previousTempo: previous, rescaledClipIds };
2556
3147
  },
2557
3148
  set_track_instrument: async (scope, op) => {
2558
3149
  const track = scope.resolveMidiTrack(op.track);
2559
3150
  scope.assertWritable([], track.id);
2560
3151
  let instrument;
2561
- if ("preset" in op.instrument) {
3152
+ if (!("type" in op.instrument)) {
2562
3153
  const preset = findInstrumentPreset(op.instrument.preset);
2563
3154
  if (!preset) {
2564
3155
  throw new Error(`No instrument preset named "${op.instrument.preset}". Valid presets: ${MIDI_INSTRUMENT_PRESETS.map((p) => `${p.id} ("${p.name}")`).join(", ")}.`);
@@ -2586,6 +3177,21 @@ const OP_HANDLERS = {
2586
3177
  },
2587
3178
  transpose_clip: runMidiNoteEdit,
2588
3179
  quantize_notes: runMidiNoteEdit,
3180
+ set_chords: (scope, op) => runSetChords(scope, op),
3181
+ clear_chords: (scope, op) => runClearChords(scope, op),
3182
+ loop_clip: (scope, op) => runLoopClip(scope, op),
3183
+ join_clips: (scope, op) => runJoinClips(scope, op),
3184
+ insert_time: (scope, op) => runInsertTime(scope, op),
3185
+ delete_time: (scope, op) => runDeleteTime(scope, op),
3186
+ duplicate_range: (scope, op) => runDuplicateRange(scope, op),
3187
+ paste_range: (scope, op) => runPasteRange(scope, op),
3188
+ list_progressions: () => runListProgressions(),
3189
+ apply_progression: (scope, op) => runApplyProgression(scope, op),
3190
+ transpose_chords: (scope, op) => runTransposeChords(scope, op),
3191
+ detect_chords: (scope, op) => runDetectChords(scope, op),
3192
+ set_clip_harmony: (scope, op) => runSetClipHarmony(scope, op),
3193
+ list_harmony_presets: () => runListHarmonyPresets(),
3194
+ fit_notes_to_chords: (scope, op) => runFitNotesToChords(scope, op),
2589
3195
  scale_velocity: runMidiNoteEdit,
2590
3196
  set_reframe_subject: (scope, op) => {
2591
3197
  const clip = scope.resolveClip(op.clip_id);
@@ -2755,7 +3361,9 @@ const OP_HANDLERS = {
2755
3361
  Object.assign(scope.state, outcome.state);
2756
3362
  scope.touch(...outcome.changedClipIds);
2757
3363
  return outcome.result;
2758
- }
3364
+ },
3365
+ ...STEP_PATTERN_OP_HANDLERS,
3366
+ ...PLUGIN_OP_HANDLERS
2759
3367
  };
2760
3368
  /** Dispatch one op against `scope`. Throws on refusal; the caller maps it. */
2761
3369
  async function runOp(scope, op) {
@@ -2769,7 +3377,12 @@ async function runOp(scope, op) {
2769
3377
  function cloneState(state) {
2770
3378
  return {
2771
3379
  ...state,
2772
- tempo: state.tempo,
3380
+ tempo: state.tempo ? structuredClone(state.tempo) : state.tempo,
3381
+ music: state.music ? structuredClone(state.music) : state.music,
3382
+ master: state.master ? structuredClone(state.master) : state.master,
3383
+ trackFolders: state.trackFolders
3384
+ ? structuredClone(state.trackFolders)
3385
+ : state.trackFolders,
2773
3386
  setup: state.setup ? structuredClone(state.setup) : state.setup,
2774
3387
  fps: state.fps,
2775
3388
  width: state.width,