@margoengine/netcode 0.0.0-stage → 0.1.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 +201 -0
- package/NOTICE +4 -0
- package/README.md +1306 -3
- package/dist/client.d.ts +167 -0
- package/dist/clock.d.ts +29 -0
- package/dist/extrapolate.d.ts +42 -0
- package/dist/extrapolate.js +25 -0
- package/dist/game.d.ts +68 -0
- package/dist/generate-rust.d.ts +14 -0
- package/dist/generate-rust.js +184 -0
- package/dist/generate.d.ts +25 -0
- package/dist/generate.js +156 -0
- package/dist/hitboxes.d.ts +74 -0
- package/dist/hitboxes.js +124 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +457 -0
- package/dist/interest.d.ts +101 -0
- package/dist/interest.js +166 -0
- package/dist/interpolation-delay.d.ts +114 -0
- package/dist/interpolation-delay.js +79 -0
- package/dist/interpolation-fields.d.ts +117 -0
- package/dist/interpolation-fields.js +147 -0
- package/dist/interpolation-timeline.d.ts +100 -0
- package/dist/interpolation-timeline.js +122 -0
- package/dist/interpolation.d.ts +39 -0
- package/dist/interpolation.js +61 -0
- package/dist/lag.d.ts +62 -0
- package/dist/lobby.d.ts +77 -0
- package/dist/lobby.js +96 -0
- package/dist/loopback.d.ts +92 -0
- package/dist/media.d.ts +197 -0
- package/dist/media.js +274 -0
- package/dist/migrate.d.ts +113 -0
- package/dist/migrate.js +289 -0
- package/dist/node.d.ts +101 -0
- package/dist/node.js +166 -0
- package/dist/physics.d.ts +133 -0
- package/dist/physics.js +169 -0
- package/dist/presence.d.ts +156 -0
- package/dist/presence.js +226 -0
- package/dist/protocol-asi_qndb.js +122 -0
- package/dist/protocol.d.ts +75 -0
- package/dist/relay.d.ts +152 -0
- package/dist/relay.js +235 -0
- package/dist/rollback.d.ts +131 -0
- package/dist/rollback.js +194 -0
- package/dist/rooms.d.ts +366 -0
- package/dist/rooms.js +479 -0
- package/dist/schema-CMfqK4Gu.js +616 -0
- package/dist/schema.d.ts +263 -0
- package/dist/server-DAVzHcWW.js +203 -0
- package/dist/server.d.ts +147 -0
- package/dist/shared/bytes.d.ts +36 -0
- package/dist/signal.d.ts +156 -0
- package/dist/signal.js +261 -0
- package/dist/smoothing.d.ts +76 -0
- package/dist/smoothing.js +155 -0
- package/dist/transport-DeQodwyv.js +49 -0
- package/dist/transport.d.ts +76 -0
- package/dist/webrtc.d.ts +32 -0
- package/dist/webrtc.js +64 -0
- package/dist/websocket.d.ts +27 -0
- package/dist/websocket.js +42 -0
- package/dist/webtransport.d.ts +83 -0
- package/dist/webtransport.js +120 -0
- package/package.json +140 -6
package/dist/media.d.ts
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import type { PeerMesh } from './signal.js';
|
|
2
|
+
/** Who an event is about: a peer's room id, or `'self'` for this end. */
|
|
3
|
+
export type MediaPeer = number | 'self';
|
|
4
|
+
/** Options of {@link MediaSession}. */
|
|
5
|
+
export interface MediaSessionOptions {
|
|
6
|
+
/** The `navigator.mediaDevices` to use (default the global one, in a browser). */
|
|
7
|
+
mediaDevices?: Pick<MediaDevices, 'getUserMedia' | 'getDisplayMedia'>;
|
|
8
|
+
/**
|
|
9
|
+
* The Web Audio context that plays remote voices and measures levels (default: one is made on first use). Without
|
|
10
|
+
* Web Audio (no `AudioContext` and none passed) voices are not played or measured: remote streams are still given on
|
|
11
|
+
* `peer.stream` for your own `<audio>` element.
|
|
12
|
+
*/
|
|
13
|
+
audioContext?: AudioContext;
|
|
14
|
+
/**
|
|
15
|
+
* Gives a remote voice its own place in your audio graph, for panning in 3D. It gets the peer's id, the peer's
|
|
16
|
+
* volume node and the context, and returns the AudioNode to connect it to (a PannerNode, say, that you have
|
|
17
|
+
* connected onward); return nothing to play it straight to `context.destination`.
|
|
18
|
+
*/
|
|
19
|
+
spatial?(peer: number, volume: GainNode, context: AudioContext): AudioNode | void;
|
|
20
|
+
/** Microphone constraints (default echo cancellation, noise suppression and automatic gain control all on). */
|
|
21
|
+
audio?: MediaTrackConstraints;
|
|
22
|
+
/** Start with the microphone closed until {@link MediaSession.talk} is pressed (default false). */
|
|
23
|
+
pushToTalk?: boolean;
|
|
24
|
+
/** RMS level (0 to 1) above which someone starts speaking (default 0.04). */
|
|
25
|
+
speakingOn?: number;
|
|
26
|
+
/** RMS level below which speech may stop (default 0.02): the gap to `speakingOn` is the hysteresis. */
|
|
27
|
+
speakingOff?: number;
|
|
28
|
+
/** Milliseconds the level must stay below `speakingOff` before speech stops (default 250). */
|
|
29
|
+
speakingHangMs?: number;
|
|
30
|
+
/** Milliseconds between level reads (default 50). 0 reads only on {@link MediaSession.poll}. */
|
|
31
|
+
pollMs?: number;
|
|
32
|
+
/** The clock in milliseconds (default `performance.now`). */
|
|
33
|
+
now?: () => number;
|
|
34
|
+
}
|
|
35
|
+
/** Options of {@link MediaSession.startVoice} and {@link MediaSession.startScreenShare}. */
|
|
36
|
+
export interface MediaStartOptions {
|
|
37
|
+
/** Aborts the start (it rejects with the signal's reason, and anything captured meanwhile is stopped). */
|
|
38
|
+
signal?: AbortSignal;
|
|
39
|
+
}
|
|
40
|
+
/** Options of {@link MediaSession.startScreenShare}. */
|
|
41
|
+
export interface ScreenShareOptions extends MediaStartOptions {
|
|
42
|
+
/** `getDisplayMedia` constraints (default `{ video: true, audio: false }`). */
|
|
43
|
+
constraints?: DisplayMediaStreamOptions;
|
|
44
|
+
}
|
|
45
|
+
/** What a peer sends: its voice stream (audio only) and its screen stream (has video). */
|
|
46
|
+
export interface RemoteMedia {
|
|
47
|
+
readonly peer: number;
|
|
48
|
+
/** The peer's voice, or null while it sends none. */
|
|
49
|
+
voice: MediaStream | null;
|
|
50
|
+
/** The peer's shared screen (and its system audio, if shared), or null. */
|
|
51
|
+
screen: MediaStream | null;
|
|
52
|
+
/** Volume from 0 up (default 1). Read it back with {@link MediaSession.volume}. */
|
|
53
|
+
volume: number;
|
|
54
|
+
/** True when this end has muted that peer's voice. */
|
|
55
|
+
muted: boolean;
|
|
56
|
+
/** True while the peer is speaking. */
|
|
57
|
+
speaking: boolean;
|
|
58
|
+
}
|
|
59
|
+
/** Event types of {@link MediaSession}. */
|
|
60
|
+
export interface MediaEventMap {
|
|
61
|
+
/** A peer or this end started or stopped speaking. */
|
|
62
|
+
speaking: {
|
|
63
|
+
peer: MediaPeer;
|
|
64
|
+
speaking: boolean;
|
|
65
|
+
};
|
|
66
|
+
/** A peer's voice or screen appeared (`active` true) or went. */
|
|
67
|
+
remote: {
|
|
68
|
+
peer: number;
|
|
69
|
+
kind: 'voice' | 'screen';
|
|
70
|
+
active: boolean;
|
|
71
|
+
stream: MediaStream | null;
|
|
72
|
+
};
|
|
73
|
+
/** This end's own screen share ended (stopped, or the user used the browser's stop button). */
|
|
74
|
+
screenended: {
|
|
75
|
+
peer: 'self';
|
|
76
|
+
};
|
|
77
|
+
/** A link failed to renegotiate or a track could not be added. */
|
|
78
|
+
error: {
|
|
79
|
+
peer: MediaPeer;
|
|
80
|
+
error: unknown;
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** The event {@link MediaSession} dispatches: `detail` is the payload in {@link MediaEventMap}. */
|
|
84
|
+
export declare class MediaSessionEvent<K extends keyof MediaEventMap = keyof MediaEventMap> extends Event {
|
|
85
|
+
readonly detail: MediaEventMap[K];
|
|
86
|
+
constructor(type: K, detail: MediaEventMap[K]);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Decides when someone is speaking from a stream of levels, with hysteresis so a voice that wavers around one line
|
|
90
|
+
* does not flicker: speech starts above `on`, and stops only after the level has stayed under `off` for `hangMs`.
|
|
91
|
+
*/
|
|
92
|
+
export declare class SpeakingDetector {
|
|
93
|
+
readonly on: number;
|
|
94
|
+
readonly off: number;
|
|
95
|
+
readonly hangMs: number;
|
|
96
|
+
speaking: boolean;
|
|
97
|
+
private quietSince;
|
|
98
|
+
constructor(on?: number, off?: number, hangMs?: number);
|
|
99
|
+
/** Feeds one level at time `now` (ms); returns true when `speaking` changed. */
|
|
100
|
+
update(level: number, now: number): boolean;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Voice chat and screen share for the peers of a {@link PeerMesh}. Start the microphone with
|
|
104
|
+
* {@link MediaSession.startVoice} and a screen with {@link MediaSession.startScreenShare}: tracks are added to every
|
|
105
|
+
* link now and to each link made later, and the mesh renegotiates. A remote stream with video is a screen; one with
|
|
106
|
+
* only audio is a voice. Many peers may share at once.
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* ```ts
|
|
110
|
+
* const media = new MediaSession(mesh, { pushToTalk: false });
|
|
111
|
+
* media.addEventListener('speaking', (event) => console.log((event as MediaSessionEvent<'speaking'>).detail));
|
|
112
|
+
* await media.startVoice({ signal: AbortSignal.timeout(10_000) });
|
|
113
|
+
* media.setMuted(true);
|
|
114
|
+
* await media.startScreenShare();
|
|
115
|
+
* media.dispose(); // stops the microphone and the screen
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
export declare class MediaSession extends EventTarget {
|
|
119
|
+
private readonly mesh;
|
|
120
|
+
/** What each peer sends now. */
|
|
121
|
+
readonly remotes: Map<number, RemoteMedia>;
|
|
122
|
+
private readonly devices;
|
|
123
|
+
private context;
|
|
124
|
+
private readonly options;
|
|
125
|
+
private readonly now;
|
|
126
|
+
private readonly sent;
|
|
127
|
+
private readonly voices;
|
|
128
|
+
private readonly meters;
|
|
129
|
+
private readonly cleanup;
|
|
130
|
+
private timer;
|
|
131
|
+
private ptt;
|
|
132
|
+
private talking;
|
|
133
|
+
private muted;
|
|
134
|
+
private disposed;
|
|
135
|
+
private before;
|
|
136
|
+
private beforeUnlink;
|
|
137
|
+
/** @throws MargoError `unsupported` when there is no `navigator.mediaDevices` here and none was passed. */
|
|
138
|
+
constructor(mesh: PeerMesh, options?: MediaSessionOptions);
|
|
139
|
+
private emit;
|
|
140
|
+
/** Events of one type as an async iterator; it ends when `signal` aborts or the session is disposed. */
|
|
141
|
+
events<K extends keyof MediaEventMap>(type: K, { signal }?: {
|
|
142
|
+
signal?: AbortSignal;
|
|
143
|
+
}): AsyncGenerator<MediaEventMap[K]>;
|
|
144
|
+
private audio;
|
|
145
|
+
private meter;
|
|
146
|
+
/** Reads every level once and emits `speaking` events on changes. Runs by itself every `pollMs`; call it to step by hand. */
|
|
147
|
+
poll(): void;
|
|
148
|
+
private capture;
|
|
149
|
+
private send;
|
|
150
|
+
private addTracks;
|
|
151
|
+
private unsend;
|
|
152
|
+
/** Whether the microphone is open now: not muted, and (with push-to-talk) the talk key is down. */
|
|
153
|
+
open(): boolean;
|
|
154
|
+
private applyOpen;
|
|
155
|
+
/**
|
|
156
|
+
* Opens the microphone (`getUserMedia`, echo cancellation, noise suppression and automatic gain control on unless
|
|
157
|
+
* `audio` says otherwise) and sends it to every peer, now and later.
|
|
158
|
+
* @throws MargoError `state` when it is already on; `unsupported` without a microphone API; the signal's reason when
|
|
159
|
+
* `signal` aborts; the browser's error (a `NotAllowedError` for a refused permission) otherwise.
|
|
160
|
+
*/
|
|
161
|
+
startVoice({ signal }?: MediaStartOptions): Promise<void>;
|
|
162
|
+
/** Closes the microphone and removes it from every link. */
|
|
163
|
+
stopVoice(): void;
|
|
164
|
+
/** Mutes or unmutes the microphone for everyone (the track stays on the link, sending silence). */
|
|
165
|
+
setMuted(muted: boolean): void;
|
|
166
|
+
/** True while the microphone is muted. */
|
|
167
|
+
get isMuted(): boolean;
|
|
168
|
+
/** Turns push-to-talk on or off. On, the microphone is closed until {@link MediaSession.talk}`(true)`. */
|
|
169
|
+
setPushToTalk(enabled: boolean): void;
|
|
170
|
+
/** Presses (`true`) or releases (`false`) the talk key. Only matters while push-to-talk is on. */
|
|
171
|
+
talk(down: boolean): void;
|
|
172
|
+
/**
|
|
173
|
+
* Shares a screen, window or tab (`getDisplayMedia`) with every peer. Stopping it from the browser's own control
|
|
174
|
+
* ends the share and emits `screenended`.
|
|
175
|
+
* @throws MargoError `state` when a share is already on; the signal's reason when `signal` aborts; the browser's
|
|
176
|
+
* error (a `NotAllowedError` when the user declines) otherwise.
|
|
177
|
+
*/
|
|
178
|
+
startScreenShare({ signal, constraints }?: ScreenShareOptions): Promise<void>;
|
|
179
|
+
/** Stops sharing the screen and removes it from every link. */
|
|
180
|
+
stopScreenShare(): void;
|
|
181
|
+
/** Sets a peer's playback volume (0 and up, default 1). */
|
|
182
|
+
setVolume(peer: number, volume: number): void;
|
|
183
|
+
/** Mutes or unmutes one peer's voice for this end only. */
|
|
184
|
+
mutePeer(peer: number, muted: boolean): void;
|
|
185
|
+
private applyVolume;
|
|
186
|
+
private remote;
|
|
187
|
+
private attach;
|
|
188
|
+
private receive;
|
|
189
|
+
private lose;
|
|
190
|
+
private play;
|
|
191
|
+
private unplay;
|
|
192
|
+
private detach;
|
|
193
|
+
/** Stops every track this end sends, leaves the mesh's hooks and ends event iterators. The mesh and its links stay. */
|
|
194
|
+
dispose(): void;
|
|
195
|
+
/** Same as {@link MediaSession.dispose}, for `using`. */
|
|
196
|
+
[Symbol.dispose](): void;
|
|
197
|
+
}
|
package/dist/media.js
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import { r as e } from "./transport-DeQodwyv.js";
|
|
2
|
+
//#region src/media.ts
|
|
3
|
+
var t = class extends Event {
|
|
4
|
+
constructor(e, t) {
|
|
5
|
+
super(e), this.detail = t;
|
|
6
|
+
}
|
|
7
|
+
}, n = class {
|
|
8
|
+
constructor(e = .04, t = .02, n = 250) {
|
|
9
|
+
if (this.on = e, this.off = t, this.hangMs = n, this.speaking = !1, this.quietSince = null, !(t >= 0 && e > t)) throw RangeError(`SpeakingDetector needs 0 <= off < on; got off ${t}, on ${e}`);
|
|
10
|
+
}
|
|
11
|
+
update(e, t) {
|
|
12
|
+
return e >= this.on ? (this.quietSince = null, this.speaking ? !1 : this.speaking = !0) : !this.speaking || e >= this.off ? (this.quietSince = null, !1) : (this.quietSince ??= t, t - this.quietSince < this.hangMs ? !1 : (this.speaking = !1, this.quietSince = null, !0));
|
|
13
|
+
}
|
|
14
|
+
}, r = (e) => {
|
|
15
|
+
let t = 0;
|
|
16
|
+
for (let n = 0; n < e.length; n++) t += e[n] * e[n];
|
|
17
|
+
return e.length ? Math.sqrt(t / e.length) : 0;
|
|
18
|
+
}, i = class extends EventTarget {
|
|
19
|
+
constructor(t, n = {}) {
|
|
20
|
+
if (super(), this.mesh = t, this.remotes = /* @__PURE__ */ new Map(), this.sent = /* @__PURE__ */ new Map(), this.voices = /* @__PURE__ */ new Map(), this.meters = /* @__PURE__ */ new Map(), this.cleanup = [], this.talking = !1, this.muted = !1, this.disposed = !1, this.options = n, this.devices = n.mediaDevices ?? globalThis.navigator?.mediaDevices, !this.devices) throw e("unsupported", "MediaSession needs navigator.mediaDevices; run it in a browser (HTTPS) or pass mediaDevices");
|
|
21
|
+
this.context = n.audioContext, this.now = n.now ?? (() => performance.now()), this.ptt = n.pushToTalk ?? !1;
|
|
22
|
+
let r = this.before = t.onlink, i = t.onunlink;
|
|
23
|
+
this.beforeUnlink = i, t.onlink = (e, t) => {
|
|
24
|
+
r?.(e, t), this.attach(e, t);
|
|
25
|
+
}, t.onunlink = (e, t) => {
|
|
26
|
+
i?.(e, t), this.detach(e);
|
|
27
|
+
};
|
|
28
|
+
for (let [e, n] of t.peerConnections) this.attach(e, n);
|
|
29
|
+
let a = n.pollMs ?? 50;
|
|
30
|
+
a > 0 && (this.timer = setInterval(() => this.poll(), a), this.timer.unref?.());
|
|
31
|
+
}
|
|
32
|
+
emit(e, n) {
|
|
33
|
+
this.dispatchEvent(new t(e, n));
|
|
34
|
+
}
|
|
35
|
+
async *events(e, { signal: t } = {}) {
|
|
36
|
+
let n = [], r, i = (e) => {
|
|
37
|
+
n.push(e.detail), r?.();
|
|
38
|
+
}, a = () => r?.();
|
|
39
|
+
this.addEventListener(e, i), this.addEventListener("dispose", a), t?.addEventListener("abort", a);
|
|
40
|
+
try {
|
|
41
|
+
for (; !t?.aborted && !this.disposed;) n.length ? yield n.shift() : await new Promise((e) => r = e);
|
|
42
|
+
} finally {
|
|
43
|
+
this.removeEventListener(e, i), this.removeEventListener("dispose", a), t?.removeEventListener("abort", a);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
audio() {
|
|
47
|
+
if (this.context) return this.context;
|
|
48
|
+
let e = globalThis.AudioContext;
|
|
49
|
+
return e ? this.context = new e() : void 0;
|
|
50
|
+
}
|
|
51
|
+
meter(e, t) {
|
|
52
|
+
let r = this.audio();
|
|
53
|
+
if (!r) return;
|
|
54
|
+
let i = r.createAnalyser();
|
|
55
|
+
i.fftSize = 1024, t.connect(i);
|
|
56
|
+
let a = this.options;
|
|
57
|
+
this.meters.set(e, {
|
|
58
|
+
detector: new n(a.speakingOn ?? .04, a.speakingOff ?? .02, a.speakingHangMs ?? 250),
|
|
59
|
+
analyser: i,
|
|
60
|
+
samples: new Float32Array(i.fftSize),
|
|
61
|
+
peer: e
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
poll() {
|
|
65
|
+
let e = this.now();
|
|
66
|
+
for (let t of this.meters.values()) {
|
|
67
|
+
t.analyser.getFloatTimeDomainData(t.samples);
|
|
68
|
+
let n = t.peer === "self" && !this.open() ? 0 : r(t.samples);
|
|
69
|
+
if (!t.detector.update(n, e)) continue;
|
|
70
|
+
let i = typeof t.peer == "number" ? this.remotes.get(t.peer) : void 0;
|
|
71
|
+
i && (i.speaking = t.detector.speaking), this.emit("speaking", {
|
|
72
|
+
peer: t.peer,
|
|
73
|
+
speaking: t.detector.speaking
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async capture(t, n) {
|
|
78
|
+
if (this.disposed) throw e("disposed", "MediaSession is disposed; create a new one");
|
|
79
|
+
n?.throwIfAborted();
|
|
80
|
+
let r = t(), i, a = new Promise((e, t) => {
|
|
81
|
+
i = () => t(n.reason), n?.addEventListener("abort", i, { once: !0 });
|
|
82
|
+
});
|
|
83
|
+
try {
|
|
84
|
+
return await Promise.race([r, a]);
|
|
85
|
+
} catch (e) {
|
|
86
|
+
throw r.then((e) => e.getTracks().forEach((e) => e.stop()), () => {}), e;
|
|
87
|
+
} finally {
|
|
88
|
+
i && n?.removeEventListener("abort", i);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
send(e, t) {
|
|
92
|
+
this.sent.set(e, {
|
|
93
|
+
senders: [],
|
|
94
|
+
stream: t
|
|
95
|
+
});
|
|
96
|
+
for (let [t, n] of this.mesh.peerConnections) this.addTracks(e, t, n);
|
|
97
|
+
}
|
|
98
|
+
addTracks(e, t, n) {
|
|
99
|
+
let r = this.sent.get(e);
|
|
100
|
+
if (r) try {
|
|
101
|
+
for (let e of r.stream.getTracks()) r.senders.push(n.addTrack(e, r.stream));
|
|
102
|
+
} catch (e) {
|
|
103
|
+
this.emit("error", {
|
|
104
|
+
peer: t,
|
|
105
|
+
error: e
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
unsend(e) {
|
|
110
|
+
let t = this.sent.get(e);
|
|
111
|
+
if (t) {
|
|
112
|
+
this.sent.delete(e);
|
|
113
|
+
for (let [e, n] of this.mesh.peerConnections) for (let r of t.senders) if (n.getSenders().includes(r)) try {
|
|
114
|
+
n.removeTrack(r);
|
|
115
|
+
} catch (t) {
|
|
116
|
+
this.emit("error", {
|
|
117
|
+
peer: e,
|
|
118
|
+
error: t
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
for (let e of t.stream.getTracks()) e.stop();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
open() {
|
|
125
|
+
return !this.muted && (!this.ptt || this.talking);
|
|
126
|
+
}
|
|
127
|
+
applyOpen() {
|
|
128
|
+
for (let e of this.sent.get("voice")?.stream.getAudioTracks() ?? []) e.enabled = this.open();
|
|
129
|
+
}
|
|
130
|
+
async startVoice({ signal: t } = {}) {
|
|
131
|
+
if (this.sent.has("voice")) throw e("state", "Voice is already on; call stopVoice first");
|
|
132
|
+
let n = await this.capture(() => this.devices.getUserMedia({
|
|
133
|
+
audio: {
|
|
134
|
+
echoCancellation: !0,
|
|
135
|
+
noiseSuppression: !0,
|
|
136
|
+
autoGainControl: !0,
|
|
137
|
+
...this.options.audio
|
|
138
|
+
},
|
|
139
|
+
video: !1
|
|
140
|
+
}), t);
|
|
141
|
+
if (this.sent.has("voice") || this.disposed) {
|
|
142
|
+
for (let e of n.getTracks()) e.stop();
|
|
143
|
+
throw this.disposed ? e("disposed", "MediaSession is disposed; create a new one") : e("state", "Voice is already on; call stopVoice first");
|
|
144
|
+
}
|
|
145
|
+
this.send("voice", n), this.applyOpen();
|
|
146
|
+
let r = this.audio();
|
|
147
|
+
r && this.meter("self", r.createMediaStreamSource(n));
|
|
148
|
+
}
|
|
149
|
+
stopVoice() {
|
|
150
|
+
this.unsend("voice"), this.meters.delete("self");
|
|
151
|
+
}
|
|
152
|
+
setMuted(e) {
|
|
153
|
+
this.muted = e, this.applyOpen();
|
|
154
|
+
}
|
|
155
|
+
get isMuted() {
|
|
156
|
+
return this.muted;
|
|
157
|
+
}
|
|
158
|
+
setPushToTalk(e) {
|
|
159
|
+
this.ptt = e, this.applyOpen();
|
|
160
|
+
}
|
|
161
|
+
talk(e) {
|
|
162
|
+
this.talking = e, this.applyOpen();
|
|
163
|
+
}
|
|
164
|
+
async startScreenShare({ signal: t, constraints: n = {
|
|
165
|
+
video: !0,
|
|
166
|
+
audio: !1
|
|
167
|
+
} } = {}) {
|
|
168
|
+
if (this.sent.has("screen")) throw e("state", "A screen is already shared; call stopScreenShare first");
|
|
169
|
+
let r = await this.capture(() => this.devices.getDisplayMedia(n), t);
|
|
170
|
+
if (this.sent.has("screen") || this.disposed) {
|
|
171
|
+
for (let e of r.getTracks()) e.stop();
|
|
172
|
+
throw this.disposed ? e("disposed", "MediaSession is disposed; create a new one") : e("state", "A screen is already shared; call stopScreenShare first");
|
|
173
|
+
}
|
|
174
|
+
let i = () => {
|
|
175
|
+
this.sent.get("screen")?.stream === r && (this.stopScreenShare(), this.emit("screenended", { peer: "self" }));
|
|
176
|
+
};
|
|
177
|
+
for (let e of r.getVideoTracks()) e.addEventListener("ended", i, { once: !0 });
|
|
178
|
+
this.send("screen", r);
|
|
179
|
+
}
|
|
180
|
+
stopScreenShare() {
|
|
181
|
+
this.unsend("screen");
|
|
182
|
+
}
|
|
183
|
+
setVolume(e, t) {
|
|
184
|
+
if (!(t >= 0)) throw RangeError(`volume is ${t}; pass 0 or more`);
|
|
185
|
+
let n = this.remotes.get(e);
|
|
186
|
+
n && (n.volume = t, this.applyVolume(e));
|
|
187
|
+
}
|
|
188
|
+
mutePeer(e, t) {
|
|
189
|
+
let n = this.remotes.get(e);
|
|
190
|
+
n && (n.muted = t, this.applyVolume(e));
|
|
191
|
+
}
|
|
192
|
+
applyVolume(e) {
|
|
193
|
+
let t = this.remotes.get(e), n = this.voices.get(e);
|
|
194
|
+
t && n && (n.volume.gain.value = t.muted ? 0 : t.volume);
|
|
195
|
+
}
|
|
196
|
+
remote(e) {
|
|
197
|
+
let t = this.remotes.get(e);
|
|
198
|
+
return t || this.remotes.set(e, t = {
|
|
199
|
+
peer: e,
|
|
200
|
+
voice: null,
|
|
201
|
+
screen: null,
|
|
202
|
+
volume: 1,
|
|
203
|
+
muted: !1,
|
|
204
|
+
speaking: !1
|
|
205
|
+
}), t;
|
|
206
|
+
}
|
|
207
|
+
attach(e, t) {
|
|
208
|
+
for (let n of ["voice", "screen"]) this.addTracks(n, e, t);
|
|
209
|
+
let n = (t) => {
|
|
210
|
+
let n = t.streams[0] ?? new MediaStream([t.track]), r = n.getVideoTracks().length || t.track.kind === "video" ? "screen" : "voice";
|
|
211
|
+
this.receive(e, r, n);
|
|
212
|
+
let i = () => this.lose(e, r, n);
|
|
213
|
+
n.addEventListener("removetrack", () => {
|
|
214
|
+
n.getTracks().length || i();
|
|
215
|
+
}), t.track.addEventListener("ended", i, { once: !0 });
|
|
216
|
+
};
|
|
217
|
+
t.addEventListener("track", n), this.cleanup.push(() => t.removeEventListener("track", n));
|
|
218
|
+
}
|
|
219
|
+
receive(e, t, n) {
|
|
220
|
+
let r = this.remote(e);
|
|
221
|
+
r[t] !== n && (r[t] = n, t === "voice" && this.play(e, n), this.emit("remote", {
|
|
222
|
+
peer: e,
|
|
223
|
+
kind: t,
|
|
224
|
+
active: !0,
|
|
225
|
+
stream: n
|
|
226
|
+
}));
|
|
227
|
+
}
|
|
228
|
+
lose(e, t, n) {
|
|
229
|
+
let r = this.remotes.get(e);
|
|
230
|
+
r && r[t] === n && (r[t] = null, t === "voice" && this.unplay(e), this.emit("remote", {
|
|
231
|
+
peer: e,
|
|
232
|
+
kind: t,
|
|
233
|
+
active: !1,
|
|
234
|
+
stream: null
|
|
235
|
+
}));
|
|
236
|
+
}
|
|
237
|
+
play(e, t) {
|
|
238
|
+
let n = this.audio();
|
|
239
|
+
if (!n) return;
|
|
240
|
+
this.unplay(e);
|
|
241
|
+
let r = n.createMediaStreamSource(t), i = n.createGain();
|
|
242
|
+
r.connect(i), this.meter(e, r), this.voices.set(e, {
|
|
243
|
+
source: r,
|
|
244
|
+
volume: i
|
|
245
|
+
}), this.applyVolume(e), i.connect(this.options.spatial?.(e, i, n) ?? n.destination);
|
|
246
|
+
}
|
|
247
|
+
unplay(e) {
|
|
248
|
+
let t = this.voices.get(e);
|
|
249
|
+
if (!t) return;
|
|
250
|
+
t.source.disconnect(), t.volume.disconnect(), this.voices.delete(e), this.meters.delete(e);
|
|
251
|
+
let n = this.remotes.get(e);
|
|
252
|
+
n?.speaking && (n.speaking = !1, this.emit("speaking", {
|
|
253
|
+
peer: e,
|
|
254
|
+
speaking: !1
|
|
255
|
+
}));
|
|
256
|
+
}
|
|
257
|
+
detach(e) {
|
|
258
|
+
let t = this.remotes.get(e);
|
|
259
|
+
t?.voice && this.lose(e, "voice", t.voice), t?.screen && this.lose(e, "screen", t.screen), this.remotes.delete(e);
|
|
260
|
+
}
|
|
261
|
+
dispose() {
|
|
262
|
+
if (!this.disposed) {
|
|
263
|
+
this.stopVoice(), this.stopScreenShare(), this.disposed = !0, clearInterval(this.timer);
|
|
264
|
+
for (let e of [...this.remotes.keys()]) this.detach(e);
|
|
265
|
+
for (let e of this.cleanup.splice(0)) e();
|
|
266
|
+
this.mesh.onlink = this.before, this.mesh.onunlink = this.beforeUnlink, this.dispatchEvent(new Event("dispose"));
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
[Symbol.dispose]() {
|
|
270
|
+
this.dispose();
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
//#endregion
|
|
274
|
+
export { i as MediaSession, t as MediaSessionEvent, n as SpeakingDetector };
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { type SchemaCodec, type SchemaShape, type UntypedSchema } from './schema.js';
|
|
2
|
+
import { type Connection } from './transport.js';
|
|
3
|
+
/** A detached confirmed checkpoint and authority epoch. */
|
|
4
|
+
export interface MigrationState<State> {
|
|
5
|
+
/** Elected peer id. */
|
|
6
|
+
host: number;
|
|
7
|
+
/** Authority generation, incremented on handoff/recovery. */
|
|
8
|
+
epoch: number;
|
|
9
|
+
/** Confirmed simulation frame to resume. */
|
|
10
|
+
frame: number;
|
|
11
|
+
/** Canonical decoded state; changing it never changes the saved checkpoint. */
|
|
12
|
+
state: State;
|
|
13
|
+
}
|
|
14
|
+
/** Configuration of one peer in a trusted full mesh. */
|
|
15
|
+
export interface HostMigrationOptions<State> {
|
|
16
|
+
/** Shared state schema. */
|
|
17
|
+
schema: SchemaCodec<SchemaShape> | UntypedSchema;
|
|
18
|
+
/** Name of the state struct. */
|
|
19
|
+
stateType: string;
|
|
20
|
+
/** Local unsigned player id. */
|
|
21
|
+
local: number;
|
|
22
|
+
/** Open reliable links to every other peer; this session owns and closes them. */
|
|
23
|
+
peers: ReadonlyMap<number, Connection>;
|
|
24
|
+
/** Initial host, default lowest player id. Same on all peers. */
|
|
25
|
+
host?: number;
|
|
26
|
+
/** Common starting state. */
|
|
27
|
+
initial: State;
|
|
28
|
+
/** Starting frame, default 0. */
|
|
29
|
+
frame?: number;
|
|
30
|
+
/** Confirmation, transfer, recovery and wait timeout in milliseconds, default 10000. */
|
|
31
|
+
timeout?: number;
|
|
32
|
+
/** Maximum encoded checkpoint bytes, default 1048576, at most 16777216. */
|
|
33
|
+
maxSnapshotBytes?: number;
|
|
34
|
+
/** Recovery failures, default console.error. Public operations also reject their promises. */
|
|
35
|
+
onerror?(error: unknown): void;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* P2P authority migration from replicated confirmed state. Serial checkpoints are prepared and committed on every
|
|
39
|
+
* connected peer. Recovery chooses the newest checkpoint common to the surviving mesh, then resumes the lowest id.
|
|
40
|
+
* Requires trusted peers and a connected full mesh, not arbitrary network partitions or Byzantine consensus.
|
|
41
|
+
*/
|
|
42
|
+
export declare class HostMigration<State> {
|
|
43
|
+
private readonly options;
|
|
44
|
+
private readonly schema;
|
|
45
|
+
private readonly links;
|
|
46
|
+
private readonly timeout;
|
|
47
|
+
private readonly maxBytes;
|
|
48
|
+
private history;
|
|
49
|
+
private prepared;
|
|
50
|
+
private hostId;
|
|
51
|
+
private epochNumber;
|
|
52
|
+
private ready;
|
|
53
|
+
private closed;
|
|
54
|
+
private pending;
|
|
55
|
+
private reports;
|
|
56
|
+
private future;
|
|
57
|
+
private resuming;
|
|
58
|
+
private transferFrom;
|
|
59
|
+
private recoveryTimer;
|
|
60
|
+
private readonly waiters;
|
|
61
|
+
/** @throws TypeError/RangeError for inconsistent roster, invalid limits or a state the schema cannot encode. */
|
|
62
|
+
constructor(options: HostMigrationOptions<State>);
|
|
63
|
+
/** Current host; undefined during crash recovery. */
|
|
64
|
+
get host(): number | undefined;
|
|
65
|
+
/** Only a ready local authority may simulate or publish new confirmed state. */
|
|
66
|
+
get isHost(): boolean;
|
|
67
|
+
/** Current authority generation. */
|
|
68
|
+
get epoch(): number;
|
|
69
|
+
/** A fresh decoded copy of the latest locally committed checkpoint. */
|
|
70
|
+
get confirmed(): {
|
|
71
|
+
frame: number;
|
|
72
|
+
state: State;
|
|
73
|
+
};
|
|
74
|
+
private get current();
|
|
75
|
+
private members;
|
|
76
|
+
private encode;
|
|
77
|
+
private packet;
|
|
78
|
+
private send;
|
|
79
|
+
private broadcast;
|
|
80
|
+
private save;
|
|
81
|
+
private authority;
|
|
82
|
+
/**
|
|
83
|
+
* Replicate a canonical checkpoint to every connected peer. Resolves after every peer stored its commit.
|
|
84
|
+
* Abort/timeout retires this session and closes its links, preventing reuse of an uncertain checkpoint.
|
|
85
|
+
* @throws MargoError `failed` outside host authority; RangeError for a frame that does not advance.
|
|
86
|
+
*/
|
|
87
|
+
confirm(state: State, frame: number, options?: {
|
|
88
|
+
signal?: AbortSignal;
|
|
89
|
+
}): Promise<void>;
|
|
90
|
+
/** Transfer authority to any connected peer without leaving. Resolves once every peer accepted the handoff. */
|
|
91
|
+
handoff(target: number, options?: {
|
|
92
|
+
signal?: AbortSignal;
|
|
93
|
+
}): Promise<void>;
|
|
94
|
+
private operation;
|
|
95
|
+
private progress;
|
|
96
|
+
private validate;
|
|
97
|
+
private receive;
|
|
98
|
+
private lost;
|
|
99
|
+
private beginRecovery;
|
|
100
|
+
private recover;
|
|
101
|
+
private completeRecovery;
|
|
102
|
+
private clearRecovery;
|
|
103
|
+
private result;
|
|
104
|
+
private notify;
|
|
105
|
+
/** Wait for a ready authority and restored checkpoint. Bounded by timeout and optional AbortSignal. */
|
|
106
|
+
waitForHost(options?: {
|
|
107
|
+
signal?: AbortSignal;
|
|
108
|
+
}): Promise<MigrationState<State>>;
|
|
109
|
+
/** Leave the mesh, rejecting waits and notifying peers through their connection close events. Idempotent. */
|
|
110
|
+
close(): void;
|
|
111
|
+
/** Leave, for using. */
|
|
112
|
+
[Symbol.dispose](): void;
|
|
113
|
+
}
|