-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrackerManager.lua
More file actions
1533 lines (1373 loc) · 56.6 KB
/
trackerManager.lua
File metadata and controls
1533 lines (1373 loc) · 56.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- See docs/trackerManager.md for the model.
--invariant: tm holds (ppqL, raw) per event; mm holds raw; column events expose evt.ppq as logical. Rebuild reconciles raw ↔ ppqL each pass; see docs/timing.md
--invariant: detune is intent (per-note); pb is realisation (channel-wide stream); only lane-1 notes drive detune realisation
--invariant: pb.val is cents inside um; raw conversion happens only on load (rawToCents) and at flush (centsToRaw); cents window is cm:get('pbRange') * 100 per side
--invariant: fake pbs are absorbers seated at lane-1 note onsets to absorb detune jumps; pb.fake is the sole marker (persisted as cc metadata via mm sidecar)
--invariant: pa events store pitch-aftertouch value in mm cc.vel; col.events project as { type='pa', vel, ... } with the cc-routing fields stripped
--invariant: loc values are valid only within a single rebuild-to-flush window; um's notesByLoc/ccsByLoc are rebuilt fresh each rebuild
--invariant: column events are sorted by logical ppq; endppq carries no delay (delay shifts only the note-on)
--invariant: 16 channels always present; channels[i] non-nil for i in 1..16 after rebuild
--shape: channel = { chan=1..16, columns = { notes=[col,...], ccs={[ccNum]=col,...}, pc=col|nil, pb=col|nil, at=col|nil } }
--shape: column = { events=[evt,...], [cc=ccNum] } -- events sorted by logical ppq
--shape: noteEvent = { ppq, endppq, pitch, vel, lane, detune, delay, [muted], [sample], [sampleShadowed], loc, [<metadata...>] }
--shape: pbEventCol = { ppq, val=cents-minus-detune, detune, hidden, [delay], [shape], [tension], loc, ... } -- column projection; um cache holds raw cents in val
--shape: paEventCol = { type='pa', ppq, pitch, vel, loc, ... } -- mixed into note column events
--shape: extraColumns[chan] = { notes=count, [pc=true], [pb=true], [at=true], [ccs={[ccNum]=true}] }
--shape: lastMuteSet = { [chan] = true }, pushed by tv via tm:setMutedChannels
local util = require 'util'
local timing = require 'timing'
local tuning = require 'tuning'
local function print(...)
return util.print(...)
end
local mm, cm = (...).mm, (...).cm
local tm = {}
local fire = util.installHooks(tm)
---------- STATE
local channels = {}
local lastMuteSet = {}
--invariant: pendingFlushUuids: uuid-set of notes touched by the in-flight flush; read by allocateNoteColumn to attribute lane overlaps; nil outside a flush-driven rebuild
local pendingFlushUuids
--invariant: staleSwing[chan]=true: this channel's resolved swing changed; rebuild rule rederives raw from ppqL and clears
local staleSwing = {}
--invariant: swingSnap caches the (cm, mm)-derived swing transforms; nil
-- means "needs rebuild". Invalidated at the head of every tm:rebuild —
-- the sole synchronisation point at which mm/cm read coherently.
local swingSnap
---------- SHARED HELPERS
local function sortByPPQ(tbl)
table.sort(tbl, function(a, b) return a.ppq < b.ppq end)
end
local function centsToRaw(cents)
local lim = cm:get('pbRange') * 100
return util.clamp(util.round(cents * 8192 / lim), -8192, 8191)
end
local function rawToCents(raw)
local lim = cm:get('pbRange') * 100
return util.round(raw / 8192 * lim)
end
local function delayToPPQ(d) return timing.delayToPPQ(d, mm:resolution()) end
local function forEachEvent(fn)
for i=1,16 do
local channel = channels[i]
if channel then
local chan, cols = channel.chan, channel.columns
-- Note branch carries lane (column events strip it; see util.clone at row clone).
for lane, col in ipairs(cols.notes) do
for _, evt in ipairs(col.events) do
local isNote = evt.type ~= 'pa'
fn(isNote and 'note' or 'pa', evt, chan, isNote, nil, lane)
end
end
for _, t in ipairs{'pb', 'at', 'pc'} do
if cols[t] then
for _, evt in ipairs(cols[t].events) do fn(t, evt, chan, false) end
end
end
-- cc branch carries ccNum: column events have cc stripped (see CC_PROJECT_STRIP), so callers needing the cc number get it from the column key.
for ccNum, col in pairs(cols.ccs) do
for _, evt in ipairs(col.events) do fn('cc', evt, chan, false, ccNum) end
end
end
end
end
--contract: synthesised PCs carry fake=true and inherit ppqL from the winning host-note record; an existing fake PC matching (ppq, val) is kept (omitted from both toRemove and toAdd), preserving its mm-side loc across rebuilds where val did not change
--contract: if record.key is set, marks key.sampleShadowed=true on records lost to lane priority; returns (toRemove, toAdd) for the caller to persist. Shadow marking is rebuild-only — flush-time callers omit key since lane events are reclone'd by the rebuild that follows. c.pc.events is not written here; rebuild's CC walk refreshes it from mm after the caller's commit.
local function reconcilePCsForChan(chan, records)
local existing = (channels[chan].columns.pc and channels[chan].columns.pc.events) or {}
local byPpq = {}
local groups = {}
for _, e in ipairs(existing) do byPpq[e.ppq] = e end
for _, r in ipairs(records) do util.bucket(groups, r.ppq, r) end
local toRemove, toAdd, kept = {}, {}, {}
for ppq, g in pairs(groups) do
table.sort(g, function(a, b) return a.lane < b.lane end)
local w = g[1]
local have = byPpq[ppq]
if have and have.fake and have.val == w.sample then
kept[have] = true
else
util.add(toAdd, { ppq = ppq, ppqL = w.ppqL, val = w.sample,
evType = 'pc', chan = chan, fake = true })
end
for i = 2, #g do
if g[i].key then g[i].key.sampleShadowed = true end
end
end
for _, have in ipairs(existing) do
if not kept[have] then util.add(toRemove, have) end
end
return toRemove, toAdd
end
---------- UPDATE MANAGER
local addEvent, assignEvent, deleteEvent, flush, reload do
----- State
local adds = {}
local assigns = {}
local deletes = {}
local chans = {}
local byToken = {}
local dirtyPcChans = {}
----- Accessors
local function owner(chan, P)
return util.seek(chans[chan].notes, 'at-or-before', P, function(n) return n.endppq > P end)
end
local function detuneAt(chan, P)
local n = util.seek(chans[chan].notes, 'at-or-before', P)
return (n and n.detune) or 0
end
local function detuneBefore(chan, P)
local n = util.seek(chans[chan].notes, 'before', P)
return (n and n.detune) or 0
end
local function rawAt(chan, P)
local pb = util.seek(chans[chan].pbs, 'at-or-before', P)
return pb and pb.val or 0
end
local function rawBefore(chan, P)
local pb = util.seek(chans[chan].pbs, 'before', P)
return pb and pb.val or 0
end
local function pbAt(chan, P)
local pb = util.seek(chans[chan].pbs, 'at-or-before', P)
return pb and pb.ppq == P and pb or nil
end
--contract: logical = raw − detune; this is the "user heard pitch" frame, decoupled from the absorber bookkeeping
local function logicalAt(chan, P)
return rawAt(chan, P) - detuneAt(chan, P)
end
local function logicalBefore(chan, P)
return rawBefore(chan, P) - detuneBefore(chan, P)
end
local function nextRealChange(chan, P)
local pb = util.seek(chans[chan].pbs, 'after', P, function(e) return not e.fake end)
return (pb and pb.ppq) or math.huge
end
local function nextNotePPQ(chan, P)
local n = util.seek(chans[chan].notes, 'after', P)
return (n and n.ppq) or math.huge
end
local function forEachAttachedPA(host, fn)
for _, cc in pairs(byToken) do
if cc.evType == 'pa' and cc.chan == host.chan and cc.pitch == host.pitch
and cc.ppq >= host.ppq and cc.ppq < host.endppq then
fn(cc)
end
end
end
----- Low-level mutation
--contract: only lane==1 notes index into chans[chan].notes; higher-lane notes get queued for mm but don't feed detune/realisation reads. Caller supplies evt.evType.
local function addLowlevel(evt)
local et = evt.evType
if et == 'note' then
if evt.lane == 1 then
local tbl = chans[evt.chan].notes
util.add(tbl, evt); sortByPPQ(tbl)
end
elseif et == 'pb' then
local tbl = chans[evt.chan].pbs
util.add(tbl, evt); sortByPPQ(tbl)
end
util.add(adds, { evt = evt })
end
--contract: dedupes by token (unique across types) so multiple in-flight assigns to the same event collapse into one mm write; util.REMOVE markers must survive merging
local function assignLowlevel(evt, update)
util.assign(evt, update)
-- ppq mutates in place; resort so subsequent util.seek calls keyed off chans[chan].notes stay correct under non-monotone callers (reswing).
if evt.evType == 'note' and update.ppq ~= nil and evt.lane == 1 then
sortByPPQ(chans[evt.chan].notes)
end
if not evt.token then return end
for _, e in ipairs(assigns) do
if e.token == evt.token then
-- Plain copy, not util.assign: util.assign collapses util.REMOVE → nil-the-key.
for k, v in pairs(update) do e.update[k] = v end
return
end
end
util.add(assigns, { token = evt.token, update = update, evt = evt })
end
local function deleteLowlevel(evt)
local et = evt.evType
local tbl
if et == 'note' then
tbl = chans[evt.chan].notes
elseif et == 'pb' then
tbl = chans[evt.chan].pbs
end
if tbl then
for i, item in ipairs(tbl) do
if item == evt then
table.remove(tbl, i)
break
end
end
end
local token = evt.token
if token then
byToken[token] = nil
util.add(deletes, { token = token })
for j = #assigns, 1, -1 do
if assigns[j].token == token then table.remove(assigns, j) end
end
else
for j = #adds, 1, -1 do
if adds[j].evt == evt then table.remove(adds, j); break end
end
end
end
--contract: shifts every pb's raw val by delta over [P1, P2); preserves logical stream above by definition since detune absorbs delta
local function retuneLowlevel(chan, P1, P2, delta)
if delta == 0 then return end
for _, pb in ipairs(chans[chan].pbs) do
if pb.ppq >= P1 and pb.ppq < P2 then
assignLowlevel(pb, { val = pb.val + delta })
end
end
end
--contract: no-op (returns false) if a pb already sits at P; otherwise seats one at the carrier value (rawAt) so logical stream is preserved
local function forcePb(chan, P, extras)
if pbAt(chan, P) then return false end
addLowlevel(util.assign({ ppq = P, chan = chan, val = rawAt(chan, P), evType = 'pb' }, extras))
return true
end
local function markFake(chan, P)
local pb = pbAt(chan, P)
if pb then assignLowlevel(pb, { fake = true }) end
end
local function unmarkFake(chan, P)
local pb = pbAt(chan, P)
if not (pb and pb.fake) then return end
assignLowlevel(pb, { fake = util.REMOVE })
end
-- Callers invoke post-mutation (note edits committed) so detuneAt/Before see live values.
local function reconcileBoundary(chan, P)
if P >= math.huge then return end
local D, C = detuneAt(chan, P), detuneBefore(chan, P)
local pb = pbAt(chan, P)
if D == C then
if pb and pb.fake and rawAt(chan, P) == rawBefore(chan, P) then
deleteLowlevel(pb)
end
elseif not pb then
forcePb(chan, P) -- val = rawAt = rawBefore (no pb yet)
markFake(chan, P)
pb = pbAt(chan, P)
assignLowlevel(pb, { val = pb.val + (D - C) })
end
end
----- High-level ops
--contract: authoring frame is logical (pb.val is logical cents); seats/updates the carrier and retunes forward to next real pb so logical above is preserved
local function addPb(pb)
local chan, P, L = pb.chan, pb.ppq, pb.val or 0
local delta = L - logicalAt(chan, P)
-- chan/ppq/val belong to forcePb's structural set; evType comes through the literal.
local extras = util.clone(pb,
{ chan = true, ppq = true, val = true, evType = true })
if not next(extras) then extras = nil end
if not forcePb(chan, P, extras) then
if extras then assignLowlevel(pbAt(chan, P), extras) end
unmarkFake(chan, P)
end
retuneLowlevel(chan, P, nextRealChange(chan, P), delta)
end
--contract: retunes forward to undo pb's logical contribution; collapses to a real delete only if the seat would also be redundant as a fake (detuneAt == detuneBefore)
local function deletePb(pb)
local chan, P = pb.chan, pb.ppq
retuneLowlevel(chan, P, nextRealChange(chan, P), logicalBefore(chan, P) - logicalAt(chan, P))
if detuneAt(chan, P) == detuneBefore(chan, P) then
deleteLowlevel(pb)
else
if owner(chan, P) then markFake(chan, P) end
end
end
local function assignPb(pb, update)
if update.ppq and update.ppq ~= pb.ppq then
local chan, oldP, newP = pb.chan, pb.ppq, update.ppq
local oldL = logicalAt(chan, oldP)
local newL = update.val ~= nil and update.val or oldL
-- Two cases need a true destroy/create on the mm stream and fall
-- through to deletePb+addPb: a non-self pb already sits at newP
-- (typically a fake absorber to be merged in), or oldP needs a
-- fresh fake born to absorb a detune jump after we leave.
local existing = pbAt(chan, newP)
local needFakeAtOld = (detuneAt(chan, oldP) ~= detuneBefore(chan, oldP))
and owner(chan, oldP)
if (existing and existing ~= pb) or needFakeAtOld then
local extras = util.clone(pb, { token = true, fake = true,
chan = true, ppq = true, val = true,
evType = true })
util.assign(extras, util.clone(update, { ppq = true, val = true }))
deletePb(pb)
addPb(util.assign({ chan = chan, ppq = newP, val = newL }, extras))
return
end
-- In-place move. Mirror deletePb's retune over [oldP, nextRealOld)
-- to revert the pb's old contribution (this also bumps pb itself
-- to a passthrough val); then mutate ppq+val+metadata in one
-- assignLowlevel; then mirror addPb's retune over [newP, nextRealNew)
-- to lift pb to its new logical value. mm-side identity (uuid,
-- sidecar, idx) survives the move.
retuneLowlevel(chan, oldP, nextRealChange(chan, oldP),
logicalBefore(chan, oldP) - oldL)
local carrierAtNew = rawAt(chan, newP)
local moveUpdate = util.clone(update)
moveUpdate.ppq = newP
moveUpdate.val = carrierAtNew
assignLowlevel(pb, moveUpdate)
sortByPPQ(chans[chan].pbs)
retuneLowlevel(chan, newP, nextRealChange(chan, newP),
newL - logicalAt(chan, newP))
return
end
if update.val then
local chan, P = pb.chan, pb.ppq
local delta = update.val - logicalAt(chan, P)
unmarkFake(chan, P)
retuneLowlevel(chan, P, nextRealChange(chan, P), delta)
end
local rest = util.clone(update, { val = true, ppq = true })
if next(rest) then assignLowlevel(pb, rest) end
end
local function dirtyPc(chan) dirtyPcChans[chan] = true end
--contract: lane-1 path: seat fake-pb if detune jumps the carry, retune forward to next note, then reconcile the next-note boundary; lane>1 just queues with no realisation work
local function addNote(n)
dirtyPc(n.chan)
local D = n.detune
if lastMuteSet[n.chan] then n.muted = true end
if n.lane == 1 then
local C = detuneAt(n.chan, n.ppq)
local nextP = nextNotePPQ(n.chan, n.ppq)
if D ~= C and forcePb(n.chan, n.ppq) then markFake(n.chan, n.ppq) end
retuneLowlevel(n.chan, n.ppq, nextP, D - C)
addLowlevel(util.assign(n, { detune = D }))
reconcileBoundary(n.chan, nextP)
else
addLowlevel(util.assign(n, { detune = D }))
end
end
--contract: attached PAs are deleted with the host unless keepPAs; lane-1 path drops any fake seat at n.ppq and retunes back to the prior detune over [n.ppq, nextNote)
local function deleteNote(n, keepPAs)
dirtyPc(n.chan)
if not keepPAs then forEachAttachedPA(n, function(evt) deleteLowlevel(evt) end) end
if n.lane ~= 1 then deleteLowlevel(n); return end
local D1, D2 = detuneBefore(n.chan, n.ppq), detuneAt(n.chan, n.ppq)
local nextP = nextNotePPQ(n.chan, n.ppq)
local pb = pbAt(n.chan, n.ppq)
if pb and pb.fake then deleteLowlevel(pb) end
deleteLowlevel(n)
retuneLowlevel(n.chan, n.ppq, nextP, D1 - D2)
reconcileBoundary(n.chan, nextP)
end
local function resizeNote(n, P1, P2)
local col1 = n.lane == 1
local shift = P1 - n.ppq
if shift ~= 0 and P2 - n.endppq == shift then
forEachAttachedPA(n, function(evt)
assignLowlevel(evt, { ppq = evt.ppq + shift })
end)
else
local lastPA
forEachAttachedPA(n, function(evt)
if evt.ppq <= P1 or evt.ppq >= P2 then
if evt.ppq <= P1 and (not lastPA or evt.ppq > lastPA.ppq) then lastPA = evt end
deleteLowlevel(evt)
end
end)
if lastPA then assignLowlevel(n, { vel = lastPA.vel }) end
end
if not col1 then
assignLowlevel(n, { ppq = P1, endppq = P2 })
return
end
-- col-1: withdraw detune at old seat, move, reapply at new. L is the
-- logical pb the user authored at P1 *before* the move — if it
-- differs from prevailing logical there we seat a real pb to carry it.
local oldppq = n.ppq
local D = n.detune
local L = logicalAt(n.chan, P1)
local C1 = detuneBefore(n.chan, oldppq)
local NP1 = nextNotePPQ(n.chan, oldppq)
local oldPb = pbAt(n.chan, oldppq)
assignLowlevel(n, { ppq = P1, endppq = P2 })
if oldPb and oldPb.fake then
deleteLowlevel(oldPb)
end
retuneLowlevel(n.chan, oldppq, NP1, C1 - D)
-- The carry into NP1 has shifted from D to C1 (n no longer
-- bridges); a previously-masked jump may now need its own
-- absorber, or a previously-needed one may have collapsed.
reconcileBoundary(n.chan, NP1)
-- New seat: real pb wins over fake; pre-existing pb wins over
-- both. logicalBefore(P1) is read after the boundary at NP1
-- has been reconciled — placing the absorber there can change
-- rawBefore at P1 in leapfrog moves.
local C2 = detuneBefore(n.chan, P1)
if L ~= logicalBefore(n.chan, P1) then
forcePb(n.chan, P1)
elseif D ~= C2 and forcePb(n.chan, P1) then
markFake(n.chan, P1)
end
local NP2 = nextNotePPQ(n.chan, P1)
retuneLowlevel(n.chan, P1, NP2, D - C2)
reconcileBoundary(n.chan, NP2)
end
--contract: chan/lane updates are rejected with a warning; ppq/endppq route through resizeNote; detune updates retune forward and reconcile both endpoint boundaries
local function assignNote(n, update)
if update.chan then print('um: not allowed to change channel of notes'); return end
if update.lane then print('um: not allowed to change lane of notes'); return end
-- update.ppq covers both direct ppq edits and delay edits
-- (realiseNoteUpdate maps delay→ppq before we get here). endppq
-- alone doesn't move the realised onset, so it doesn't dirty.
if update.sample ~= nil or update.ppq ~= nil then dirtyPc(n.chan) end
if update.ppq ~= nil or update.endppq ~= nil then
resizeNote(n, update.ppq or n.ppq, update.endppq or n.endppq)
update.ppq, update.endppq = nil, nil
end
if update.pitch then
forEachAttachedPA(n, function(e) assignLowlevel(e, { pitch = update.pitch }) end)
end
if n.lane == 1 and update.detune ~= nil and update.detune ~= n.detune then
local nextP = nextNotePPQ(n.chan, n.ppq)
if forcePb(n.chan, n.ppq) then markFake(n.chan, n.ppq) end
retuneLowlevel(n.chan, n.ppq, nextP, update.detune - n.detune)
-- Commit detune now so the boundary reconciliations below read
-- post-update state. Our own seat may collapse (detune now
-- matches prior); the next note's seat may flip either way —
-- a previously-absorbed jump may erase, or a previously-absent
-- jump may appear because the carry has shifted.
assignLowlevel(n, { detune = update.detune })
update.detune = nil
reconcileBoundary(n.chan, n.ppq)
reconcileBoundary(n.chan, nextP)
end
if next(update) then assignLowlevel(n, update) end
end
-- Returns (clampEnd, clampEndL): the realised end and its logical
-- counterpart. Truncated peers are stamped with endppqL = selfPpqL so
-- the canonical logical frame stays coherent with endppq.
local function clearSameKeyRange(chan, pitch, P, Pend, selfPpqL, selfEvt)
local clampEnd, clampEndL = Pend, nil
local toDelete, toTruncate = {}, {}
for _, n in pairs(byToken) do
if n.evType == 'note' and n ~= selfEvt and n.chan == chan and n.pitch == pitch then
if n.ppq <= P and n.endppq > P then
if n.ppq == P then util.add(toDelete, n)
else util.add(toTruncate, n) end
elseif clampEnd and n.ppq > P and n.ppq < clampEnd then
clampEnd, clampEndL = n.ppq, n.ppqL
end
end
end
for _, n in ipairs(toDelete) do deleteNote(n) end
for _, n in ipairs(toTruncate) do
assignNote(n, { endppq = P, endppqL = selfPpqL })
end
return clampEnd, clampEndL
end
----- PC reconciliation (trackerMode mutation hook)
local function reconcilePcs(chan)
local records = {}
for _, n in pairs(byToken) do
if n.evType == 'note' and n.chan == chan then
util.add(records, { ppq = n.ppq, ppqL = n.ppqL, lane = n.lane,
sample = n.sample or 0 })
end
end
for _, a in ipairs(adds) do
if a.evt.evType == 'note' and a.evt.chan == chan then
local n = a.evt
util.add(records, { ppq = n.ppq, ppqL = n.ppqL, lane = n.lane,
sample = n.sample or 0 })
end
end
local toRemove, toAdd = reconcilePCsForChan(chan, records)
for _, have in ipairs(toRemove) do deleteLowlevel(have) end
for _, want in ipairs(toAdd) do addLowlevel(want) end
end
local function lookup(evtOrToken)
local token = type(evtOrToken) == 'table' and evtOrToken.token or evtOrToken
if not token then return end
return byToken[token], token
end
----- Public interface
function deleteEvent(evtOrToken)
local evt = lookup(evtOrToken)
if not evt then return end
local et = evt.evType
if et == 'note' then deleteNote(evt)
elseif et == 'pb' then deletePb(evt)
else deleteLowlevel(evt) end
end
--contract: update.ppq/endppq arrive logical; stamps ppqL/endppqL and rewrites ppq/endppq to raw. Caller-supplied update.ppqL/endppqL signals "raw already computed" — translation is skipped, only delay-delta applies. See docs/timing.md.
local function realiseNoteUpdate(evt, update)
local dOld = delayToPPQ(evt.delay)
local dNew = delayToPPQ(update.delay ~= nil and update.delay or evt.delay)
if update.ppq == nil and update.endppq == nil and dNew == dOld then return end
if update.ppqL ~= nil or update.endppqL ~= nil then
if update.ppq ~= nil then
update.ppq = update.ppq + dNew
elseif dNew ~= dOld then
update.ppq = evt.ppq + (dNew - dOld)
end
return
end
if update.ppq ~= nil then
update.ppqL = update.ppq
update.ppq = tm:fromLogical(evt.chan, update.ppqL, dNew)
elseif evt.ppqL ~= nil then
update.ppq = tm:fromLogical(evt.chan, evt.ppqL, dNew)
else
update.ppq = evt.ppq + (dNew - dOld)
end
if update.endppq ~= nil then
update.endppqL = update.endppq
update.endppq = tm:fromLogical(evt.chan, update.endppqL)
end
end
local function realiseNonNoteUpdate(chan, update)
if update.ppqL ~= nil then return end
if not chan or update.ppq == nil then return end
update.ppqL = update.ppq
update.ppq = tm:fromLogical(chan, update.ppqL)
end
local function realiseAddPpq(evt, withDelay, withEnd)
if evt.ppq == nil or not evt.chan then return end
evt.ppqL = evt.ppq
evt.ppq = tm:fromLogical(evt.chan, evt.ppqL,
withDelay and delayToPPQ(evt.delay or 0) or 0)
if withEnd and evt.endppq ~= nil then
evt.endppqL = evt.endppq
evt.endppq = tm:fromLogical(evt.chan, evt.endppqL)
end
end
function assignEvent(evtOrToken, update)
local evt = lookup(evtOrToken)
if not evt then return end
local et = evt.evType
if et == 'note' then
local rawCaller = update.ppqL ~= nil or update.endppqL ~= nil
realiseNoteUpdate(evt, update)
if not rawCaller
and (update.pitch ~= nil or update.ppq ~= nil or update.endppq ~= nil) then
local P = update.ppq or evt.ppq
local Pend = update.endppq or evt.endppq
local pitch = update.pitch or evt.pitch
local selfL = update.ppqL or evt.ppqL
local clamped, clampedL = clearSameKeyRange(evt.chan, pitch, P, Pend, selfL, evt)
if clamped ~= Pend then
update.endppq = clamped
update.endppqL = clampedL
end
end
assignNote(evt, update)
elseif et == 'pb' then
realiseNonNoteUpdate(evt.chan, update)
assignPb(evt, update)
else
realiseNonNoteUpdate(evt.chan, update)
assignLowlevel(evt, update)
end
end
--contract: notes default detune=0, delay=0, lane=1; evt.ppq/endppq arrive logical; stamps ppqL/endppqL and rewrites ppq/endppq to raw before mm. Caller-supplied evt.ppqL signals "raw already computed" — translation is skipped (mirrors assignEvent).
function addEvent(evt)
local rawCaller = evt.ppqL ~= nil
if evt.evType == 'note' then
evt.detune = evt.detune or 0
evt.delay = evt.delay or 0
evt.lane = evt.lane or 1
if not rawCaller then realiseAddPpq(evt, true, true) end
local clamped, clampedL =
clearSameKeyRange(evt.chan, evt.pitch, evt.ppq, evt.endppq, evt.ppqL, evt)
evt.endppq = clamped
if clampedL then evt.endppqL = clampedL end
addNote(evt)
else
if not rawCaller then realiseAddPpq(evt, false, false) end
if evt.evType == 'pb' then addPb(evt) else addLowlevel(evt) end
end
end
----- Flush: commit accumulated ops to mm.
--contract: no-op if nothing staged; otherwise commits assigns then deletes then adds under one mm:modify; pb cents→raw conversion happens here; byToken is re-keyed live from mm:assign's returned token whenever an identity field moved
--contract: snapshots adds/assigns/deletes before mm:modify so re-entry from mm callbacks (e.g. setMutedChannels via rebuild) cannot re-emit in-flight ops
function flush()
if cm:get('trackerMode') and next(dirtyPcChans) then
for chan in pairs(dirtyPcChans) do reconcilePcs(chan) end
dirtyPcChans = {}
end
if #adds == 0 and #assigns == 0 and #deletes == 0 then return end
local flushAdds, flushAssigns, flushDeletes = adds, assigns, deletes
adds, assigns, deletes = {}, {}, {}
for _, e in ipairs(flushAssigns) do
if e.evt.evType == 'pb' and e.update.val ~= nil then
e.update.val = centsToRaw(e.update.val)
end
end
for _, a in ipairs(flushAdds) do
if a.evt.evType == 'pb' then
a.evt.val = centsToRaw(a.evt.val)
end
end
-- Capture uuids of notes this flush touches, so the rebuild fired
-- from mm's reload can attribute over-threshold lane overlaps to us.
local touched = {}
for _, o in ipairs(flushAssigns) do
if o.evt.evType == 'note' and o.evt.uuid then touched[o.evt.uuid] = true end
end
pendingFlushUuids = touched
mm:modify(function()
for _, o in ipairs(flushAssigns) do
local newTok = mm:assign(o.token, o.update)
if newTok and newTok ~= o.token then
byToken[o.token] = nil
byToken[newTok] = o.evt
o.evt.token = newTok
end
end
for _, o in ipairs(flushDeletes) do
mm:delete(o.token)
byToken[o.token] = nil
end
for _, o in ipairs(flushAdds) do
local tok = mm:add(o.evt)
if tok then
byToken[tok] = o.evt
o.evt.token = tok
if o.evt.evType == 'note' and o.evt.uuid then touched[o.evt.uuid] = true end
end
end
end)
end
----- Init / reload: (re)load local cache from mm.
-- Also clears staging buffers: a rebuild must not carry un-flushed ops
-- across (their tokens may be stale for newly-added events), matching the
-- prior "fresh um per rebuild" semantics now that the um itself persists.
function reload()
adds, assigns, deletes = {}, {}, {}
dirtyPcChans = {}
byToken = {}
for i = 1, 16 do chans[i] = { notes = {}, pbs = {} } end
for tok, e in mm:events() do
local evt
if e.evType == 'pb' then
evt = util.pick(e, 'ppq ppqL chan shape tension fake frame',
{ val = rawToCents(e.val), token = tok, evType = 'pb' })
util.add(chans[evt.chan].pbs, evt)
else
evt = e
evt.token = tok
if evt.evType == 'note' and evt.lane == 1 then
util.add(chans[evt.chan].notes, evt)
end
end
byToken[tok] = evt
end
for i = 1, 16 do sortByPPQ(chans[i].notes); sortByPPQ(chans[i].pbs) end
end
reload()
end
---------- PUBLIC
----- Accessors
function tm:getChannel(chan) return channels and channels[chan] end
function tm:channels()
local i = 0
return function()
i = i + 1
local channel = channels[i]
if channel then
return i, channel
end
end
end
function tm:editCursor()
if not (mm and mm:take()) then return end
local editCursorTime = reaper.GetCursorPosition()
return reaper.MIDI_GetPPQPosFromProjTime(mm:take(), editCursorTime)
end
function tm:length() return mm and mm:length() or 0 end
function tm:resolution() return mm and mm:resolution() end
function tm:name() return mm and mm:name() end
function tm:setName(name) if mm then mm:setName(name) end end
function tm:timeSigs() return mm and mm:timeSigs() or {} end
function tm:interpolate(A, B, ppq) return mm and mm:interpolate(A, B, ppq) end
-- E_c: column is inner, global is outer (see docs/timing.md).
--contract: cached per-(cm, mm) pair; invalidated at rebuild head.
-- fromLogical returns rounded int + optional offset (raw ppqs are integer).
-- toLogical returns the raw float (ppqL is a float frame).
local clearSwing do
local swing = nil
local function currentSwing()
if not swing then
local global, column = nil, {}
if mm then
local length, ppqPerQN = mm:length() or 0, mm:resolution()
local function resolve(name)
local composite = timing.findShape(name, cm:get('swings'))
if timing.isIdentity(composite) or length <= 0 then return nil end
return timing.resolveComposite(composite, length, ppqPerQN)
end
global = resolve(cm:get('swing'))
for chan, name in pairs(cm:get('colSwing') or {}) do
column[chan] = resolve(name)
end
end
swing = {
fromLogical = function(chan, ppqL)
local ppqI = ppqL
local c = column[chan]
if c then ppqI = timing.eval(c, ppqI) end
if global then ppqI = timing.eval(global, ppqI) end
return ppqI
end,
toLogical = function(chan, ppqI)
local ppqL = ppqI
if global then ppqL = timing.invert(global, ppqL) end
local c = column[chan]
if c then ppqL = timing.invert(c, ppqL) end
return ppqL
end,
}
end
return swing
end
function tm:fromLogical(chan, ppqL, offset)
return util.round(currentSwing().fromLogical(chan, ppqL) + (offset or 0))
end
function tm:toLogical(chan, ppqI)
return currentSwing().toLogical(chan, ppqI)
end
function clearSwing()
swing = nil
end
end
--contract: chan==nil marks all 16 channels stale; otherwise just the named channel. Consumed by the rebuild rule on the next tm:rebuild, then cleared.
function tm:markSwingStale(chan)
if chan then staleSwing[chan] = true; return end
for i = 1, 16 do staleSwing[i] = true end
end
----- Mutation
function tm:deleteEvent(evt) deleteEvent(evt) end
function tm:addEvent(evt) addEvent(evt) end
function tm:assignEvent(evt, update) assignEvent(evt, update) end
function tm:flush() flush() end
----- Length
-- On shrink, notes spanning the boundary keep their onset and have endppq clamped.
function tm:setLength(newPpq)
if not mm then return end
local oldPpq = mm:length() or 0
if newPpq < oldPpq then
local kills, clamps = {}, {}
forEachEvent(function(_, evt, _, isNote)
if evt.ppq >= newPpq then
util.add(kills, evt)
elseif isNote and evt.endppq > newPpq then
util.add(clamps, evt)
end
end)
for _, evt in ipairs(kills) do deleteEvent(evt) end
for _, evt in ipairs(clamps) do assignEvent(evt, { endppq = newPpq }) end
flush()
end
if newPpq ~= oldPpq then mm:setLength(newPpq / mm:resolution()) end
end
-- Stretch the take to `newPpq` by linearly remapping the logical
-- frame: each event on logical row r ends up on row f·r where
-- f = newPpq/oldPpq. ppqL stamps scale by f; raw ppqs are
-- rederived through swing — so under non-identity swing raw
-- ppqs are not linearly scaled (rows are preserved instead, which
-- keeps reswing well-defined). Note delays scale by f. Frame stamps
-- (rpb, swing slot names) are untouched. No events are deleted.
function tm:rescaleLength(newPpq)
if not mm then return end
local oldPpq = mm:length() or 0
if oldPpq <= 0 or newPpq == oldPpq then
if newPpq ~= oldPpq then mm:setLength(newPpq / mm:resolution()) end
return
end
local f = newPpq / oldPpq
-- τ acts on logical positions; raw ppqs rederive through the current swing snapshot.
-- Events without ppqL fall back to τ on raw ppq (identical under identity swing).
-- slopeAt scales note delays so realised stretch tracks logical stretch locally.
-- Two passes (gather, then mutate) so all reads are stable.
local function applyTimeMap(tau, slopeAt)
local plans = {}
forEachEvent(function(_, evt, chan, isNote)
local p = { evt = evt }
if evt.ppqL ~= nil then
p.newPpqL = tau(evt.ppqL)
p.newPpq = tm:fromLogical(chan, p.newPpqL)
else
p.newPpq = util.round(tau(evt.ppq))
end
if isNote then
if evt.endppqL ~= nil then
p.newEndppqL = tau(evt.endppqL)
p.newEndppq = tm:fromLogical(chan, p.newEndppqL)
else
p.newEndppq = util.round(tau(evt.endppq))
end
if evt.delay and evt.delay ~= 0 then
p.newDelay = slopeAt(evt.ppqL or evt.ppq) * evt.delay
end
end
util.add(plans, p)
end)
for _, p in ipairs(plans) do
assignEvent(p.evt, {
ppq = p.newPpq,
endppq = p.newEndppq,
delay = p.newDelay,
ppqL = p.newPpqL,
endppqL = p.newEndppqL,
})
end
flush()
end
applyTimeMap(function(t) return f * t end, function() return f end)
mm:setLength(newPpq / mm:resolution())
end
-- Loop the existing pattern to fill `newPpq`. The events in [0, oldPpq)
-- are replicated at offsets k·oldPpq for k = 1 .. ceil(newPpq/oldPpq)-1.
-- Copies whose shifted ppq lands at-or-past newPpq are dropped; note
-- endppqs that extend past newPpq are clamped. Originals are untouched.
-- Shrinks fall through to setLength.
--
-- Walks mm-level events directly rather than column-projected ones:
-- the projection strips fields a verbatim replica needs (cc number,
-- pb fake flag, custom user metadata). For pbs this means the copied
-- stream recreates the source's pitch trajectory exactly — including
-- whatever carry it inherits from the end of the prior tile.
--
-- Because oldPpq sits on a swing-period boundary (take length aligns
-- to QN), shifting by k·oldPpq is identical in logical and realised
-- frames; one delta serves both ppq and ppqL paths.
function tm:tileLength(newPpq)
if not mm then return end
local oldPpq = mm:length() or 0
if oldPpq <= 0 or newPpq <= oldPpq then return self:setLength(newPpq) end
local function snapshot(iter)
local out = {}
for _, evt in iter do
if evt.ppq < oldPpq then
local c = util.clone(evt, { uuid = true })
util.add(out, c)
end
end
return out
end
local sourceEvents = snapshot(mm:events())
mm:setLength(newPpq / mm:resolution())
local function shift(c, delta)
c.ppq = c.ppq + delta
if c.ppqL then c.ppqL = c.ppqL + delta end
if c.ppq >= newPpq then return false end
if c.evType == 'note' then
c.endppq = c.endppq + delta
if c.endppqL then c.endppqL = c.endppqL + delta end
if c.endppq > newPpq then c.endppq, c.endppqL = newPpq, nil end
end
return true
end
mm:modify(function()
for k = 1, math.ceil(newPpq / oldPpq) - 1 do
local delta = k * oldPpq
for _, src in ipairs(sourceEvents) do
local c = util.clone(src)
if shift(c, delta) then mm:add(c) end
end
end
end)
end
----- Transport
function tm:playFrom(ppq)
if not (mm and mm:take()) then return end
reaper.SetEditCurPos(reaper.MIDI_GetProjTimeFromPPQPos(mm:take(), ppq), false, false)
reaper.Main_OnCommand(1007, 0)
end
function tm:play() reaper.Main_OnCommand(1007, 0) end
function tm:stop() reaper.Main_OnCommand(1016, 0) end