entangled-worlds-orbiters-shared 1.1.0 → 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/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 +18 -4
- 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
|
@@ -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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "entangled-worlds-orbiters-shared",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Shared library for entangled worlds orbiters - contains core world rendering, moons system, and UI components",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.js",
|
|
7
|
+
"sideEffects": false,
|
|
7
8
|
"exports": {
|
|
8
9
|
".": "./src/index.js",
|
|
9
10
|
"./world": "./src/world/index.js",
|
|
@@ -11,10 +12,16 @@
|
|
|
11
12
|
"./loaders": "./src/loaders/index.js",
|
|
12
13
|
"./core": "./src/core/index.js",
|
|
13
14
|
"./config": "./src/config/index.js",
|
|
14
|
-
"./utils": "./src/utils/index.js"
|
|
15
|
+
"./utils": "./src/utils/index.js",
|
|
16
|
+
"./clock": { "types": "./dist/clock/index.d.ts", "import": "./dist/clock/index.js" },
|
|
17
|
+
"./clock/musical": { "types": "./dist/clock/musical.d.ts", "import": "./dist/clock/musical.js" },
|
|
18
|
+
"./clock/sync": { "types": "./dist/clock/sync.d.ts", "import": "./dist/clock/sync.js" },
|
|
19
|
+
"./clock/curves": { "types": "./dist/clock/curves.d.ts", "import": "./dist/clock/curves.js" }
|
|
15
20
|
},
|
|
16
21
|
"files": [
|
|
17
22
|
"src/**/*",
|
|
23
|
+
"!src/**/*.test.ts",
|
|
24
|
+
"dist/**/*",
|
|
18
25
|
"public/**/*",
|
|
19
26
|
"README.md",
|
|
20
27
|
"LICENSE",
|
|
@@ -40,7 +47,10 @@
|
|
|
40
47
|
"eslint": "^10.0.0",
|
|
41
48
|
"globals": "^17.3.0",
|
|
42
49
|
"three": "^0.166.1",
|
|
43
|
-
"three-stdlib": "^2.34.0"
|
|
50
|
+
"three-stdlib": "^2.34.0",
|
|
51
|
+
"@types/node": "^20.19.0",
|
|
52
|
+
"tsx": "^4.19.2",
|
|
53
|
+
"typescript": "^5.7.2"
|
|
44
54
|
},
|
|
45
55
|
"repository": {
|
|
46
56
|
"type": "git",
|
|
@@ -53,6 +63,10 @@
|
|
|
53
63
|
"scripts": {
|
|
54
64
|
"lint": "eslint .",
|
|
55
65
|
"lint:strict": "eslint . --max-warnings=0",
|
|
56
|
-
"lint:fallback": "node scripts/lint.js"
|
|
66
|
+
"lint:fallback": "node scripts/lint.js",
|
|
67
|
+
"build:clock": "tsc -p tsconfig.build.json",
|
|
68
|
+
"prepare": "npm run build:clock",
|
|
69
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
70
|
+
"test:clock": "node --test --import tsx src/clock/*.test.ts"
|
|
57
71
|
}
|
|
58
72
|
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// ClockBackend — the neutral audio-anchored time source the transport depends on.
|
|
2
|
+
//
|
|
3
|
+
// The shared package depends ONLY on this interface. Production injects an AudioContext/Tone-backed
|
|
4
|
+
// implementation; headless tests inject a VirtualClockBackend. No Tone/AudioContext type ever leaks
|
|
5
|
+
// through the transport's public surface (design doc §0 D1).
|
|
6
|
+
//
|
|
7
|
+
// The contract distinguishes ARMING from OCCURRENCE:
|
|
8
|
+
// - `armAt(audioTimeSec, payload)` schedules an audio event AHEAD and returns a CANCEL handle. This
|
|
9
|
+
// is the ONLY thing a real backend must do — wire `node.start(audioTimeSec)` here. The backend is
|
|
10
|
+
// pure audio I/O; it does NOT drive the transport's event lifecycle.
|
|
11
|
+
// - the TRANSPORT self-detects occurrence in its tick (when its audio clock passes `armedTarget`)
|
|
12
|
+
// and runs the per-event fire/reset itself — so a real backend never needs a JS timer to call back.
|
|
13
|
+
// - cancelling before occurrence prevents the sound (pause/seek/rate/loop change cancels armed-but-
|
|
14
|
+
// unplayed audio). Cancelling after occurrence is a no-op.
|
|
15
|
+
|
|
16
|
+
/** A cancel handle from `armAt`; returns true iff it cancelled an armed-but-unoccurred event. */
|
|
17
|
+
export type CancelHandle = () => boolean;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The neutral backend contract the Transport depends on. No Tone/AudioContext type leaks through the
|
|
21
|
+
* transport's public surface (design doc §0 D1).
|
|
22
|
+
*/
|
|
23
|
+
export interface ClockBackend {
|
|
24
|
+
/** Current audio time in seconds. */
|
|
25
|
+
nowSec(): number;
|
|
26
|
+
/** Arm an audio event at a precise future audio time. Returns a cancel handle. */
|
|
27
|
+
armAt(audioTimeSec: number, payload: unknown): CancelHandle;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface ArmedRecord {
|
|
31
|
+
audioTimeSec: number;
|
|
32
|
+
payload: unknown;
|
|
33
|
+
armedAtNowSec: number;
|
|
34
|
+
cancelled: boolean;
|
|
35
|
+
occurred: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Headless, fully deterministic backend. Time only moves when the test advances it (no wall-clock
|
|
40
|
+
* flakiness). Records arms + occurrences for assertions, and actually OCCURS armed events when virtual
|
|
41
|
+
* time passes their target — so tests can prove cancellation, not just callback invocation.
|
|
42
|
+
*/
|
|
43
|
+
export class VirtualClockBackend implements ClockBackend {
|
|
44
|
+
private _now: number;
|
|
45
|
+
readonly armed: ArmedRecord[];
|
|
46
|
+
readonly occurrences: Array<{ audioTimeSec: number; payload: unknown }>;
|
|
47
|
+
|
|
48
|
+
constructor(startSec = 0) {
|
|
49
|
+
this._now = startSec;
|
|
50
|
+
this.armed = [];
|
|
51
|
+
this.occurrences = [];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
nowSec(): number {
|
|
55
|
+
return this._now;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Arm an audio event at a precise future audio time. Returns a cancel handle (true if it cancelled). */
|
|
59
|
+
armAt(audioTimeSec: number, payload: unknown): CancelHandle {
|
|
60
|
+
const rec: ArmedRecord = {
|
|
61
|
+
audioTimeSec,
|
|
62
|
+
payload,
|
|
63
|
+
armedAtNowSec: this._now,
|
|
64
|
+
cancelled: false,
|
|
65
|
+
occurred: false,
|
|
66
|
+
};
|
|
67
|
+
this.armed.push(rec);
|
|
68
|
+
return () => {
|
|
69
|
+
if (rec.occurred || rec.cancelled) return false;
|
|
70
|
+
rec.cancelled = true;
|
|
71
|
+
return true;
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Advance virtual audio time. Marks armed events occurred (for cancellation assertions only — the
|
|
76
|
+
* Transport, not the backend, fires them). A cancelled event never occurs. */
|
|
77
|
+
advance(dtSec: number, jitterSec = 0): number {
|
|
78
|
+
const step = Math.max(0, dtSec + jitterSec);
|
|
79
|
+
this._now += step;
|
|
80
|
+
for (const r of this.armed) {
|
|
81
|
+
if (!r.cancelled && !r.occurred && r.audioTimeSec <= this._now + 1e-12) {
|
|
82
|
+
r.occurred = true;
|
|
83
|
+
this.occurrences.push(r);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return this._now;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Events armed at least `leadSec` before their target (proof of look-ahead). */
|
|
90
|
+
armedAheadBy(leadSec: number): ArmedRecord[] {
|
|
91
|
+
return this.armed.filter((a) => a.audioTimeSec - a.armedAtNowSec >= leadSec - 1e-9);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Count of events that actually occurred (not cancelled) — the audible truth. */
|
|
95
|
+
get occurredCount(): number {
|
|
96
|
+
return this.occurrences.length;
|
|
97
|
+
}
|
|
98
|
+
}
|