entangled-worlds-orbiters-shared 1.0.9 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +12 -5
- package/THIRD-PARTY-NOTICES.md +5 -0
- package/dist/clock/ClockBackend.d.ts +44 -0
- package/dist/clock/ClockBackend.js +70 -0
- package/dist/clock/Transport.d.ts +85 -0
- package/dist/clock/Transport.js +268 -0
- package/dist/clock/curves.d.ts +84 -0
- package/dist/clock/curves.js +115 -0
- package/dist/clock/index.d.ts +4 -0
- package/dist/clock/index.js +4 -0
- package/dist/clock/musical.d.ts +47 -0
- package/dist/clock/musical.js +125 -0
- package/dist/clock/sync.d.ts +136 -0
- package/dist/clock/sync.js +224 -0
- package/package.json +22 -7
- package/src/clock/ClockBackend.ts +98 -0
- package/src/clock/Transport.ts +331 -0
- package/src/clock/curves.ts +163 -0
- package/src/clock/index.ts +17 -0
- package/src/clock/musical.ts +161 -0
- package/src/clock/sync.ts +315 -0
- package/src/index.js +0 -1
- package/src/utils/dispose.js +20 -4
- package/src/arrow-ui/BooleanController.js +0 -31
- package/src/arrow-ui/ColorController.js +0 -108
- package/src/arrow-ui/Controller.js +0 -447
- package/src/arrow-ui/FunctionController.js +0 -27
- package/src/arrow-ui/GUI.js +0 -595
- package/src/arrow-ui/NumberController.js +0 -567
- package/src/arrow-ui/OptionController.js +0 -64
- package/src/arrow-ui/StringController.js +0 -41
- package/src/arrow-ui/index.js +0 -13
- package/src/arrow-ui/lilGuiLoader.js +0 -10
- package/src/arrow-ui/utils/getColorFormat.js +0 -75
- package/src/arrow-ui/utils/injectStyles.js +0 -10
- package/src/arrow-ui/utils/normalizeColorString.js +0 -29
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// CurveTrack — a time-addressable curve the orchestrator samples by position (design doc §0 D3, §4/§5).
|
|
2
|
+
//
|
|
3
|
+
// Two kinds, one interface:
|
|
4
|
+
// - 'absolute-seconds' : keyframes are { t: seconds, value } (free gestures, non-metric)
|
|
5
|
+
// - 'beat-locked' : keyframes are { t: beats, value } (musical; needs a projection)
|
|
6
|
+
// A beat-locked curve REFLOWS automatically when tempo changes — a peak authored "at beat 3" lands on
|
|
7
|
+
// beat 3 at any tempo. This is what lets recorded gestures and authored anime-style curves share the
|
|
8
|
+
// musical timeline. `sample(positionSec)` is pure: position in, value out — no internal timer.
|
|
9
|
+
export const Ease = {
|
|
10
|
+
linear: (x) => x,
|
|
11
|
+
smooth: (x) => x * x * (3 - 2 * x), // smoothstep
|
|
12
|
+
};
|
|
13
|
+
function lerp(a, b, t) {
|
|
14
|
+
return a + (b - a) * t;
|
|
15
|
+
}
|
|
16
|
+
export class CurveTrack {
|
|
17
|
+
keyframes;
|
|
18
|
+
timeMode;
|
|
19
|
+
projection;
|
|
20
|
+
ease;
|
|
21
|
+
outputIntent;
|
|
22
|
+
constructor(spec) {
|
|
23
|
+
this.keyframes = spec.keyframes.slice().sort((a, b) => a.t - b.t);
|
|
24
|
+
this.timeMode = spec.timeMode ?? 'absolute-seconds';
|
|
25
|
+
this.projection = spec.projection ?? null;
|
|
26
|
+
this.ease = spec.ease ?? Ease.linear;
|
|
27
|
+
this.outputIntent = spec.outputIntent ?? null;
|
|
28
|
+
if (this.timeMode === 'beat-locked' && !this.projection) {
|
|
29
|
+
throw new Error('beat-locked CurveTrack needs a MusicalProjection');
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** The track's own time key for a given clock position. */
|
|
33
|
+
_key(positionSec) {
|
|
34
|
+
return this.timeMode === 'beat-locked' ? this.projection.secondsToBeats(positionSec) : positionSec;
|
|
35
|
+
}
|
|
36
|
+
sample(positionSec) {
|
|
37
|
+
const k = this._key(positionSec);
|
|
38
|
+
const kf = this.keyframes;
|
|
39
|
+
if (k <= kf[0].t)
|
|
40
|
+
return kf[0].value;
|
|
41
|
+
if (k >= kf[kf.length - 1].t)
|
|
42
|
+
return kf[kf.length - 1].value;
|
|
43
|
+
let i = 0;
|
|
44
|
+
while (i < kf.length - 1 && kf[i + 1].t <= k)
|
|
45
|
+
i++;
|
|
46
|
+
const a = kf[i];
|
|
47
|
+
const b = kf[i + 1];
|
|
48
|
+
const frac = (k - a.t) / (b.t - a.t);
|
|
49
|
+
return lerp(a.value, b.value, this.ease(frac));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* GestureRecorder — captures live input samples stamped with the transport position, producing a
|
|
54
|
+
* CurveTrack. Free gestures stamp seconds; musical gestures stamp beats (so they tempo-rebase).
|
|
55
|
+
* (design doc §4a: today gestures are applied live & never recorded against musical time.)
|
|
56
|
+
*/
|
|
57
|
+
export class GestureRecorder {
|
|
58
|
+
transport;
|
|
59
|
+
timeMode;
|
|
60
|
+
projection;
|
|
61
|
+
keyframes;
|
|
62
|
+
constructor(transport, { timeMode = 'absolute-seconds', projection = null } = {}) {
|
|
63
|
+
this.transport = transport;
|
|
64
|
+
this.timeMode = timeMode;
|
|
65
|
+
// `_projection` is the transport's private musical overlay (read defensively — it is an
|
|
66
|
+
// implementation detail not part of the public TransportLike contract).
|
|
67
|
+
const carried = transport._projection;
|
|
68
|
+
this.projection = projection ?? carried ?? null;
|
|
69
|
+
// Fail fast: a beat-locked gesture must have a projection to stamp beats, else capture() would
|
|
70
|
+
// crash later with a cryptic null error (Codex review). Invalid config only — valid paths unchanged.
|
|
71
|
+
if (this.timeMode === 'beat-locked' && !this.projection) {
|
|
72
|
+
throw new Error('[GestureRecorder] timeMode "beat-locked" requires a projection (none provided or carried by the transport).');
|
|
73
|
+
}
|
|
74
|
+
this.keyframes = [];
|
|
75
|
+
}
|
|
76
|
+
/** Stamp a value at the current transport position. */
|
|
77
|
+
capture(value) {
|
|
78
|
+
const pos = this.transport.positionSec();
|
|
79
|
+
const t = this.timeMode === 'beat-locked' ? this.projection.secondsToBeats(pos) : pos;
|
|
80
|
+
this.keyframes.push({ t, value });
|
|
81
|
+
}
|
|
82
|
+
toTrack(ease) {
|
|
83
|
+
return new CurveTrack({ keyframes: this.keyframes, timeMode: this.timeMode, projection: this.projection, ease });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Orchestrator — the thin layer that subscribes every domain to ONE transport (design doc §5):
|
|
88
|
+
* - audio: schedule(atSec, fire) -> armed ahead with precise audio time
|
|
89
|
+
* - visuals: onTick -> sample curves at the current position each frame (one shared reader)
|
|
90
|
+
*/
|
|
91
|
+
export class Orchestrator {
|
|
92
|
+
transport;
|
|
93
|
+
curves;
|
|
94
|
+
lastValues;
|
|
95
|
+
_off;
|
|
96
|
+
constructor(transport) {
|
|
97
|
+
this.transport = transport;
|
|
98
|
+
this.curves = new Map();
|
|
99
|
+
this._off = transport.onTick((positionSec) => this._readFrame(positionSec));
|
|
100
|
+
this.lastValues = new Map();
|
|
101
|
+
}
|
|
102
|
+
addCurve(id, track) {
|
|
103
|
+
this.curves.set(id, track);
|
|
104
|
+
}
|
|
105
|
+
scheduleAudio(atSec, fire) {
|
|
106
|
+
return this.transport.schedule({ atSec, fire });
|
|
107
|
+
}
|
|
108
|
+
_readFrame(positionSec) {
|
|
109
|
+
for (const [id, track] of this.curves)
|
|
110
|
+
this.lastValues.set(id, track.sample(positionSec));
|
|
111
|
+
}
|
|
112
|
+
dispose() {
|
|
113
|
+
this._off();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { Transport } from './Transport.js';
|
|
2
|
+
export type { LoopSec, PlayState, EventSpec, TransportSnapshot, AnchoredState, ScheduleStateMeta, MusicalProjectionLike, TransportOptions, } from './Transport.js';
|
|
3
|
+
export { VirtualClockBackend } from './ClockBackend.js';
|
|
4
|
+
export type { ClockBackend, CancelHandle } from './ClockBackend.js';
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// ./clock — the headless, framework-free time core: the seconds-first Transport + look-ahead
|
|
2
|
+
// scheduler and the neutral ClockBackend contract. No three, no react, no sync/musical/curves.
|
|
3
|
+
export { Transport } from './Transport.js';
|
|
4
|
+
export { VirtualClockBackend } from './ClockBackend.js';
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export interface TempoEntry {
|
|
2
|
+
startSec: number;
|
|
3
|
+
bpm: number;
|
|
4
|
+
}
|
|
5
|
+
export interface SignatureEntry {
|
|
6
|
+
startBar: number;
|
|
7
|
+
numerator: number;
|
|
8
|
+
denominator: number;
|
|
9
|
+
}
|
|
10
|
+
export interface MusicalProjectionSpec {
|
|
11
|
+
tempoMap?: TempoEntry[];
|
|
12
|
+
signatureMap?: SignatureEntry[];
|
|
13
|
+
ppq?: number;
|
|
14
|
+
}
|
|
15
|
+
export interface BarBeat {
|
|
16
|
+
bar: number;
|
|
17
|
+
beat: number;
|
|
18
|
+
}
|
|
19
|
+
export interface MusicalPosition {
|
|
20
|
+
bar: number;
|
|
21
|
+
beat: number;
|
|
22
|
+
beatsTotal: number;
|
|
23
|
+
ticks: number;
|
|
24
|
+
bpm: number;
|
|
25
|
+
signature: string;
|
|
26
|
+
}
|
|
27
|
+
export declare class MusicalProjection {
|
|
28
|
+
ppq: number;
|
|
29
|
+
private _tempo;
|
|
30
|
+
private _sig;
|
|
31
|
+
constructor(spec?: MusicalProjectionSpec);
|
|
32
|
+
private _tempoSegAtSec;
|
|
33
|
+
private _tempoSegAtBeat;
|
|
34
|
+
secondsToBeats(sec: number): number;
|
|
35
|
+
beatsToSeconds(beat: number): number;
|
|
36
|
+
private _sigSegAtBeat;
|
|
37
|
+
private _sigSegAtBar;
|
|
38
|
+
/** total quarter-beats -> { bar, beat (0-indexed within bar) } */
|
|
39
|
+
beatsToBarBeat(beat: number): BarBeat;
|
|
40
|
+
barBeatToBeats(bar: number, beatInBar?: number): number;
|
|
41
|
+
/** The DERIVED musical position at a given seconds value. */
|
|
42
|
+
musicalAt(sec: number): MusicalPosition;
|
|
43
|
+
/** Snap a seconds value to the nearest grid line `gridBeats` wide (e.g. 1 = quarter, 0.25 = 16th). */
|
|
44
|
+
quantizeSecToGrid(sec: number, gridBeats?: number): number;
|
|
45
|
+
/** Snap a seconds value to the nearest bar line (honors a changing time signature). */
|
|
46
|
+
quantizeSecToBar(sec: number): number;
|
|
47
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// MusicalProjection — the OPTIONAL musical overlay on the seconds-first clock (design doc §0 D3).
|
|
2
|
+
//
|
|
3
|
+
// Turns seconds <-> musical position using a piecewise-constant tempo map and a per-bar time-signature
|
|
4
|
+
// map. PPQ defaults to 480 (DAW-grade, Bruna's call). This object is what `Transport.setProjection`
|
|
5
|
+
// plugs in; with NO projection the transport stays pure-seconds (non-metric sound). Everything here is
|
|
6
|
+
// DERIVED — the seconds timeline never depends on it.
|
|
7
|
+
//
|
|
8
|
+
// Units: a "beat" is a QUARTER note (PPQ is per quarter). A bar's length in quarter-beats =
|
|
9
|
+
// numerator * 4 / denominator (so 4/4 = 4, 3/4 = 3, 7/8 = 3.5).
|
|
10
|
+
const DEFAULT_PPQ = 480;
|
|
11
|
+
export class MusicalProjection {
|
|
12
|
+
ppq;
|
|
13
|
+
_tempo;
|
|
14
|
+
_sig;
|
|
15
|
+
constructor(spec = {}) {
|
|
16
|
+
this.ppq = spec.ppq ?? DEFAULT_PPQ;
|
|
17
|
+
const tempo = (spec.tempoMap && spec.tempoMap.length ? spec.tempoMap : [{ startSec: 0, bpm: 120 }])
|
|
18
|
+
.slice()
|
|
19
|
+
.sort((a, b) => a.startSec - b.startSec);
|
|
20
|
+
// precompute the cumulative beat position at each tempo segment boundary
|
|
21
|
+
this._tempo = tempo.map((s) => ({ ...s, startBeat: 0 }));
|
|
22
|
+
for (let i = 1; i < this._tempo.length; i++) {
|
|
23
|
+
const prev = this._tempo[i - 1];
|
|
24
|
+
this._tempo[i].startBeat = prev.startBeat + (this._tempo[i].startSec - prev.startSec) * (prev.bpm / 60);
|
|
25
|
+
}
|
|
26
|
+
const sig = (spec.signatureMap && spec.signatureMap.length
|
|
27
|
+
? spec.signatureMap
|
|
28
|
+
: [{ startBar: 0, numerator: 4, denominator: 4 }])
|
|
29
|
+
.slice()
|
|
30
|
+
.sort((a, b) => a.startBar - b.startBar);
|
|
31
|
+
// precompute the cumulative beat position at each signature segment's startBar
|
|
32
|
+
this._sig = sig.map((s) => ({ ...s, beatsPerBar: (s.numerator * 4) / s.denominator, startBeat: 0 }));
|
|
33
|
+
for (let i = 1; i < this._sig.length; i++) {
|
|
34
|
+
const prev = this._sig[i - 1];
|
|
35
|
+
const bars = this._sig[i].startBar - prev.startBar;
|
|
36
|
+
this._sig[i].startBeat = prev.startBeat + bars * prev.beatsPerBar;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
_tempoSegAtSec(sec) {
|
|
40
|
+
let seg = this._tempo[0];
|
|
41
|
+
for (const s of this._tempo)
|
|
42
|
+
if (s.startSec <= sec + 1e-9)
|
|
43
|
+
seg = s;
|
|
44
|
+
else
|
|
45
|
+
break;
|
|
46
|
+
return seg;
|
|
47
|
+
}
|
|
48
|
+
_tempoSegAtBeat(beat) {
|
|
49
|
+
let seg = this._tempo[0];
|
|
50
|
+
for (const s of this._tempo)
|
|
51
|
+
if (s.startBeat <= beat + 1e-9)
|
|
52
|
+
seg = s;
|
|
53
|
+
else
|
|
54
|
+
break;
|
|
55
|
+
return seg;
|
|
56
|
+
}
|
|
57
|
+
secondsToBeats(sec) {
|
|
58
|
+
const seg = this._tempoSegAtSec(sec);
|
|
59
|
+
return seg.startBeat + (sec - seg.startSec) * (seg.bpm / 60);
|
|
60
|
+
}
|
|
61
|
+
beatsToSeconds(beat) {
|
|
62
|
+
const seg = this._tempoSegAtBeat(beat);
|
|
63
|
+
return seg.startSec + (beat - seg.startBeat) * (60 / seg.bpm);
|
|
64
|
+
}
|
|
65
|
+
_sigSegAtBeat(beat) {
|
|
66
|
+
let seg = this._sig[0];
|
|
67
|
+
for (const s of this._sig)
|
|
68
|
+
if (s.startBeat <= beat + 1e-9)
|
|
69
|
+
seg = s;
|
|
70
|
+
else
|
|
71
|
+
break;
|
|
72
|
+
return seg;
|
|
73
|
+
}
|
|
74
|
+
_sigSegAtBar(bar) {
|
|
75
|
+
let seg = this._sig[0];
|
|
76
|
+
for (const s of this._sig)
|
|
77
|
+
if (s.startBar <= bar)
|
|
78
|
+
seg = s;
|
|
79
|
+
else
|
|
80
|
+
break;
|
|
81
|
+
return seg;
|
|
82
|
+
}
|
|
83
|
+
/** total quarter-beats -> { bar, beat (0-indexed within bar) } */
|
|
84
|
+
beatsToBarBeat(beat) {
|
|
85
|
+
const seg = this._sigSegAtBeat(beat);
|
|
86
|
+
const local = beat - seg.startBeat;
|
|
87
|
+
const barInSeg = Math.floor(local / seg.beatsPerBar + 1e-9);
|
|
88
|
+
const beatInBar = local - barInSeg * seg.beatsPerBar;
|
|
89
|
+
return { bar: seg.startBar + barInSeg, beat: beatInBar };
|
|
90
|
+
}
|
|
91
|
+
barBeatToBeats(bar, beatInBar = 0) {
|
|
92
|
+
const seg = this._sigSegAtBar(bar);
|
|
93
|
+
return seg.startBeat + (bar - seg.startBar) * seg.beatsPerBar + beatInBar;
|
|
94
|
+
}
|
|
95
|
+
/** The DERIVED musical position at a given seconds value. */
|
|
96
|
+
musicalAt(sec) {
|
|
97
|
+
const beat = this.secondsToBeats(sec);
|
|
98
|
+
const { bar, beat: beatInBar } = this.beatsToBarBeat(beat);
|
|
99
|
+
const seg = this._tempoSegAtSec(sec);
|
|
100
|
+
const sig = this._sigSegAtBeat(beat);
|
|
101
|
+
return {
|
|
102
|
+
bar,
|
|
103
|
+
beat: beatInBar,
|
|
104
|
+
beatsTotal: beat,
|
|
105
|
+
ticks: Math.round(beat * this.ppq),
|
|
106
|
+
bpm: seg.bpm,
|
|
107
|
+
signature: `${sig.numerator}/${sig.denominator}`,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
// ---- edit-time snap (design doc §0 D3: snap-to-tempo where edits land) ---------------
|
|
111
|
+
/** Snap a seconds value to the nearest grid line `gridBeats` wide (e.g. 1 = quarter, 0.25 = 16th). */
|
|
112
|
+
quantizeSecToGrid(sec, gridBeats = 1) {
|
|
113
|
+
const beat = this.secondsToBeats(sec);
|
|
114
|
+
const snapped = Math.round(beat / gridBeats) * gridBeats;
|
|
115
|
+
return this.beatsToSeconds(snapped);
|
|
116
|
+
}
|
|
117
|
+
/** Snap a seconds value to the nearest bar line (honors a changing time signature). */
|
|
118
|
+
quantizeSecToBar(sec) {
|
|
119
|
+
const beat = this.secondsToBeats(sec);
|
|
120
|
+
const { bar, beat: beatInBar } = this.beatsToBarBeat(beat);
|
|
121
|
+
const seg = this._sigSegAtBeat(beat);
|
|
122
|
+
const nearestBar = beatInBar >= seg.beatsPerBar / 2 ? bar + 1 : bar;
|
|
123
|
+
return this.beatsToSeconds(this.barBeatToBeats(nearestBar, 0));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/** Audio-anchored local clock the beat timeline pins to (the transport's backend in prod). */
|
|
2
|
+
export interface AudioClockLike {
|
|
3
|
+
nowSec(): number;
|
|
4
|
+
}
|
|
5
|
+
/** Last-writer-wins stamp on the replicated timeline. */
|
|
6
|
+
export interface TimelineStamp {
|
|
7
|
+
time: number;
|
|
8
|
+
id: string;
|
|
9
|
+
}
|
|
10
|
+
/** The replicated beat timeline (Link SessionState): tempo + a beat<->sessionTime bijection. */
|
|
11
|
+
export interface BeatTimelineState {
|
|
12
|
+
tempoBpm: number;
|
|
13
|
+
anchorBeat: number;
|
|
14
|
+
anchorSessionMs: number;
|
|
15
|
+
}
|
|
16
|
+
/** A peer's observed (NOT adopted) transport intent. */
|
|
17
|
+
export interface PeerIntent {
|
|
18
|
+
playing: boolean;
|
|
19
|
+
atSessionMs: number;
|
|
20
|
+
}
|
|
21
|
+
/** Messages exchanged over the relay seam. */
|
|
22
|
+
export type SyncMessage = {
|
|
23
|
+
kind: 'link:hello';
|
|
24
|
+
id: string;
|
|
25
|
+
} | {
|
|
26
|
+
kind: 'link:timeline';
|
|
27
|
+
timeline: BeatTimelineState;
|
|
28
|
+
ts: TimelineStamp;
|
|
29
|
+
id: string;
|
|
30
|
+
} | {
|
|
31
|
+
kind: 'link:transport';
|
|
32
|
+
id: string;
|
|
33
|
+
playing: boolean;
|
|
34
|
+
atSessionMs: number;
|
|
35
|
+
};
|
|
36
|
+
/** A node the relay can register + deliver to. */
|
|
37
|
+
export interface RelayNode {
|
|
38
|
+
id: string;
|
|
39
|
+
online: boolean;
|
|
40
|
+
localWallMs(): number;
|
|
41
|
+
receive(msg: SyncMessage): void;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The relay seam the beat timeline depends on: a shared server clock + epoch + message fan-out.
|
|
45
|
+
* Production wires this to the real transport/signalling channel; tests inject a FakeRelay.
|
|
46
|
+
*/
|
|
47
|
+
export interface RelaySeam {
|
|
48
|
+
sessionEpochMs: number;
|
|
49
|
+
upMs: number;
|
|
50
|
+
downMs: number;
|
|
51
|
+
serverNowMs(): number;
|
|
52
|
+
register(node: RelayNode): void;
|
|
53
|
+
send(fromId: string, msg: SyncMessage, toId?: string | null): void;
|
|
54
|
+
}
|
|
55
|
+
/** Options for the Cristian/SNTP offset estimate. */
|
|
56
|
+
export interface EstimateOffsetOpts {
|
|
57
|
+
samples?: number;
|
|
58
|
+
upMs?: number;
|
|
59
|
+
downMs?: number;
|
|
60
|
+
jitterFn?: () => number;
|
|
61
|
+
}
|
|
62
|
+
/** Cristian/SNTP offset estimate: median of (serverStamp + rtt/2 - t1). Asymmetry biases by (up-down)/2. */
|
|
63
|
+
export declare function estimateOffset(node: Pick<RelayNode, 'localWallMs'>, relay: RelaySeam, { samples, upMs, downMs, jitterFn }?: EstimateOffsetOpts): number;
|
|
64
|
+
export interface BeatTimelineConfig {
|
|
65
|
+
id: string;
|
|
66
|
+
relay: RelaySeam;
|
|
67
|
+
audioClock: AudioClockLike;
|
|
68
|
+
/** `quantum` (beats) is LOCAL & app-set — derive it from the active time signature / loop length. */
|
|
69
|
+
quantum?: number;
|
|
70
|
+
trueOffsetMs?: number;
|
|
71
|
+
}
|
|
72
|
+
/** Result of a quantized launch: where the local transport should begin + the count-in length. */
|
|
73
|
+
export interface LaunchResult {
|
|
74
|
+
startBeat: number;
|
|
75
|
+
startAudioSec: number;
|
|
76
|
+
countInBeats: number;
|
|
77
|
+
}
|
|
78
|
+
export declare class BeatTimeline implements RelayNode {
|
|
79
|
+
id: string;
|
|
80
|
+
relay: RelaySeam;
|
|
81
|
+
audioClock: AudioClockLike;
|
|
82
|
+
quantum: number;
|
|
83
|
+
trueOffsetMs: number;
|
|
84
|
+
online: boolean;
|
|
85
|
+
timeline: BeatTimelineState;
|
|
86
|
+
private _ts;
|
|
87
|
+
offsetMs: number;
|
|
88
|
+
private _audioToSessionMs;
|
|
89
|
+
localPlaying: boolean;
|
|
90
|
+
peerIntents: Map<string, PeerIntent>;
|
|
91
|
+
peers: Set<string>;
|
|
92
|
+
enabled: boolean;
|
|
93
|
+
onChange: (() => void) | null;
|
|
94
|
+
onPeerTransport: ((id: string, intent: PeerIntent) => void) | null;
|
|
95
|
+
/**
|
|
96
|
+
* `audioClock` is the local transport's backend (AudioContext.currentTime in prod).
|
|
97
|
+
*/
|
|
98
|
+
constructor({ id, relay, audioClock, quantum, trueOffsetMs }: BeatTimelineConfig);
|
|
99
|
+
localWallMs(): number;
|
|
100
|
+
sessionNowMs(): number;
|
|
101
|
+
pinAudio(): void;
|
|
102
|
+
sessionMsToAudioSec(ms: number): number;
|
|
103
|
+
/** Join: estimate offset to server time, pin the audio clock, and ask the session for its timeline. */
|
|
104
|
+
join(estimateOpts?: EstimateOffsetOpts): void;
|
|
105
|
+
/** Broadcast presence (peers reply with their timeline). Safe to call periodically as a heartbeat. */
|
|
106
|
+
announce(): void;
|
|
107
|
+
/** Toggle participation. Off = solo (no broadcast, no adoption). On = re-announce + re-adopt. */
|
|
108
|
+
setEnabled(on: boolean): void;
|
|
109
|
+
beatAtSession(ms: number): number;
|
|
110
|
+
sessionAtBeat(beat: number): number;
|
|
111
|
+
beatNow(): number;
|
|
112
|
+
phaseAt(ms: number, quantum?: number): number;
|
|
113
|
+
phaseNow(quantum?: number): number;
|
|
114
|
+
/** Local audio time at which a given session beat occurs (for scheduling on the local clock). */
|
|
115
|
+
beatToAudioSec(beat: number): number;
|
|
116
|
+
get tempoBpm(): number;
|
|
117
|
+
private _commit;
|
|
118
|
+
/** Propose a tempo. Keeps the beat value continuous at the moment of change (no jump). */
|
|
119
|
+
setTempo(bpm: number): void;
|
|
120
|
+
/** Hard-set: make `beat` the value at `sessionMs` (an explicit downbeat / reset). */
|
|
121
|
+
forceBeatAtTime(beat: number, sessionMs?: number): void;
|
|
122
|
+
/** Gently shift the timeline so phase aligns to `beat` at `sessionMs`, nearest (no big jump). */
|
|
123
|
+
requestBeatAtTime(beat: number, sessionMs?: number, quantum?: number): void;
|
|
124
|
+
/** The next quantum boundary strictly after `fromBeat` — guarantees a count-in. */
|
|
125
|
+
quantizedLaunchBeat(fromBeat?: number, quantum?: number): number;
|
|
126
|
+
/**
|
|
127
|
+
* Compute a quantized launch: returns the start beat, its local audio time, and the count-in length.
|
|
128
|
+
* The caller schedules its local transport to begin at `startAudioSec` and shows the count-in.
|
|
129
|
+
* Two peers launching in the same bar resolve to the SAME startBeat ⇒ they start in phase.
|
|
130
|
+
*/
|
|
131
|
+
launch(quantum?: number): LaunchResult;
|
|
132
|
+
setLocalPlaying(playing: boolean): void;
|
|
133
|
+
receive(msg: SyncMessage): void;
|
|
134
|
+
/** Peers currently broadcasting "playing" (for the indicator — observed, not adopted). */
|
|
135
|
+
playingPeers(): string[];
|
|
136
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// BeatTimeline — leaderless shared beat-timeline sync (conceptually based on Ableton Link). Design doc
|
|
2
|
+
// planning/shared-timeline/ORB-102-beat-timeline-sync.md. Replaces the authority/conductor sync model.
|
|
3
|
+
//
|
|
4
|
+
// What's shared: a BEAT TIMELINE (tempo + a beat<->sessionTime bijection). NOT a transport position.
|
|
5
|
+
// - Tempo is LEADERLESS: any peer proposes; each adopts the newest proposal (last-writer-wins);
|
|
6
|
+
// the session converges. No conductor.
|
|
7
|
+
// - Beat alignment + phase come for free: every peer anchors the same `beatAtSession` bijection on
|
|
8
|
+
// the shared session clock, so integral beats correspond; `phase = beat mod quantum`.
|
|
9
|
+
// - Play/pause/seek/loop are LOCAL. Start/stop is OPT-IN: a peer broadcasts its intent but no one
|
|
10
|
+
// adopts another's play state (Link v3). Launch is QUANTIZED: start at the next quantum boundary.
|
|
11
|
+
//
|
|
12
|
+
// Reuses the session-time substrate offset estimation; the server `sessionEpoch` gives every peer a
|
|
13
|
+
// shared `sessionMs`; the beat timeline is anchored to that.
|
|
14
|
+
const mod = (n, m) => ((n % m) + m) % m;
|
|
15
|
+
const newerTs = (a, b) => a.time > b.time || (a.time === b.time && a.id > b.id);
|
|
16
|
+
/** Cristian/SNTP offset estimate: median of (serverStamp + rtt/2 - t1). Asymmetry biases by (up-down)/2. */
|
|
17
|
+
export function estimateOffset(node, relay, { samples = 7, upMs = relay.upMs, downMs = relay.downMs, jitterFn = () => 0 } = {}) {
|
|
18
|
+
const offs = [];
|
|
19
|
+
for (let i = 0; i < samples; i++) {
|
|
20
|
+
const up = upMs + jitterFn();
|
|
21
|
+
const down = downMs + jitterFn();
|
|
22
|
+
const t0 = node.localWallMs();
|
|
23
|
+
const serverStamp = relay.serverNowMs() + up;
|
|
24
|
+
const rtt = up + down;
|
|
25
|
+
const t1 = t0 + rtt;
|
|
26
|
+
offs.push(serverStamp + rtt / 2 - t1);
|
|
27
|
+
}
|
|
28
|
+
offs.sort((a, b) => a - b);
|
|
29
|
+
return offs[Math.floor(offs.length / 2)];
|
|
30
|
+
}
|
|
31
|
+
export class BeatTimeline {
|
|
32
|
+
id;
|
|
33
|
+
relay;
|
|
34
|
+
audioClock;
|
|
35
|
+
quantum;
|
|
36
|
+
trueOffsetMs;
|
|
37
|
+
online;
|
|
38
|
+
timeline;
|
|
39
|
+
_ts; // last-writer-wins stamp for the timeline
|
|
40
|
+
offsetMs;
|
|
41
|
+
_audioToSessionMs;
|
|
42
|
+
localPlaying; // LOCAL transport intent
|
|
43
|
+
peerIntents; // observed (NOT adopted): id -> { playing, atSessionMs }
|
|
44
|
+
peers;
|
|
45
|
+
enabled; // when false: solo — don't broadcast or adopt
|
|
46
|
+
onChange;
|
|
47
|
+
onPeerTransport; // for an opt-in follow toggle
|
|
48
|
+
/**
|
|
49
|
+
* `audioClock` is the local transport's backend (AudioContext.currentTime in prod).
|
|
50
|
+
*/
|
|
51
|
+
constructor({ id, relay, audioClock, quantum = 4, trueOffsetMs = 0 }) {
|
|
52
|
+
this.id = id;
|
|
53
|
+
this.relay = relay;
|
|
54
|
+
this.audioClock = audioClock;
|
|
55
|
+
this.quantum = quantum;
|
|
56
|
+
this.trueOffsetMs = trueOffsetMs;
|
|
57
|
+
this.online = true;
|
|
58
|
+
// The replicated beat timeline. Default: beat 0 at the session EPOCH, 120 bpm — identical for every
|
|
59
|
+
// peer (they share the epoch + session clock), so peers are beat-aligned from the start, no handshake.
|
|
60
|
+
this.timeline = { tempoBpm: 120, anchorBeat: 0, anchorSessionMs: relay.sessionEpochMs };
|
|
61
|
+
this._ts = { time: -1, id }; // last-writer-wins stamp for the timeline
|
|
62
|
+
this.offsetMs = 0;
|
|
63
|
+
this._audioToSessionMs = 0;
|
|
64
|
+
this.localPlaying = false; // LOCAL transport intent
|
|
65
|
+
this.peerIntents = new Map(); // observed (NOT adopted): id -> { playing, atSessionMs }
|
|
66
|
+
this.peers = new Set();
|
|
67
|
+
this.enabled = true; // when false: solo — don't broadcast or adopt
|
|
68
|
+
this.onChange = null;
|
|
69
|
+
this.onPeerTransport = null; // (id, {playing, atSessionMs}) — for an opt-in follow toggle
|
|
70
|
+
relay.register(this);
|
|
71
|
+
}
|
|
72
|
+
// ---- session-time substrate ---------------------------------------------------------
|
|
73
|
+
localWallMs() {
|
|
74
|
+
return this.relay.serverNowMs() - this.trueOffsetMs;
|
|
75
|
+
}
|
|
76
|
+
sessionNowMs() {
|
|
77
|
+
return this.localWallMs() + this.offsetMs;
|
|
78
|
+
}
|
|
79
|
+
pinAudio() {
|
|
80
|
+
this._audioToSessionMs = this.sessionNowMs() - this.audioClock.nowSec() * 1000;
|
|
81
|
+
}
|
|
82
|
+
sessionMsToAudioSec(ms) {
|
|
83
|
+
return (ms - this._audioToSessionMs) / 1000;
|
|
84
|
+
}
|
|
85
|
+
/** Join: estimate offset to server time, pin the audio clock, and ask the session for its timeline. */
|
|
86
|
+
join(estimateOpts) {
|
|
87
|
+
this.offsetMs = estimateOffset(this, this.relay, estimateOpts);
|
|
88
|
+
this.pinAudio();
|
|
89
|
+
this.announce();
|
|
90
|
+
}
|
|
91
|
+
/** Broadcast presence (peers reply with their timeline). Safe to call periodically as a heartbeat. */
|
|
92
|
+
announce() {
|
|
93
|
+
if (this.enabled)
|
|
94
|
+
this.relay.send(this.id, { kind: 'link:hello', id: this.id });
|
|
95
|
+
}
|
|
96
|
+
/** Toggle participation. Off = solo (no broadcast, no adoption). On = re-announce + re-adopt. */
|
|
97
|
+
setEnabled(on) {
|
|
98
|
+
this.enabled = !!on;
|
|
99
|
+
if (this.enabled)
|
|
100
|
+
this.announce();
|
|
101
|
+
else {
|
|
102
|
+
this.peers.clear();
|
|
103
|
+
this.peerIntents.clear();
|
|
104
|
+
}
|
|
105
|
+
if (this.onChange)
|
|
106
|
+
this.onChange();
|
|
107
|
+
}
|
|
108
|
+
// ---- the beat timeline (Link SessionState) ------------------------------------------
|
|
109
|
+
beatAtSession(ms) {
|
|
110
|
+
const t = this.timeline;
|
|
111
|
+
return t.anchorBeat + (ms - t.anchorSessionMs) * (t.tempoBpm / 60000);
|
|
112
|
+
}
|
|
113
|
+
sessionAtBeat(beat) {
|
|
114
|
+
const t = this.timeline;
|
|
115
|
+
return t.anchorSessionMs + (beat - t.anchorBeat) * (60000 / t.tempoBpm);
|
|
116
|
+
}
|
|
117
|
+
beatNow() {
|
|
118
|
+
return this.beatAtSession(this.sessionNowMs());
|
|
119
|
+
}
|
|
120
|
+
phaseAt(ms, quantum = this.quantum) {
|
|
121
|
+
return mod(this.beatAtSession(ms), quantum);
|
|
122
|
+
}
|
|
123
|
+
phaseNow(quantum = this.quantum) {
|
|
124
|
+
return this.phaseAt(this.sessionNowMs(), quantum);
|
|
125
|
+
}
|
|
126
|
+
/** Local audio time at which a given session beat occurs (for scheduling on the local clock). */
|
|
127
|
+
beatToAudioSec(beat) {
|
|
128
|
+
return this.sessionMsToAudioSec(this.sessionAtBeat(beat));
|
|
129
|
+
}
|
|
130
|
+
get tempoBpm() {
|
|
131
|
+
return this.timeline.tempoBpm;
|
|
132
|
+
}
|
|
133
|
+
// ---- timeline mutations (all leaderless: broadcast + last-writer-wins) ---------------
|
|
134
|
+
_commit(timeline) {
|
|
135
|
+
this.timeline = { ...timeline };
|
|
136
|
+
this._ts = { time: this.sessionNowMs(), id: this.id };
|
|
137
|
+
if (this.enabled)
|
|
138
|
+
this.relay.send(this.id, { kind: 'link:timeline', timeline: this.timeline, ts: this._ts, id: this.id });
|
|
139
|
+
if (this.onChange)
|
|
140
|
+
this.onChange();
|
|
141
|
+
}
|
|
142
|
+
/** Propose a tempo. Keeps the beat value continuous at the moment of change (no jump). */
|
|
143
|
+
setTempo(bpm) {
|
|
144
|
+
const atMs = this.sessionNowMs();
|
|
145
|
+
this._commit({ tempoBpm: bpm, anchorBeat: this.beatAtSession(atMs), anchorSessionMs: atMs });
|
|
146
|
+
}
|
|
147
|
+
/** Hard-set: make `beat` the value at `sessionMs` (an explicit downbeat / reset). */
|
|
148
|
+
forceBeatAtTime(beat, sessionMs = this.sessionNowMs()) {
|
|
149
|
+
this._commit({ tempoBpm: this.timeline.tempoBpm, anchorBeat: beat, anchorSessionMs: sessionMs });
|
|
150
|
+
}
|
|
151
|
+
/** Gently shift the timeline so phase aligns to `beat` at `sessionMs`, nearest (no big jump). */
|
|
152
|
+
requestBeatAtTime(beat, sessionMs = this.sessionNowMs(), quantum = this.quantum) {
|
|
153
|
+
const current = this.beatAtSession(sessionMs);
|
|
154
|
+
let shift = mod(beat, quantum) - mod(current, quantum);
|
|
155
|
+
if (shift > quantum / 2)
|
|
156
|
+
shift -= quantum;
|
|
157
|
+
if (shift < -quantum / 2)
|
|
158
|
+
shift += quantum;
|
|
159
|
+
this._commit({ ...this.timeline, anchorBeat: this.timeline.anchorBeat + shift });
|
|
160
|
+
}
|
|
161
|
+
// ---- quantized launch ---------------------------------------------------------------
|
|
162
|
+
/** The next quantum boundary strictly after `fromBeat` — guarantees a count-in. */
|
|
163
|
+
quantizedLaunchBeat(fromBeat = this.beatNow(), quantum = this.quantum) {
|
|
164
|
+
return (Math.floor(fromBeat / quantum + 1e-9) + 1) * quantum;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Compute a quantized launch: returns the start beat, its local audio time, and the count-in length.
|
|
168
|
+
* The caller schedules its local transport to begin at `startAudioSec` and shows the count-in.
|
|
169
|
+
* Two peers launching in the same bar resolve to the SAME startBeat ⇒ they start in phase.
|
|
170
|
+
*/
|
|
171
|
+
launch(quantum = this.quantum) {
|
|
172
|
+
const fromBeat = this.beatNow();
|
|
173
|
+
const startBeat = this.quantizedLaunchBeat(fromBeat, quantum);
|
|
174
|
+
this.setLocalPlaying(true);
|
|
175
|
+
return { startBeat, startAudioSec: this.beatToAudioSec(startBeat), countInBeats: startBeat - fromBeat };
|
|
176
|
+
}
|
|
177
|
+
// ---- start/stop intent (opt-in; never adopted on join) ------------------------------
|
|
178
|
+
setLocalPlaying(playing) {
|
|
179
|
+
this.localPlaying = playing;
|
|
180
|
+
this.relay.send(this.id, { kind: 'link:transport', id: this.id, playing, atSessionMs: this.sessionNowMs() });
|
|
181
|
+
if (this.onChange)
|
|
182
|
+
this.onChange();
|
|
183
|
+
}
|
|
184
|
+
// ---- receive ------------------------------------------------------------------------
|
|
185
|
+
receive(msg) {
|
|
186
|
+
if (!this.enabled)
|
|
187
|
+
return; // solo: ignore everything from the network
|
|
188
|
+
switch (msg.kind) {
|
|
189
|
+
case 'link:hello':
|
|
190
|
+
this.peers.add(msg.id);
|
|
191
|
+
// reply with our current timeline (tagged with our id) so the joiner adopts tempo/phase + learns us
|
|
192
|
+
this.relay.send(this.id, { kind: 'link:timeline', timeline: this.timeline, ts: this._ts, id: this.id }, msg.id);
|
|
193
|
+
if (this.onChange)
|
|
194
|
+
this.onChange();
|
|
195
|
+
break;
|
|
196
|
+
case 'link:timeline':
|
|
197
|
+
if (msg.id)
|
|
198
|
+
this.peers.add(msg.id);
|
|
199
|
+
if (newerTs(msg.ts, this._ts)) {
|
|
200
|
+
this.timeline = { ...msg.timeline };
|
|
201
|
+
this._ts = msg.ts;
|
|
202
|
+
}
|
|
203
|
+
if (this.onChange)
|
|
204
|
+
this.onChange();
|
|
205
|
+
break;
|
|
206
|
+
case 'link:transport':
|
|
207
|
+
// OBSERVE by default (Link v3: never auto-adopt). `onPeerTransport` lets the app opt into
|
|
208
|
+
// following (the "Sync play" toggle) — it decides whether to launch/stop locally.
|
|
209
|
+
this.peers.add(msg.id);
|
|
210
|
+
this.peerIntents.set(msg.id, { playing: msg.playing, atSessionMs: msg.atSessionMs });
|
|
211
|
+
if (this.onPeerTransport)
|
|
212
|
+
this.onPeerTransport(msg.id, { playing: msg.playing, atSessionMs: msg.atSessionMs });
|
|
213
|
+
if (this.onChange)
|
|
214
|
+
this.onChange();
|
|
215
|
+
break;
|
|
216
|
+
default:
|
|
217
|
+
break;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
/** Peers currently broadcasting "playing" (for the indicator — observed, not adopted). */
|
|
221
|
+
playingPeers() {
|
|
222
|
+
return [...this.peerIntents.entries()].filter(([, v]) => v.playing).map(([id]) => id);
|
|
223
|
+
}
|
|
224
|
+
}
|