sigelo-contact 0.1.13 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +13 -10
  2. package/call.mjs +727 -0
  3. package/carrier.mjs +1204 -137
  4. package/control.mjs +81 -22
  5. package/device.mjs +1 -1
  6. package/enrol.mjs +239 -43
  7. package/gen-carrier.mjs +4 -4
  8. package/gen-device.mjs +2 -2
  9. package/gen-envelope.mjs +3 -3
  10. package/gen-invite.mjs +3 -3
  11. package/gen-short.mjs +3 -3
  12. package/group.mjs +616 -0
  13. package/invite.mjs +63 -13
  14. package/kdf.mjs +1 -1
  15. package/link.mjs +24 -16
  16. package/package.json +49 -7
  17. package/page.mjs +1172 -70
  18. package/photo.mjs +37 -0
  19. package/platform-node.mjs +125 -18
  20. package/prekeys.mjs +10 -2
  21. package/public.mjs +93 -0
  22. package/relays.mjs +1 -1
  23. package/restore.mjs +3 -3
  24. package/rtc-web.mjs +95 -0
  25. package/short.mjs +31 -3
  26. package/store.mjs +147 -12
  27. package/test-carrier.mjs +138 -21
  28. package/test-device.mjs +1 -1
  29. package/test-enrol.mjs +157 -8
  30. package/test-envelope.mjs +16 -3
  31. package/test-file.mjs +5 -5
  32. package/test-group.mjs +413 -0
  33. package/test-invite.mjs +15 -2
  34. package/test-link.mjs +11 -8
  35. package/test-platform.mjs +5 -5
  36. package/test-presence.mjs +169 -0
  37. package/test-push.mjs +136 -0
  38. package/test-relay-lane.mjs +248 -0
  39. package/test-short.mjs +38 -12
  40. package/test-tier.mjs +6 -6
  41. package/test-transfer-web.mjs +246 -0
  42. package/test-transfer.mjs +463 -0
  43. package/test-voice.mjs +158 -0
  44. package/test-ws.mjs +5 -5
  45. package/transfer-engine.mjs +800 -0
  46. package/transfer-node.mjs +449 -0
  47. package/transfer-web.mjs +80 -0
  48. package/transfer.mjs +388 -0
  49. package/voice-web.mjs +113 -0
  50. package/voice.mjs +65 -0
  51. package/words-lock.mjs +115 -0
package/call.mjs ADDED
@@ -0,0 +1,727 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Voice calls (design/calls.md): 1:1 audio between two paired people, the media WebRTC (Opus, DTLS-SRTP) in the page's
3
+ // own RTCPeerConnection, the signalling `sigelo-call/0` messages inside the pairing's signed envelopes. No import: the
4
+ // computer's page loads this file as it is (`/call.mjs`, beside ui.js), the phone app through its import map.
5
+ //
6
+ // Two halves:
7
+ // Line the host's, where the carrier runs (page.mjs: Node under `sigelo-agent ui`, the page itself in the phone
8
+ // app): what comes and goes over the relay, who may ring here, the ring's timers, glare, busy, "unavailable"
9
+ // with no page to ring, the chat lines ("Call · 3:12", "Missed call"); the /api/calls* routes (callRoutes).
10
+ // Phone the page's (ui.js): the microphone, the RTCPeerConnection (a fresh DTLS certificate per call), batched
11
+ // candidates, the ICE timers and restarts, mute; it reaches its Line only through /api/calls*.
12
+ //
13
+ // The messages (design §2), content {typ, id, …}, id 32 hex, kept apart by the carrier (CALL_LABEL, CALL_SEND: never in
14
+ // the inbox, the log, MCP; `watch` answers a ring `end unavailable`):
15
+ // ring caller {attempt: 1, sdp (the offer), exp (iat + 60 s), text (what an older app shows), pad}
16
+ // ringing callee {} (only to a contact this side shares presence with: it says "online")
17
+ // answer callee {attempt, sdp, pad} (attempt 1: the ring accepted; n > 1: a restart answered)
18
+ // cands either {attempt, cands: ["candidate:…"]} the candidates gathered after the offer or answer left, once
19
+ // restart caller {attempt n + 1, sdp (an ICE-restart offer), pad}
20
+ // end either {reason} hangup declined busy no_answer cancelled lost no_path unavailable
21
+ // ring, answer and restart are padded to PAD characters of JSON, so their size tells nothing. Every field is checked
22
+ // exactly (an unknown key, a wrong type: dropped); an SDP must hold one audio stream and exactly one sha-256 DTLS
23
+ // fingerprint, which the envelope's signature binds to the pairing's identities: a relay cannot stand in the middle.
24
+ //
25
+ // Timers: the caller gives up at RING_S (end no_answer); a ring past its exp is a "Missed call"; a ring with no page
26
+ // here that can take it (none polled GET /api/calls?rtc=1 within PAGE_MS) gets `end unavailable`; ICE has ICE_MS after
27
+ // the answer, else end no_path ("Could not connect directly from these two networks." No TURN in the free tier);
28
+ // roaming (Wi-Fi to mobile data, a new address): disconnected DISCONNECTED_MS (2 s), or failed, or the shell's network
29
+ // change → the caller restarts ICE with a fresh offer, again every RETRY_MS while it does not connect; both screens say
30
+ // "Reconnecting…"; LOST_MS (30 s) after the drop → end lost, "Connection lost" on the screen and in the chat. Weak links:
31
+ // Opus asked mono, DTX, in-band FEC, ptime 20, at most MAX_BPS (16 kbit/s); every STATS_MS the far end's RTCP (loss,
32
+ // round trip) steps this side's bitrate down to MIN_BPS (8 kbit/s) under loss, back up once clean, and sets the screen's
33
+ // three bars. Signalling late or out of order: candidates wait for their description, a repeat is dropped, a restart's
34
+ // candidates that come before it wait for it, an end that comes before its ring makes that ring a missed call. Glare (two rings crossing): the call
35
+ // of the smaller original DID stands, the other side drops its own and takes the ring at once (both wanted the call).
36
+ // A second call while one is live gets `end busy`. busy and unavailable, like ringing, go only to a contact shown this
37
+ // side's presence (each says the carrier runs): another one hears nothing and its call rings out ("No answer").
38
+ //
39
+ // Ringing with the app closed (design §5): not here. A ring waits at the relay; whatever wakes the app within its 60 s
40
+ // (the push build, design/push.md) finds it in the first drain and rings through Line's `alert` hook; later than that
41
+ // it is a "Missed call". That hook is the seam: alert({on, id, did, name}) — the phone app's ringtone and heads-up today.
42
+
43
+ export const CALL_LABEL = 'sigelo-call/0';
44
+ export const TYPS = Object.freeze(['ring', 'ringing', 'answer', 'cands', 'restart', 'end']);
45
+ export const REASONS = Object.freeze(['hangup', 'declined', 'busy', 'no_answer', 'cancelled', 'lost', 'no_path', 'unavailable']);
46
+ /** Seconds: the caller's wait, a ring's life. */
47
+ export const RING_S = 45, EXP_S = 60;
48
+ /** Milliseconds: gathering before the offer goes, before the late candidates go; ICE after the answer; a disconnection
49
+ * before the restart, then before the call is lost; a page's last poll for a ring to wait for it; an ended call shown. */
50
+ export const GATHER_MS = 1000, LATE_MS = 5000, ICE_MS = 15000, DISCONNECTED_MS = 2000, RETRY_MS = 8000, LOST_MS = 30000, PAGE_MS = 10000, KEEP_MS = 30000;
51
+ /** Weak links (2026-11-24): Opus at most MAX_BPS, at least MIN_BPS, stepped by the far end's RTCP every STATS_MS. */
52
+ export const MAX_BPS = 16000, MIN_BPS = 8000, STEP_BPS = 4000, STATS_MS = 3000;
53
+ /** A contact's busy or unavailable answers: at most one per REPLY_MS (a flood of rings costs this side one message a while). */
54
+ export const REPLY_MS = 30000;
55
+ export const PAD = 8192, SDP_MAX = 6144, CANDS_MAX = 16, CAND_MAX = 512, ATTEMPT_MAX = 100, TEXT_MAX = 200;
56
+ export const OLD_TEXT = 'Calling you on sigelo: update to answer';
57
+ export const NO_PATH = 'Could not connect directly from these two networks.';
58
+ export const STUN_PORT = 3478;
59
+
60
+ const ID = /^[0-9a-f]{32}$/;
61
+ const bad = (check, message, status = 400) => { throw Object.assign(new Error(message), { check, status }); };
62
+ const isInt = (v) => Number.isSafeInteger(v);
63
+ const hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
64
+ export const newCallId = () => { const b = new Uint8Array(16); globalThis.crypto.getRandomValues(b); return hex(b); };
65
+ export const mss = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
66
+ /** STUN as transfers use it (transfer-engine.mjs stunFor): this side's relay host and the contact's, port 3478. */
67
+ export const stunOf = (...relays) => [...new Set(relays.filter((r) => typeof r === 'string' && r !== '').map((r) => r.replace(/:\d+$/, '')))].map((h) => `${h}:${STUN_PORT}`);
68
+ /** A `.local` (multicast DNS) candidate dropped, as rtc-web.mjs does: resolving one would put an mDNS socket on the LAN. */
69
+ export const noMdns = (sdp) => sdp.split(/\r?\n/).filter((l) => !/^a=candidate:.* [0-9a-f-]+\.local /i.test(l)).join('\r\n');
70
+ const candsIn = (sdp) => (String(sdp).match(/^a=candidate:.*$/gm) ?? []).map((l) => l.slice(2).trim());
71
+
72
+ /** An SDP as a call takes it: ASCII, one audio stream, exactly one sha-256 DTLS fingerprint; else refused. */
73
+ export function checkSdp(sdp) {
74
+ if (typeof sdp !== 'string' || sdp.length === 0 || sdp.length > SDP_MAX) bad('sdp', `an SDP of 1 to ${SDP_MAX} characters`);
75
+ if (!sdp.startsWith('v=0') || /[^\x20-\x7e\r\n\t]/.test(sdp)) bad('sdp', 'not an SDP');
76
+ const fp = sdp.match(/^a=fingerprint:.*$/gim) ?? [];
77
+ if (fp.length !== 1) bad('sdp_fingerprint', `exactly one DTLS fingerprint, not ${fp.length}`);
78
+ if (!/^a=fingerprint:sha-256 ([0-9a-f]{2}:){31}[0-9a-f]{2}\s*$/i.test(fp[0])) bad('sdp_fingerprint', 'the fingerprint is not sha-256');
79
+ const m = sdp.match(/^m=\S+/gm) ?? [];
80
+ if (m.length !== 1 || m[0] !== 'm=audio') bad('sdp_media', 'one audio stream, nothing else');
81
+ return sdp;
82
+ }
83
+ const checkCands = (l) => {
84
+ if (!Array.isArray(l) || l.length === 0 || l.length > CANDS_MAX) bad('cands', `1 to ${CANDS_MAX} candidates`);
85
+ for (const c of l) if (typeof c !== 'string' || c.length > CAND_MAX || !/^candidate:[\x20-\x7e]+$/.test(c)) bad('cands', 'a candidate line');
86
+ return l;
87
+ };
88
+ const KEYS = { ring: ['attempt', 'sdp', 'exp', 'text'], ringing: [], answer: ['attempt', 'sdp'], cands: ['attempt', 'cands'], restart: ['attempt', 'sdp'], end: ['reason'] };
89
+ const PADDED = new Set(['ring', 'answer', 'restart']);
90
+
91
+ /** A sigelo-call/0 content checked exactly → the same object; refused (check call, sdp…) otherwise. */
92
+ export function checkSignal(x) {
93
+ if (x === null || typeof x !== 'object' || Array.isArray(x)) bad('call', 'an object');
94
+ if (!TYPS.includes(x.typ)) bad('call', 'typ: one of ' + TYPS.join(', '));
95
+ if (typeof x.id !== 'string' || !ID.test(x.id)) bad('call', 'id: 32 hex digits');
96
+ const want = new Set(['typ', 'id', ...KEYS[x.typ], ...(PADDED.has(x.typ) ? ['pad'] : [])]);
97
+ for (const k of Object.keys(x)) if (!want.has(k)) bad('call', `${x.typ}: no member ${JSON.stringify(k).slice(0, 40)}`);
98
+ for (const k of KEYS[x.typ]) if (x[k] === undefined) bad('call', `${x.typ}: ${k} missing`);
99
+ if (x.pad !== undefined && (typeof x.pad !== 'string' || x.pad.length > PAD || /[^.]/.test(x.pad))) bad('call', 'pad: dots');
100
+ if (x.attempt !== undefined && (!isInt(x.attempt) || x.attempt < 1 || x.attempt > ATTEMPT_MAX)) bad('call', `attempt: 1 to ${ATTEMPT_MAX}`);
101
+ if (x.typ === 'ring' && x.attempt !== 1) bad('call', 'ring: attempt 1');
102
+ if (x.typ === 'restart' && x.attempt < 2) bad('call', 'restart: attempt 2 or more');
103
+ if (x.sdp !== undefined) checkSdp(x.sdp);
104
+ if (x.typ === 'ring' && (!isInt(x.exp) || x.exp < 0)) bad('call', 'exp: unix seconds');
105
+ if (x.typ === 'ring' && (typeof x.text !== 'string' || x.text.length > TEXT_MAX)) bad('call', 'text: a line');
106
+ if (x.typ === 'cands') checkCands(x.cands);
107
+ if (x.typ === 'end' && !REASONS.includes(x.reason)) bad('call', 'reason: one of ' + REASONS.join(', '));
108
+ return x;
109
+ }
110
+
111
+ /** content padded with dots to PAD characters of JSON (ring, answer, restart). */
112
+ export function padded(content) {
113
+ const len = JSON.stringify({ ...content, pad: '' }).length;
114
+ return { ...content, pad: '.'.repeat(Math.max(0, PAD - len)) };
115
+ }
116
+
117
+ /** The chat line a call leaves: { text, state } (design §4: "Call · 4:12", "Missed call", "Declined"). */
118
+ export function lineOf(call, nowMs) {
119
+ if (call.connected !== null) {
120
+ const s = Math.max(0, Math.floor(((call.ended ?? nowMs) - call.connected) / 1000));
121
+ return call.reason === 'lost' ? { text: `Connection lost · ${mss(s)}`, state: 'lost', secs: s } : { text: `Call · ${mss(s)}`, state: 'done', secs: s };
122
+ }
123
+ if (call.answered !== null) return { text: 'Could not connect', state: 'failed', secs: 0 };
124
+ if (call.dir === 'in') return call.reason === 'declined' && call.by === 'me' ? { text: 'Declined', state: 'declined', secs: 0 } : { text: 'Missed call', state: 'missed', secs: 0 };
125
+ const r = call.reason;
126
+ return r === 'declined' ? { text: 'Declined', state: 'declined', secs: 0 } : r === 'busy' ? { text: 'Busy', state: 'busy', secs: 0 }
127
+ : r === 'cancelled' || r === 'hangup' ? { text: 'Cancelled', state: 'cancelled', secs: 0 } : r === 'no_path' ? { text: 'Could not connect', state: 'failed', secs: 0 }
128
+ : { text: 'No answer', state: 'no_answer', secs: 0 };
129
+ }
130
+
131
+ // ================================================================ the host's half
132
+ /**
133
+ * new Line({ send, contact, allowed, shares, me, line, alert?, audio?, changed?, now?, timers?, o? })
134
+ * send(did, content) → Promise the carrier's send, label CALL_LABEL, internal CALL_SEND
135
+ * contact(did) → { did, name, online, … } | null a live contact by its (original) DID
136
+ * allowed(c) → may that contact ring here ("Can call me"); shares(c) → may it see this side online (presence)
137
+ * me() → this identity's original DID (glare)
138
+ * line({ did, dir, text, call: { id, state, secs } }) a chat line kept in the history
139
+ * alert({ on, id, did, name }) the ring here (the seam above); audio({ on, id, name }) the call's audio mode (the
140
+ * phone app's CallService); changed() after anything the page shows moved
141
+ * o: { ringS, expS, pageMs, keepMs } (tests shorten them)
142
+ */
143
+ export class Line {
144
+ #t = new Map(); // id → [timer]
145
+ constructor({ send, contact, allowed, shares = () => false, me, line, alert = () => {}, audio = () => {}, changed = () => {}, now = () => Date.now(), timers = globalThis, o = {} }) {
146
+ Object.assign(this, { send, contact, allowed, shares, me, line, alert, audio, changed, now, timers });
147
+ this.o = { ringS: RING_S, expS: EXP_S, pageMs: PAGE_MS, keepMs: KEEP_MS, ...o };
148
+ this.calls = new Map();
149
+ this.live = null;
150
+ this.pageAt = -Infinity;
151
+ this.seen = new Set();
152
+ this.gone = new Set(); // ends that came before their ring (signalling out of order)
153
+ this.replied = new Map(); // did → when a busy or unavailable answer last went
154
+ this.dropped = 0;
155
+ }
156
+ /** A busy or unavailable answer, at most one per contact per REPLY_MS. */
157
+ #reply(did, content) {
158
+ const now = this.now(), at = this.replied.get(did);
159
+ if (at !== undefined && now - at < REPLY_MS) return;
160
+ this.replied.set(did, now);
161
+ if (this.replied.size > 256) this.replied.delete(this.replied.keys().next().value);
162
+ void this.send(did, content).catch(() => {});
163
+ }
164
+ #after(call, ms, f) { const t = this.timers.setTimeout(() => { try { f(); } catch {} }, ms); (this.#t.get(call.id) ?? this.#t.set(call.id, []).get(call.id)).push(t); }
165
+ #clear(call) { for (const t of this.#t.get(call.id) ?? []) this.timers.clearTimeout(t); this.#t.delete(call.id); }
166
+ #say(call, content) { return this.send(call.did, PADDED.has(content.typ) ? padded(content) : content); }
167
+ #signal(call, s) {
168
+ // A repeat (the relay delivered it twice, a retry): dropped.
169
+ const key = JSON.stringify(s);
170
+ if ((call.keys ??= new Set()).has(key)) return;
171
+ call.keys.add(key);
172
+ call.signals.push({ n: ++call.n, ...s }); this.changed();
173
+ }
174
+ #mine(id, dir) {
175
+ const c = typeof id === 'string' ? this.calls.get(id) : undefined;
176
+ if (!c || c.state === 'ended' || (dir && c.dir !== dir)) bad('call_unknown', 'no such call going on here', 404);
177
+ return c;
178
+ }
179
+ #seen(id) { this.seen.add(id); if (this.seen.size > 512) this.seen.delete(this.seen.values().next().value); }
180
+ #missed(c, id) { this.line({ did: c.did, dir: 'in', text: 'Missed call', call: { id, state: 'missed', secs: 0 } }); }
181
+ /** The live call, or null. */
182
+ current() { const c = this.live ? this.calls.get(this.live) : null; return c && c.state !== 'ended' ? c : null; }
183
+
184
+ /** GET /api/calls: the live call (or the last, KEEP_MS after its end) as the page draws it; rtc: a page that can take one polled. */
185
+ view({ rtc = false } = {}) {
186
+ const now = this.now();
187
+ if (rtc) this.pageAt = now;
188
+ let c = this.current();
189
+ if (!c) { for (const x of this.calls.values()) if (x.ended !== null && now - x.ended < this.o.keepMs && (!c || x.ended > c.ended)) c = x; }
190
+ for (const [id, x] of this.calls) if (x.ended !== null && now - x.ended >= this.o.keepMs) this.calls.delete(id);
191
+ if (!c) return null;
192
+ const secs = c.connected === null ? 0 : Math.max(0, Math.floor(((c.ended ?? now) - c.connected) / 1000));
193
+ return { id: c.id, did: c.did, name: c.name, dir: c.dir, state: c.state, reason: c.reason, glare: c.glare, attempt: c.attempt, secs,
194
+ ...(c.dir === 'in' && c.offer && { offer: c.offer }), signals: c.signals.map((s) => ({ ...s })) };
195
+ }
196
+
197
+ /** The caller's Call: the ring goes, padded, with its offer. → the view. */
198
+ async start(c, sdp) {
199
+ if (this.current()) bad('call_busy', 'a call is going on already', 409);
200
+ checkSdp(sdp);
201
+ const id = newCallId(), now = this.now();
202
+ const call = { id, did: c.did, name: c.name, dir: 'out', state: 'calling', at: now, answered: null, connected: null, ended: null, reason: null, by: null, glare: false, attempt: 1, n: 0, signals: [], audio: true };
203
+ this.calls.set(id, call); this.live = id; this.#seen(id);
204
+ this.audio({ on: true, id, name: c.name });
205
+ try { await this.#say(call, { typ: 'ring', id, attempt: 1, sdp, exp: Math.floor(now / 1000) + this.o.expS, text: OLD_TEXT }); } catch (e) {
206
+ this.#finish(call, 'unsent', 'me', { quiet: true });
207
+ throw e;
208
+ }
209
+ this.#after(call, this.o.ringS * 1000, () => { if (call.state === 'calling' || call.state === 'ringing') void this.end(id, 'no_answer').catch(() => {}); });
210
+ this.changed();
211
+ return this.view();
212
+ }
213
+ /** Accept (attempt 1) or a restart answered (attempt n): the answer goes. */
214
+ async accept(id, sdp, attempt = 1) {
215
+ const call = this.#mine(id, 'in');
216
+ checkSdp(sdp);
217
+ if (attempt === 1) {
218
+ if (call.state !== 'incoming') bad('call_state', 'that call is not ringing here', 409);
219
+ call.state = 'connecting'; call.answered = this.now();
220
+ this.alert({ on: false, id, did: call.did, name: call.name });
221
+ if (!call.audio) { call.audio = true; this.audio({ on: true, id, name: call.name }); }
222
+ } else if (attempt !== call.attempt || call.state === 'incoming') bad('call_state', `no restart ${attempt} to answer`, 409);
223
+ await this.#say(call, { typ: 'answer', id, attempt, sdp });
224
+ this.changed();
225
+ return this.view();
226
+ }
227
+ async decline(id) {
228
+ const call = this.#mine(id, 'in');
229
+ if (call.state !== 'incoming') bad('call_state', 'that call is not ringing here', 409);
230
+ this.#finish(call, 'declined', 'me');
231
+ await this.#say(call, { typ: 'end', id, reason: 'declined' }).catch(() => {});
232
+ return this.view();
233
+ }
234
+ async cands(id, attempt, list) {
235
+ const call = this.#mine(id);
236
+ if (attempt !== call.attempt) bad('call_state', `attempt ${call.attempt} is the current one`, 409);
237
+ await this.#say(call, { typ: 'cands', id, attempt, cands: checkCands(list) });
238
+ return { sent: list.length };
239
+ }
240
+ async restart(id, attempt, sdp) {
241
+ const call = this.#mine(id, 'out');
242
+ checkSdp(sdp);
243
+ if (call.answered === null || attempt !== call.attempt + 1) bad('call_state', `the next restart is ${call.attempt + 1}`, 409);
244
+ call.attempt = attempt;
245
+ await this.#say(call, { typ: 'restart', id, attempt, sdp });
246
+ this.changed();
247
+ return this.view();
248
+ }
249
+ /** The page's media flows (ICE connected): the call's time starts. */
250
+ connected(id) {
251
+ const call = this.#mine(id);
252
+ if (call.answered === null) bad('call_state', 'not answered yet', 409);
253
+ if (call.connected === null) { call.connected = this.now(); call.state = 'active'; this.changed(); }
254
+ return this.view();
255
+ }
256
+ /** Hang up, cancel, or the page's verdict (no_path, lost): the end goes, then the line. */
257
+ async end(id, reason = 'hangup') {
258
+ const call = this.#mine(id);
259
+ if (!REASONS.includes(reason)) bad('body', 'reason: one of ' + REASONS.join(', '));
260
+ const r = call.dir === 'out' && call.answered === null && reason === 'hangup' ? 'cancelled' : reason;
261
+ if (call.dir === 'in' && call.state === 'incoming' && r === 'hangup') return this.decline(id);
262
+ this.#finish(call, r, 'me');
263
+ await this.#say(call, { typ: 'end', id, reason: r }).catch(() => {});
264
+ return this.view();
265
+ }
266
+ /** The live call ended from outside the page (the phone's notification's Hang up). */
267
+ async hangup() { const c = this.current(); return c ? this.end(c.id, 'hangup') : null; }
268
+
269
+ #finish(call, reason, by, { quiet = false } = {}) {
270
+ if (call.state === 'ended') return;
271
+ this.#clear(call);
272
+ const was = call.state;
273
+ call.state = 'ended'; call.reason = reason; call.by = by; call.ended = this.now();
274
+ if (this.live === call.id) this.live = null;
275
+ if (was === 'incoming') this.alert({ on: false, id: call.id, did: call.did, name: call.name });
276
+ if (call.audio) { call.audio = false; this.audio({ on: false, id: call.id, name: call.name }); }
277
+ if (!quiet) { const l = lineOf(call, call.ended); this.line({ did: call.did, dir: call.dir, text: l.text, call: { id: call.id, state: l.state, secs: l.secs } }); }
278
+ this.changed();
279
+ }
280
+
281
+ /** A sigelo-call/0 message from the carrier ({ from, name, content }): checked, then acted on. */
282
+ receive({ from, content }) {
283
+ let x;
284
+ try { x = checkSignal(content); } catch { this.dropped++; return; }
285
+ const c = this.contact(from);
286
+ if (!c) { this.dropped++; return; }
287
+ if (x.typ === 'ring') return this.#ring(c, x);
288
+ const call = this.calls.get(x.id);
289
+ if (!call && x.typ === 'end' && !this.seen.has(x.id)) { this.gone.add(`${c.did} ${x.id}`); if (this.gone.size > 256) this.gone.delete(this.gone.values().next().value); return; }
290
+ if (!call || call.did !== c.did || call.state === 'ended') return;
291
+ switch (x.typ) {
292
+ case 'ringing': if (call.dir === 'out' && call.state === 'calling') { call.state = 'ringing'; this.changed(); } break;
293
+ case 'answer':
294
+ if (call.dir !== 'out') break;
295
+ if (x.attempt === 1 && (call.state === 'calling' || call.state === 'ringing')) { call.state = 'connecting'; call.answered = this.now(); this.#clear(call); this.#signal(call, { typ: 'answer', attempt: 1, sdp: x.sdp }); }
296
+ else if (x.attempt > 1 && x.attempt === call.attempt) this.#signal(call, { typ: 'answer', attempt: x.attempt, sdp: x.sdp });
297
+ break;
298
+ case 'cands':
299
+ if (x.attempt === call.attempt) this.#signal(call, { typ: 'cands', attempt: x.attempt, cands: x.cands });
300
+ // A restart's candidates that came before the restart itself: kept for it (one batch).
301
+ else if (call.dir === 'in' && x.attempt === call.attempt + 1) call.early = { attempt: x.attempt, cands: x.cands };
302
+ break;
303
+ case 'restart':
304
+ if (call.dir === 'in' && call.answered !== null && x.attempt === call.attempt + 1) {
305
+ call.attempt = x.attempt; this.#signal(call, { typ: 'restart', attempt: x.attempt, sdp: x.sdp });
306
+ if (call.early?.attempt === x.attempt) this.#signal(call, { typ: 'cands', attempt: x.attempt, cands: call.early.cands });
307
+ call.early = null;
308
+ }
309
+ break;
310
+ case 'end': this.#finish(call, x.reason, 'them'); break;
311
+ }
312
+ }
313
+ #ring(c, x) {
314
+ if (this.seen.has(x.id)) return; // a repeat of one already taken
315
+ this.#seen(x.id);
316
+ const now = this.now(), nowS = Math.floor(now / 1000);
317
+ // Not allowed to ring here (a quiet contact, the switch off) or past its life: a line, nothing said back.
318
+ if (!this.allowed(c) || x.exp <= nowS || this.gone.has(`${c.did} ${x.id}`)) return this.#missed(c, x.id);
319
+ let glare = false;
320
+ const live = this.current();
321
+ if (live) {
322
+ if (live.did === c.did && live.dir === 'out' && (live.state === 'calling' || live.state === 'ringing')) {
323
+ // Glare: the smaller original DID's call stands. Mine stands: theirs is dropped here (mine is taken there).
324
+ if (this.me() < c.did) return;
325
+ // Theirs stands: mine goes without a word (it is dropped there) and theirs is taken at once.
326
+ this.#finish(live, 'glare', 'me', { quiet: true });
327
+ glare = true;
328
+ } else {
329
+ // "Busy" says this side is online, in a call: only to a contact that may see it (as "Ringing…"); else it rings out.
330
+ if (this.shares(c)) this.#reply(c.did, { typ: 'end', id: x.id, reason: 'busy' });
331
+ return this.#missed(c, x.id);
332
+ }
333
+ }
334
+ const exp = Math.min(x.exp, nowS + this.o.expS);
335
+ const call = { id: x.id, did: c.did, name: c.name, dir: 'in', state: 'incoming', at: now, answered: null, connected: null, ended: null, reason: null, by: null, glare, attempt: 1, n: 0, signals: [], offer: x.sdp, exp, audio: false };
336
+ this.calls.set(x.id, call); this.live = x.id;
337
+ // "Ringing…" says this side is online: only to a contact that may see it (decision 2026-11-17).
338
+ if (this.shares(c)) void this.send(c.did, { typ: 'ringing', id: x.id }).catch(() => {});
339
+ if (!glare) this.alert({ on: true, id: x.id, did: c.did, name: c.name });
340
+ this.#after(call, Math.max(0, exp * 1000 - now), () => { if (call.state === 'incoming') this.#finish(call, 'no_answer', 'them'); });
341
+ // No page here that can take a call (none polled with rtc lately): unavailable, once the page had its chance.
342
+ const check = () => {
343
+ if (call.state !== 'incoming') return;
344
+ if (this.now() - this.pageAt <= this.o.pageMs) return;
345
+ this.#finish(call, 'unavailable', 'me');
346
+ // Its quick answer says this side's carrier runs: only to a contact shown this side's presence; else it rings out.
347
+ if (this.shares(c)) this.#reply(c.did, { typ: 'end', id: x.id, reason: 'unavailable' });
348
+ };
349
+ if (now - this.pageAt > this.o.pageMs) this.#after(call, this.o.pageMs, check);
350
+ this.changed();
351
+ }
352
+ close() { for (const c of this.calls.values()) this.#clear(c); }
353
+ }
354
+
355
+ /**
356
+ * The /api/calls* routes over one Line (UI-API.md "Calls"). contactOf(did) → the contact (refuses an unknown one);
357
+ * callable(c) → whether this side may call it now (a person, present); stun(c) → the STUN list; can: { speaker, mic, ring }
358
+ * (ring: the host rings itself, the page plays no tone);
359
+ * hooks: { speaker(on), mic(), micSettings() } where the host has them (the phone app); allow(c, on) / allowOf(c) the
360
+ * "Can call me" switch.
361
+ */
362
+ export function callRoutes({ line, contactOf, callable, stun, can = {}, hooks = {}, allow, allowOf }) {
363
+ const idOf = (b) => (typeof b['id'] === 'string' && ID.test(b['id']) ? b['id'] : bad('body', 'id: a call id (32 hex digits)'));
364
+ const attemptOf = (b, d) => (b['attempt'] === undefined ? d : isInt(b['attempt']) && b['attempt'] >= 1 && b['attempt'] <= ATTEMPT_MAX ? b['attempt'] : bad('body', 'attempt: a whole number'));
365
+ return {
366
+ 'GET /api/calls': (_, q) => {
367
+ const to = q?.get?.('to'), c = to ? contactOf(to) : null, call = line.view({ rtc: q?.get?.('rtc') === '1' });
368
+ const peer = c ?? (call ? contactOf(call.did) : null);
369
+ return { call, stun: stun(peer), can: { speaker: can.speaker === true, mic: can.mic === true, ring: can.ring === true } };
370
+ },
371
+ 'POST /api/calls/start': async (b) => {
372
+ const c = contactOf(b['to']);
373
+ const why = callable(c);
374
+ if (why !== true) bad(why.check, why.message, 409);
375
+ return { call: await line.start(c, b['sdp']) };
376
+ },
377
+ 'POST /api/calls/accept': async (b) => ({ call: await line.accept(idOf(b), b['sdp'], attemptOf(b, 1)) }),
378
+ 'POST /api/calls/decline': async (b) => ({ call: await line.decline(idOf(b)) }),
379
+ 'POST /api/calls/cands': async (b) => line.cands(idOf(b), attemptOf(b, 0), b['cands']),
380
+ 'POST /api/calls/restart': async (b) => ({ call: await line.restart(idOf(b), attemptOf(b, 0), b['sdp']) }),
381
+ 'POST /api/calls/connected': (b) => ({ call: line.connected(idOf(b)) }),
382
+ 'POST /api/calls/end': async (b) => ({ call: await line.end(idOf(b), b['reason'] ?? 'hangup') }),
383
+ ...(typeof hooks.speaker === 'function' && { 'POST /api/calls/speaker': async (b) => { if (typeof b['on'] !== 'boolean') bad('body', 'on: true or false'); await hooks.speaker(b['on']); return { speaker: b['on'] }; } }),
384
+ ...(typeof hooks.mic === 'function' && { 'POST /api/calls/mic': async () => ({ granted: await hooks.mic() }) }),
385
+ ...(typeof hooks.micSettings === 'function' && { 'POST /api/calls/mic-settings': async () => { await hooks.micSettings(); return { opened: true }; } }),
386
+ 'POST /api/calls/allow': (b) => {
387
+ const c = contactOf(b['contact']), on = b['on'];
388
+ if (on !== true && on !== false && on !== null) bad('body', 'on: true, false, or null (the default again)');
389
+ allow(c, on);
390
+ return { did: c.did, can_call: allowOf(c), set: on !== null };
391
+ },
392
+ };
393
+ }
394
+
395
+ // ================================================================ the page's half
396
+ /**
397
+ * Opus for weak links (design §3, 2026-11-24), asked of the far end's encoder through the SDP it is given: mono,
398
+ * DTX (no packets in silence), in-band FEC, at most MAX_BPS, 20 ms frames (a=ptime:20). Applied to every remote description.
399
+ */
400
+ export function opusTune(sdp) {
401
+ const pt = /^a=rtpmap:(\d+) opus\/48000/im.exec(sdp)?.[1];
402
+ if (!pt) return sdp;
403
+ if (!/^a=ptime:/m.test(sdp)) sdp = sdp.replace(new RegExp(`^(a=rtpmap:${pt} opus/48000[^\r\n]*)`, 'im'), '$1\r\na=ptime:20');
404
+ const want = { useinbandfec: '1', usedtx: '1', stereo: '0', 'sprop-stereo': '0', maxaveragebitrate: String(MAX_BPS) };
405
+ const lines = sdp.split(/\r\n|\n/);
406
+ const at = lines.findIndex((l) => l.startsWith(`a=fmtp:${pt} `));
407
+ if (at < 0) { const r = lines.findIndex((l) => l.toLowerCase().startsWith(`a=rtpmap:${pt} opus`)); lines.splice(r + 1, 0, `a=fmtp:${pt} ` + Object.entries(want).map(([k, v]) => `${k}=${v}`).join(';')); return lines.join('\r\n'); }
408
+ const kv = new Map(lines[at].slice(`a=fmtp:${pt} `.length).split(';').map((x) => x.trim()).filter(Boolean).map((x) => { const i = x.indexOf('='); return i < 0 ? [x, ''] : [x.slice(0, i), x.slice(i + 1)]; }));
409
+ for (const [k, v] of Object.entries(want)) kv.set(k, v);
410
+ lines[at] = `a=fmtp:${pt} ` + [...kv].map(([k, v]) => (v === '' ? k : `${k}=${v}`)).join(';');
411
+ return lines.join('\r\n');
412
+ }
413
+ /** The screen's bars from loss (0 to 1) and round trip (s): 3 good, 2 fair, 1 poor; null not known yet. */
414
+ export function barsOf(loss, rtt) {
415
+ if (loss === null && rtt === null) return null;
416
+ const l = loss ?? 0, r = rtt ?? 0;
417
+ return l < 0.03 && r < 0.3 ? 3 : l < 0.1 && r < 0.6 ? 2 : 1;
418
+ }
419
+ /** The next bitrate: down a step under loss (≥ 10 %) or a long round trip (≥ 0.5 s), up a step after two clean reads. */
420
+ export function nextBps(bps, loss, rtt, clean) {
421
+ if ((loss ?? 0) >= 0.1 || (rtt ?? 0) >= 0.5) return { bps: Math.max(MIN_BPS, bps - STEP_BPS), clean: 0 };
422
+ if ((loss ?? 0) < 0.02 && (rtt ?? 0) < 0.3) { const c = clean + 1; return c >= 2 ? { bps: Math.min(MAX_BPS, bps + STEP_BPS), clean: 0 } : { bps, clean: c }; }
423
+ return { bps, clean: 0 };
424
+ }
425
+ export const AUDIO = Object.freeze({ echoCancellation: true, noiseSuppression: true, autoGainControl: true, channelCount: 1 });
426
+
427
+ /**
428
+ * new Phone({ api, RTC, media, onState, onStream, timers, now, o })
429
+ * api(method, path, body?) → the route's JSON, or throws { check, message, status }
430
+ * RTC: the RTCPeerConnection constructor (generateCertificate on it when the browser has it: a fresh key per call)
431
+ * media() → a MediaStream with one audio track (getUserMedia({audio: AUDIO})); refused: mic_permission, no_mic
432
+ * onState(view) at every change (the call screen); onStream(stream | null) the far end's audio
433
+ * o: { gatherMs, lateMs, iceMs, disconnectedMs, lostMs, pollMs }
434
+ * phone.tick() reads GET /api/calls?rtc=1 and acts on it (the page's poll calls it; while a call is live it polls itself).
435
+ * phone.place(did), accept(), decline(), hangup(), mute(on), speaker(on); phone.view() → what the screen shows.
436
+ */
437
+ export class Phone {
438
+ constructor({ api, RTC = globalThis.RTCPeerConnection, media, onState = () => {}, onStream = () => {}, timers = globalThis, now = () => Date.now(), o = {} }) {
439
+ Object.assign(this, { api, RTC, media, onState, onStream, timers, now });
440
+ this.o = { gatherMs: GATHER_MS, lateMs: LATE_MS, iceMs: ICE_MS, disconnectedMs: DISCONNECTED_MS, retryMs: RETRY_MS, lostMs: LOST_MS, statsMs: STATS_MS, pollMs: 500, ...o };
441
+ this.call = null; // the Line's view
442
+ this.stun = [];
443
+ this.can = { speaker: false, mic: false };
444
+ this.#reset();
445
+ }
446
+ #reset() {
447
+ this.pc = null; this.stream = null; this.id = null; this.attempt = 1; this.applied = 0; this.pending = []; this.remote = false;
448
+ this.ever = false; this.muted = false; this.speakerOn = false; this.phase = null; this.error = null; this.place_ = null;
449
+ this.reconnecting = false; this.quality = null; this.bps = MAX_BPS; this.clean = 0; this.prevIn = null; this.loss = null; this.rtt = null;
450
+ for (const k of ['ice', 'disc', 'retry', 'lost', 'stats', 'poll']) this.#stop(k);
451
+ }
452
+ #tm = {};
453
+ #q = Promise.resolve();
454
+ #stop(k) { if (this.#tm[k] !== undefined) { this.timers.clearTimeout(this.#tm[k]); delete this.#tm[k]; } }
455
+ #start(k, ms, f) { this.#stop(k); this.#tm[k] = this.timers.setTimeout(() => { delete this.#tm[k]; void f(); }, ms); }
456
+ static available(env = globalThis) { return typeof env.RTCPeerConnection === 'function' && typeof env.navigator?.mediaDevices?.getUserMedia === 'function'; }
457
+
458
+ /** What the screen shows: the Line's view and this page's own (the phase, an error, mute and speaker). */
459
+ view() {
460
+ const c = this.call;
461
+ return { call: c, phase: this.phase, error: this.error, muted: this.muted, speaker: this.speakerOn, can: this.can, reconnecting: this.reconnecting,
462
+ quality: this.reconnecting ? 0 : this.quality, bps: this.bps, loss: this.loss, rtt: this.rtt, live: Boolean(c && c.state !== 'ended') || this.phase === 'mic' || this.phase === 'placing' };
463
+ }
464
+ #changed() { try { this.onState(this.view()); } catch {} }
465
+
466
+ async tick(extra = '') {
467
+ let r;
468
+ try { r = await this.api('GET', `/api/calls?rtc=1${extra}`); } catch (e) { return null; }
469
+ this.stun = Array.isArray(r.stun) ? r.stun : [];
470
+ this.can = r.can ?? this.can;
471
+ // One view acted on at a time, in order: a signal is applied once (a second setRemoteDescription would throw).
472
+ const run = this.#q.then(() => this.#sync(r.call ?? null));
473
+ this.#q = run.catch(() => {});
474
+ await run;
475
+ return r;
476
+ }
477
+ #loop() {
478
+ if (this.#tm.poll !== undefined) return;
479
+ const go = async () => { await this.tick(); if (this.view().live) this.#start('poll', this.o.pollMs, go); };
480
+ this.#start('poll', this.o.pollMs, go);
481
+ }
482
+
483
+ async #pc() {
484
+ let certificates;
485
+ try { if (typeof this.RTC.generateCertificate === 'function') certificates = [await this.RTC.generateCertificate({ name: 'ECDSA', namedCurve: 'P-256' })]; } catch {}
486
+ const pc = new this.RTC({ iceServers: this.stun.length ? [{ urls: this.stun.map((s) => `stun:${s}`) }] : [], bundlePolicy: 'max-bundle', rtcpMuxPolicy: 'require', ...(certificates && { certificates }) });
487
+ for (const t of this.stream.getAudioTracks()) pc.addTrack(t, this.stream);
488
+ this.prevIn = null;
489
+ pc.addEventListener('track', (ev) => { try { this.onStream(ev.streams?.[0] ?? null); } catch {} });
490
+ pc.addEventListener('iceconnectionstatechange', () => void this.#ice(pc));
491
+ return pc;
492
+ }
493
+ async #mic() {
494
+ this.phase = 'mic'; this.#changed();
495
+ if (this.can.mic) await this.api('POST', '/api/calls/mic');
496
+ this.stream = await this.media();
497
+ }
498
+ async #gathered(pc, ms) {
499
+ if (pc.iceGatheringState !== 'complete') {
500
+ await new Promise((r) => {
501
+ const t = this.timers.setTimeout(r, ms);
502
+ pc.addEventListener('icegatheringstatechange', () => { if (pc.iceGatheringState === 'complete') { this.timers.clearTimeout(t); r(); } });
503
+ });
504
+ }
505
+ return pc.localDescription.sdp;
506
+ }
507
+ /** The candidates found after the SDP left, once (gathering done, or lateMs). */
508
+ async #late(pc, attempt, sent) {
509
+ await this.#gathered(pc, this.o.lateMs);
510
+ if (this.pc !== pc || this.attempt !== attempt || !this.id) return;
511
+ const had = new Set(candsIn(sent)), more = candsIn(pc.localDescription?.sdp ?? '').filter((c) => !had.has(c)).slice(0, CANDS_MAX);
512
+ if (more.length) await this.api('POST', '/api/calls/cands', { id: this.id, attempt, cands: more }).catch(() => {});
513
+ }
514
+ async #remote(pc, type, sdp) {
515
+ await pc.setRemoteDescription({ type, sdp: opusTune(noMdns(sdp)) });
516
+ this.remote = true;
517
+ for (const c of this.pending.splice(0)) await this.#add(pc, c);
518
+ }
519
+ async #add(pc, c) {
520
+ if (/ [0-9a-f-]+\.local /i.test(c)) return;
521
+ if (!this.remote) { this.pending.push(c); return; }
522
+ try { await pc.addIceCandidate({ candidate: c, sdpMLineIndex: 0 }); } catch {}
523
+ }
524
+ #fail(e) { this.error = { check: e?.check ?? 'call', message: String(e?.message ?? e) }; }
525
+
526
+ /** Call: the microphone, a fresh connection, the offer after GATHER_MS, the ring. */
527
+ async place(did) {
528
+ if (this.view().live) throw Object.assign(new Error('a call is going on already'), { check: 'call_busy' });
529
+ this.#reset();
530
+ this.place_ = did; this.call = null;
531
+ try {
532
+ await this.tick(`&to=${encodeURIComponent(did)}`);
533
+ await this.#mic();
534
+ this.phase = 'placing'; this.#changed();
535
+ const pc = this.pc = await this.#pc();
536
+ await pc.setLocalDescription(await pc.createOffer());
537
+ const sdp = await this.#gathered(pc, this.o.gatherMs);
538
+ const r = await this.api('POST', '/api/calls/start', { to: did, sdp });
539
+ this.id = r.call.id; this.call = r.call; this.phase = null;
540
+ void this.#late(pc, 1, sdp);
541
+ this.#changed(); this.#loop();
542
+ return r.call;
543
+ } catch (e) {
544
+ this.#fail(e); this.#close(); this.phase = 'failed'; this.#changed();
545
+ throw e;
546
+ }
547
+ }
548
+ /** Accept the ringing call: the microphone, a connection, the answer. Nothing is gathered before this. */
549
+ async accept() {
550
+ const c = this.call;
551
+ if (!c || c.dir !== 'in' || c.state !== 'incoming' || this.pc) return;
552
+ // A fresh call here: nothing of the last one carried over (its connection's flags, bitrate, timers).
553
+ const applied = this.applied;
554
+ this.#reset();
555
+ this.call = c; this.id = c.id; this.applied = applied;
556
+ try {
557
+ await this.#mic();
558
+ const pc = this.pc = await this.#pc();
559
+ await this.#remote(pc, 'offer', c.offer);
560
+ await pc.setLocalDescription(await pc.createAnswer());
561
+ const sdp = await this.#gathered(pc, this.o.gatherMs);
562
+ const r = await this.api('POST', '/api/calls/accept', { id: c.id, sdp });
563
+ this.call = r.call; this.phase = null;
564
+ this.#start('ice', this.o.iceMs, () => this.#noPath());
565
+ void this.#late(pc, 1, sdp);
566
+ this.#changed(); this.#loop();
567
+ } catch (e) {
568
+ this.#fail(e); this.phase = 'failed';
569
+ await this.api('POST', '/api/calls/end', { id: c.id, reason: 'hangup' }).catch(() => {});
570
+ this.#close(); this.#changed();
571
+ }
572
+ }
573
+ async decline() { const c = this.call; if (c?.dir === 'in' && c.state === 'incoming') { const r = await this.api('POST', '/api/calls/decline', { id: c.id }).catch(() => null); if (r) this.call = r.call; this.#close(); this.#changed(); } }
574
+ async hangup(reason = 'hangup') {
575
+ const id = this.id ?? this.call?.id;
576
+ if (!id) { this.#close(); this.phase = null; this.#changed(); return; }
577
+ const r = await this.api('POST', '/api/calls/end', { id, reason }).catch(() => null);
578
+ if (r?.call) this.call = r.call;
579
+ this.#close(); this.#changed();
580
+ }
581
+ mute(on) { this.muted = on === true; for (const t of this.stream?.getAudioTracks() ?? []) t.enabled = !this.muted; this.#changed(); }
582
+ async speaker(on) { if (!this.can.speaker) return; await this.api('POST', '/api/calls/speaker', { on: on === true }); this.speakerOn = on === true; this.#changed(); }
583
+ /** The page leaves the call screen for good (Close on the ended state). */
584
+ dismiss() { if (!this.view().live) { this.call = null; this.phase = null; this.error = null; this.#changed(); } }
585
+
586
+ async #noPath() { if (!this.ever && this.id) { this.error = { check: 'no_path', message: NO_PATH }; await this.hangup('no_path'); } }
587
+ async #ice(pc) {
588
+ if (this.pc !== pc) return;
589
+ const s = pc.iceConnectionState;
590
+ if (s === 'connected' || s === 'completed') {
591
+ for (const k of ['ice', 'disc', 'retry', 'lost']) this.#stop(k);
592
+ if (this.reconnecting) { this.reconnecting = false; this.#changed(); }
593
+ if (!this.ever) {
594
+ this.ever = true;
595
+ await this.#bitrate(pc);
596
+ this.#start('stats', this.o.statsMs, () => this.#stats(pc));
597
+ const r = await this.api('POST', '/api/calls/connected', { id: this.id }).catch(() => null);
598
+ if (r?.call) this.call = r.call;
599
+ this.#changed();
600
+ }
601
+ } else if (s === 'disconnected' || s === 'failed') {
602
+ if (!this.ever) { if (s === 'failed') await this.#noPath(); return; }
603
+ this.#drop(s === 'failed' ? 0 : this.o.disconnectedMs);
604
+ }
605
+ }
606
+ /** The path dropped (or the network changed): "Reconnecting…"; the caller restarts ICE after ms (one side only: no restart
607
+ * glare), again every RETRY_MS while it does not connect; either side gives up LOST_MS after the drop ("Connection lost"). */
608
+ #drop(ms) {
609
+ if (!this.reconnecting) { this.reconnecting = true; this.#changed(); }
610
+ if (this.call?.dir === 'out' && this.#tm.disc === undefined) this.#start('disc', ms, () => this.#restart());
611
+ if (this.#tm.lost === undefined) this.#start('lost', this.o.lostMs, () => this.hangup('lost'));
612
+ }
613
+ /** The shell saw the network change (Android's default network: Wi-Fi to mobile data, a new address): the caller
614
+ * restarts at once, before ICE notices; the callee waits for the caller's restart. */
615
+ networkChanged() {
616
+ if (!this.ever || !this.pc || this.call?.state !== 'active') return;
617
+ if (this.call.dir === 'out') { this.#stop('disc'); this.#drop(0); }
618
+ }
619
+ async #restart() {
620
+ const pc = this.pc;
621
+ if (!pc || !this.id || !this.reconnecting) return;
622
+ const attempt = this.attempt + 1;
623
+ // Not connected again within RETRY_MS: another restart (a later network may be up by then).
624
+ this.#start('retry', this.o.retryMs, () => { if (this.reconnecting && this.pc === pc) { this.#stop('disc'); this.#start('disc', 0, () => this.#restart()); } });
625
+ try {
626
+ await pc.setLocalDescription(await pc.createOffer({ iceRestart: true }));
627
+ this.remote = false;
628
+ const sdp = await this.#gathered(pc, this.o.gatherMs);
629
+ if (this.pc !== pc) return;
630
+ const r = await this.api('POST', '/api/calls/restart', { id: this.id, attempt, sdp });
631
+ this.attempt = attempt; this.call = r.call;
632
+ void this.#late(pc, attempt, sdp);
633
+ } catch {}
634
+ }
635
+ /** The far end's RTCP every STATS_MS: loss and round trip → the bars, and this side's bitrate stepped (MIN_BPS to MAX_BPS). */
636
+ async #stats(pc) {
637
+ if (this.pc !== pc) return;
638
+ try {
639
+ const r = await pc.getStats();
640
+ let loss = null, rtt = null, inLost = null, inRecv = null;
641
+ r.forEach((x) => {
642
+ if (x.type === 'remote-inbound-rtp' && (x.kind ?? 'audio') === 'audio') {
643
+ if (typeof x.fractionLost === 'number') loss = Math.max(loss ?? 0, x.fractionLost);
644
+ if (typeof x.roundTripTime === 'number') rtt = x.roundTripTime;
645
+ } else if (x.type === 'inbound-rtp' && (x.kind ?? 'audio') === 'audio') { inLost = x.packetsLost ?? 0; inRecv = x.packetsReceived ?? 0; }
646
+ else if (x.type === 'candidate-pair' && x.nominated && typeof x.currentRoundTripTime === 'number' && rtt === null) rtt = x.currentRoundTripTime;
647
+ });
648
+ // What reaches this side: the loss since the last read.
649
+ const p = this.prevIn;
650
+ if (inLost !== null) {
651
+ this.prevIn = { lost: inLost, recv: inRecv };
652
+ if (p) { const dl = Math.max(0, inLost - p.lost), dr = Math.max(0, inRecv - p.recv); if (dl + dr > 0) loss = Math.max(loss ?? 0, dl / (dl + dr)); }
653
+ }
654
+ this.loss = loss; this.rtt = rtt;
655
+ if (!this.reconnecting) this.quality = barsOf(loss, rtt);
656
+ const n = nextBps(this.bps, loss, rtt, this.clean);
657
+ this.clean = n.clean;
658
+ if (n.bps !== this.bps) { this.bps = n.bps; await this.#bitrate(pc); }
659
+ this.#changed();
660
+ } catch {}
661
+ if (this.pc === pc) this.#start('stats', this.o.statsMs, () => this.#stats(pc));
662
+ }
663
+ async #bitrate(pc) {
664
+ for (const snd of pc.getSenders?.() ?? []) {
665
+ if (snd.track && snd.track.kind !== 'audio') continue;
666
+ try {
667
+ const p = snd.getParameters();
668
+ if (!p.encodings || p.encodings.length === 0) p.encodings = [{}];
669
+ p.encodings[0].maxBitrate = this.bps;
670
+ await snd.setParameters(p);
671
+ } catch {}
672
+ }
673
+ }
674
+ async #sync(call) {
675
+ const was = this.call;
676
+ if (call === null) {
677
+ // Gone from the host (KEEP_MS after its end, or the page started before it): nothing live here either.
678
+ if (was && was.state !== 'ended' && !this.place_) { this.#close(); this.call = null; this.#changed(); }
679
+ else if (this.call && this.call.state === 'ended' && !this.pc) { /* kept on the screen until dismissed */ }
680
+ return;
681
+ }
682
+ if (this.place_ && call.dir === 'out' && this.id === null) return; // placing: its own answer says the id
683
+ if (this.id && call.id !== this.id) {
684
+ // Ours ended, another one came (a glare's ring, a new call): this page's connection goes.
685
+ if (this.pc) this.#close();
686
+ }
687
+ const fresh = !was || was.id !== call.id;
688
+ this.call = call;
689
+ if (fresh) { this.applied = 0; if (call.dir === 'in') { this.id = null; this.attempt = 1; } }
690
+ if (call.state === 'ended') { if (this.pc || this.stream) this.#close(); this.#changed(); return; }
691
+ // Glare: theirs stands and this side wanted the call too: taken at once.
692
+ if (call.dir === 'in' && call.state === 'incoming' && call.glare && !this.pc) { this.#changed(); return this.accept(); }
693
+ const pc = this.pc;
694
+ for (const s of call.signals) {
695
+ if (!pc || this.pc !== pc) break;
696
+ if (s.n <= this.applied) continue;
697
+ this.applied = s.n;
698
+ try {
699
+ if (s.typ === 'answer' && call.dir === 'out' && s.attempt === this.attempt) {
700
+ await this.#remote(pc, 'answer', s.sdp);
701
+ if (s.attempt === 1) this.#start('ice', this.o.iceMs, () => this.#noPath());
702
+ // A restart whose path never dropped (the shell's network event came first): ICE stays connected, no event comes.
703
+ else if (['connected', 'completed'].includes(pc.iceConnectionState)) void this.#ice(pc);
704
+ } else if (s.typ === 'cands' && s.attempt === this.attempt) {
705
+ for (const c of s.cands) await this.#add(pc, c);
706
+ } else if (s.typ === 'restart' && call.dir === 'in') {
707
+ this.attempt = s.attempt; this.remote = false;
708
+ await this.#remote(pc, 'offer', s.sdp);
709
+ await pc.setLocalDescription(await pc.createAnswer());
710
+ const sdp = await this.#gathered(pc, this.o.gatherMs);
711
+ await this.api('POST', '/api/calls/accept', { id: this.id, attempt: s.attempt, sdp });
712
+ void this.#late(pc, s.attempt, sdp);
713
+ }
714
+ } catch (e) { this.#fail(e); }
715
+ }
716
+ this.#changed();
717
+ if (call.state !== 'ended') this.#loop();
718
+ }
719
+ #close() {
720
+ for (const k of ['ice', 'disc', 'retry', 'lost', 'stats']) this.#stop(k);
721
+ this.reconnecting = false;
722
+ try { this.pc?.close(); } catch {}
723
+ for (const t of this.stream?.getTracks?.() ?? []) { try { t.stop(); } catch {} }
724
+ this.pc = null; this.stream = null; this.place_ = null; this.remote = false; this.pending = [];
725
+ try { this.onStream(null); } catch {}
726
+ }
727
+ }