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