@yaks/rtc 0.0.0-stage → 0.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +117 -2
- package/_dist/door.d.ts +74 -0
- package/_dist/door.d.ts.map +1 -0
- package/_dist/effects.d.ts +8 -0
- package/_dist/effects.d.ts.map +1 -0
- package/_dist/join.d.ts +66 -0
- package/_dist/join.d.ts.map +1 -0
- package/_dist/loop.d.ts +11 -0
- package/_dist/loop.d.ts.map +1 -0
- package/_dist/mod.d.ts +30 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/vocab.d.ts +6 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/deno.json +1 -0
- package/door.js +349 -0
- package/door.js.map +1 -0
- package/door.ts +417 -0
- package/effects.js +23 -0
- package/effects.js.map +1 -0
- package/effects.ts +27 -0
- package/join.js +515 -0
- package/join.js.map +1 -0
- package/join.ts +564 -0
- package/loop.js +64 -0
- package/loop.js.map +1 -0
- package/loop.ts +73 -0
- package/mod.js +30 -0
- package/mod.js.map +1 -0
- package/mod.ts +45 -0
- package/package.json +30 -4
- package/vocab.js +16 -0
- package/vocab.js.map +1 -0
- package/vocab.json +68 -0
- package/vocab.ts +17 -0
package/join.ts
ADDED
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
// The page half: one RTCPeerConnection to Cloudflare Realtime, reached
|
|
2
|
+
// through the app's door (./door.ts), and the `rtc` component the page wears
|
|
3
|
+
// while it speaks.
|
|
4
|
+
//
|
|
5
|
+
// A call is one Realtime session. `publish` sends a track from it and names
|
|
6
|
+
// the track in `rtc`, which the relay carries to everyone watching the entity
|
|
7
|
+
// (@yaks/sync); `hear` asks for another session's track and hands back its
|
|
8
|
+
// stream. Nobody holds a room: a page hears the voices it asks for, and a
|
|
9
|
+
// voice goes quiet for everyone when the tab that wore it closes, since the
|
|
10
|
+
// relay clears `rtc` with the connection.
|
|
11
|
+
//
|
|
12
|
+
// The call keeps itself up. It renews its lease through the door about every
|
|
13
|
+
// half minute and re-writes `rtc` with it, so a listener that missed it hears
|
|
14
|
+
// it again. A connection that fails, or a lease the door no longer holds, is a
|
|
15
|
+
// new session: the call opens one, publishes again and says `lost` for the
|
|
16
|
+
// voices it heard, which the page asks for again. A voice going quiet never
|
|
17
|
+
// stops the page.
|
|
18
|
+
//
|
|
19
|
+
// A call opens with its voice already in place: the first section of the
|
|
20
|
+
// connection is a sender named `voice`, silent until a microphone is
|
|
21
|
+
// published into it, and never closed while the call lasts. The first section
|
|
22
|
+
// is the BUNDLE tag, which carries the connection's one transport; closing it
|
|
23
|
+
// makes Chrome start a new transport, which Realtime takes for a disconnected
|
|
24
|
+
// session. So turning the microphone off and on again swaps the sender's track
|
|
25
|
+
// and asks Realtime nothing, and every other section, a voice heard or another
|
|
26
|
+
// track sent, can come and go.
|
|
27
|
+
//
|
|
28
|
+
// Chrome plays a remote track that feeds only Web Audio as silence: the
|
|
29
|
+
// stream must also play through a media element, muted if the page plays it
|
|
30
|
+
// some other way. So every stream `hear` hands back is already playing
|
|
31
|
+
// through a muted <audio>.
|
|
32
|
+
|
|
33
|
+
import type { Bundle } from 'jsr:@yaks/graph@0.2.36'
|
|
34
|
+
import { KEY } from './door.js'
|
|
35
|
+
|
|
36
|
+
/** How a call stands. `limit` is the space's allowance used up: the lease
|
|
37
|
+
* runs out and the voices go quiet until it lifts. `refused` is a caller the
|
|
38
|
+
* app does not let speak. */
|
|
39
|
+
export type State = 'joining' | 'live' | 'limit' | 'refused' | 'lost' | 'left'
|
|
40
|
+
|
|
41
|
+
export type Opts = {
|
|
42
|
+
/** the entity the page speaks as, which wears `rtc` */
|
|
43
|
+
entity: string
|
|
44
|
+
/** how the page writes a bundle into its graph */
|
|
45
|
+
write: (bundles: Bundle[]) => unknown
|
|
46
|
+
/** the app's Realtime door: `./api/rtc/` beside the page unless named */
|
|
47
|
+
door?: string | URL
|
|
48
|
+
/** told whenever the call's state moves */
|
|
49
|
+
change?: (state: State) => void
|
|
50
|
+
fetch?: typeof fetch
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A snapshot of the actual microphone sender, not a promise that a listener
|
|
54
|
+
* hears it. A null statistic means this browser does not expose that field. */
|
|
55
|
+
export type MicSignal = {
|
|
56
|
+
ready: boolean
|
|
57
|
+
enabled: boolean
|
|
58
|
+
connected: boolean
|
|
59
|
+
level: number | null
|
|
60
|
+
energy: number | null
|
|
61
|
+
duration: number | null
|
|
62
|
+
packets: number | null
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A track the call publishes. */
|
|
66
|
+
export type Published = { name: string; stop: () => Promise<void> }
|
|
67
|
+
|
|
68
|
+
/** A track the call hears: its stream, while `live`. */
|
|
69
|
+
export type Heard = {
|
|
70
|
+
stream: MediaStream
|
|
71
|
+
readonly live: boolean
|
|
72
|
+
stop: () => Promise<void>
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export type Call = {
|
|
76
|
+
readonly session: string
|
|
77
|
+
readonly state: State
|
|
78
|
+
publish: (track: MediaStreamTrack, name?: string) => Promise<Published>
|
|
79
|
+
mute: (muted: boolean) => void
|
|
80
|
+
/** Inspect the published sender, for local input and transport guidance. */
|
|
81
|
+
diagnose: (name?: string) => Promise<MicSignal | null>
|
|
82
|
+
hear: (session: string, track: string) => Promise<Heard | null>
|
|
83
|
+
leave: () => Promise<void>
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A door's refusal, with its code: `limit`, `not_found`, `not_yours`. */
|
|
87
|
+
export class Refused extends Error {
|
|
88
|
+
code: string
|
|
89
|
+
status: number
|
|
90
|
+
constructor(code: string, message: string, status = 0) {
|
|
91
|
+
super(message)
|
|
92
|
+
this.name = 'Refused'
|
|
93
|
+
this.code = code
|
|
94
|
+
this.status = status
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** What Opus is capped at, in bits a second: a voice, not a song. */
|
|
99
|
+
export let BITRATE = 32_000
|
|
100
|
+
|
|
101
|
+
/** The track a call opens with, silent until a microphone is published into
|
|
102
|
+
* it: the name `publish` takes unless told another. */
|
|
103
|
+
export let VOICE = 'voice'
|
|
104
|
+
|
|
105
|
+
/** How often the lease is renewed, in milliseconds: twice a lease. */
|
|
106
|
+
export let RENEW = 30_000
|
|
107
|
+
|
|
108
|
+
/** A microphone as a voice wants it. */
|
|
109
|
+
export let microphone = async (): Promise<MediaStreamTrack> => {
|
|
110
|
+
let stream = await navigator.mediaDevices.getUserMedia({
|
|
111
|
+
audio: {
|
|
112
|
+
echoCancellation: true,
|
|
113
|
+
noiseSuppression: true,
|
|
114
|
+
autoGainControl: true,
|
|
115
|
+
},
|
|
116
|
+
})
|
|
117
|
+
let track = stream.getAudioTracks()[0]
|
|
118
|
+
if (!track) {
|
|
119
|
+
stream.getTracks().forEach((t) => t.stop())
|
|
120
|
+
throw new DOMException('No audio input was returned', 'NotFoundError')
|
|
121
|
+
}
|
|
122
|
+
return track
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Whether a microphone is hearing a voice, from its level (0 to 1) and
|
|
127
|
+
* whether it was a moment ago: it starts above one line and stops below a
|
|
128
|
+
* lower one, so a voice between the two does not flicker.
|
|
129
|
+
*
|
|
130
|
+
* ```ts
|
|
131
|
+
* import { assertEquals } from '@std/assert'
|
|
132
|
+
* import { voiced } from './join.ts'
|
|
133
|
+
*
|
|
134
|
+
* assertEquals(voiced(0.2, false), true)
|
|
135
|
+
* assertEquals(voiced(0.03, false), false)
|
|
136
|
+
* assertEquals(voiced(0.03, true), true)
|
|
137
|
+
* assertEquals(voiced(0.005, true), false)
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
140
|
+
export let voiced = (level: number, was: boolean) =>
|
|
141
|
+
level >= (was ? 0.01 : 0.04)
|
|
142
|
+
|
|
143
|
+
/** Open a call: a session at Realtime, through the app's door. */
|
|
144
|
+
export let join = async (opts: Opts): Promise<Call> => {
|
|
145
|
+
let door = new URL(opts.door ?? 'api/rtc/', document.baseURI)
|
|
146
|
+
let send = opts.fetch ?? fetch.bind(globalThis)
|
|
147
|
+
let state: State = 'joining'
|
|
148
|
+
let moved = (s: State) => {
|
|
149
|
+
if (s == state) return
|
|
150
|
+
state = s
|
|
151
|
+
opts.change?.(s)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let leaving = new AbortController()
|
|
155
|
+
let hasLeft = () => leaving.signal.aborted
|
|
156
|
+
let session = ''
|
|
157
|
+
let key = ''
|
|
158
|
+
let ask = async (method: string, path: string, body?: unknown) => {
|
|
159
|
+
let res = await send(new URL(path, door), {
|
|
160
|
+
method,
|
|
161
|
+
credentials: 'same-origin',
|
|
162
|
+
headers: {
|
|
163
|
+
...(key ? { [KEY]: key } : {}),
|
|
164
|
+
...(body === undefined ? {} : { 'content-type': 'application/json' }),
|
|
165
|
+
},
|
|
166
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
167
|
+
signal: AbortSignal.any([AbortSignal.timeout(15_000), leaving.signal]),
|
|
168
|
+
})
|
|
169
|
+
let said = await res.json().catch(() => null)
|
|
170
|
+
if (!res.ok) {
|
|
171
|
+
let e = said?.error ?? {}
|
|
172
|
+
throw new Refused(
|
|
173
|
+
e.code ?? 'unavailable',
|
|
174
|
+
e.message ?? `the door answered ${res.status}`,
|
|
175
|
+
res.status,
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
return said
|
|
179
|
+
}
|
|
180
|
+
let on = (path = '') => `sessions/${session}${path}`
|
|
181
|
+
|
|
182
|
+
// One negotiation at a time: each is an offer and an answer, and a second
|
|
183
|
+
// started before the first settles would answer the wrong offer.
|
|
184
|
+
let queue: Promise<unknown> = Promise.resolve()
|
|
185
|
+
let serial = <T>(fn: () => Promise<T>): Promise<T> => {
|
|
186
|
+
let next = queue.then(fn, fn)
|
|
187
|
+
queue = next.catch(() => {})
|
|
188
|
+
return next
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
let pc!: RTCPeerConnection
|
|
192
|
+
let voice: RTCRtpTransceiver
|
|
193
|
+
let sent = new Map<
|
|
194
|
+
string,
|
|
195
|
+
{ track: MediaStreamTrack; tx: RTCRtpTransceiver }
|
|
196
|
+
>()
|
|
197
|
+
let heard = new Set<{ dead: boolean; detach: () => void }>()
|
|
198
|
+
let cancelBackoff: (() => void) | null = null
|
|
199
|
+
let muted = false
|
|
200
|
+
let talking = false
|
|
201
|
+
|
|
202
|
+
// Graph writes may be asynchronous. Keep their order even when an older
|
|
203
|
+
// publication is still settling as a call leaves and another joins.
|
|
204
|
+
let writes: Promise<void> = Promise.resolve()
|
|
205
|
+
let writePresence = (rtc: Bundle['rtc']) => {
|
|
206
|
+
let next = writes.then(() =>
|
|
207
|
+
opts.write([{
|
|
208
|
+
entity: { eid: opts.entity },
|
|
209
|
+
rtc,
|
|
210
|
+
}])
|
|
211
|
+
).then(() => {})
|
|
212
|
+
writes = next.catch(() => {})
|
|
213
|
+
return next
|
|
214
|
+
}
|
|
215
|
+
let wear = () =>
|
|
216
|
+
hasLeft() ? Promise.resolve() : writePresence(
|
|
217
|
+
sent.size
|
|
218
|
+
? { session, tracks: [...sent.keys()], muted, talking }
|
|
219
|
+
: { session, tracks: [], muted, talking: false },
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
let open = async () => {
|
|
223
|
+
key = ''
|
|
224
|
+
let { iceServers } = await ask('POST', 'ice')
|
|
225
|
+
if (hasLeft()) return
|
|
226
|
+
let opened = await ask('POST', 'sessions/new')
|
|
227
|
+
if (hasLeft()) return
|
|
228
|
+
session = opened.sessionId
|
|
229
|
+
key = opened.key
|
|
230
|
+
pc = new RTCPeerConnection({ iceServers, bundlePolicy: 'max-bundle' })
|
|
231
|
+
let mine = pc
|
|
232
|
+
let lost: ReturnType<typeof setTimeout> | undefined
|
|
233
|
+
pc.onconnectionstatechange = () => {
|
|
234
|
+
if (mine != pc || hasLeft()) return
|
|
235
|
+
clearTimeout(lost)
|
|
236
|
+
if (pc.connectionState == 'failed') void rebuild()
|
|
237
|
+
// A connection that drops often comes back by itself; one that stays
|
|
238
|
+
// down is rebuilt.
|
|
239
|
+
if (pc.connectionState == 'disconnected') {
|
|
240
|
+
lost = setTimeout(() => mine == pc && void rebuild(), 5000)
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
voice = await sender(null, VOICE)
|
|
244
|
+
if (hasLeft()) pc.close()
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// A sender section, offered and answered as a local track of the session.
|
|
248
|
+
let sender = async (track: MediaStreamTrack | null, name: string) => {
|
|
249
|
+
let tx = pc.addTransceiver(track ?? 'audio', {
|
|
250
|
+
direction: 'sendonly',
|
|
251
|
+
sendEncodings: [{ maxBitrate: BITRATE }],
|
|
252
|
+
})
|
|
253
|
+
await pc.setLocalDescription(await pc.createOffer())
|
|
254
|
+
let res = await ask('POST', on('/tracks/new'), {
|
|
255
|
+
sessionDescription: pc.localDescription,
|
|
256
|
+
tracks: [{ location: 'local', mid: tx.mid, trackName: name }],
|
|
257
|
+
})
|
|
258
|
+
await pc.setRemoteDescription(res.sessionDescription)
|
|
259
|
+
return tx
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
let push = async (track: MediaStreamTrack, name: string) => {
|
|
263
|
+
let previous = sent.get(name)
|
|
264
|
+
let live = () => track.readyState != 'ended'
|
|
265
|
+
let tx = name == VOICE ? voice : await sender(track, name)
|
|
266
|
+
if (
|
|
267
|
+
hasLeft() || !live() ||
|
|
268
|
+
(previous && sent.get(name) != previous)
|
|
269
|
+
) {
|
|
270
|
+
if (tx != voice) tx.stop()
|
|
271
|
+
return
|
|
272
|
+
}
|
|
273
|
+
if (tx == voice) await voice.sender.replaceTrack(track)
|
|
274
|
+
if (
|
|
275
|
+
hasLeft() || !live() ||
|
|
276
|
+
(previous && sent.get(name) != previous)
|
|
277
|
+
) {
|
|
278
|
+
await tx.sender.replaceTrack(null).catch(() => {})
|
|
279
|
+
if (tx != voice) tx.stop()
|
|
280
|
+
return
|
|
281
|
+
}
|
|
282
|
+
sent.set(name, { track, tx })
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Close transceivers on this session: stopped here, offered, answered. The
|
|
286
|
+
// voice's section is never among them, so the offer keeps its BUNDLE tag.
|
|
287
|
+
let close = async (txs: RTCRtpTransceiver[]) => {
|
|
288
|
+
let mids = txs.map((tx) => tx.mid).filter(Boolean)
|
|
289
|
+
for (let tx of txs) tx.stop()
|
|
290
|
+
if (!mids.length || pc.connectionState == 'closed') return
|
|
291
|
+
let tracks = mids.map((mid) => ({ mid }))
|
|
292
|
+
await pc.setLocalDescription(await pc.createOffer())
|
|
293
|
+
let res = await ask('PUT', on('/tracks/close'), {
|
|
294
|
+
tracks,
|
|
295
|
+
sessionDescription: pc.localDescription,
|
|
296
|
+
force: false,
|
|
297
|
+
})
|
|
298
|
+
if (res.sessionDescription) {
|
|
299
|
+
await pc.setRemoteDescription(res.sessionDescription)
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// Leave does not wait for a failing connection's backoff or negotiations.
|
|
304
|
+
let backoff = (ms: number) =>
|
|
305
|
+
new Promise<void>((resolve) => {
|
|
306
|
+
let timer = setTimeout(done, ms)
|
|
307
|
+
function done() {
|
|
308
|
+
clearTimeout(timer)
|
|
309
|
+
if (cancelBackoff == done) cancelBackoff = null
|
|
310
|
+
resolve()
|
|
311
|
+
}
|
|
312
|
+
cancelBackoff = done
|
|
313
|
+
})
|
|
314
|
+
|
|
315
|
+
let rebuilding: Promise<void> | null = null
|
|
316
|
+
let rebuild = () =>
|
|
317
|
+
rebuilding ??= serial(async () => {
|
|
318
|
+
moved('lost')
|
|
319
|
+
for (let h of heard) {
|
|
320
|
+
h.dead = true
|
|
321
|
+
h.detach()
|
|
322
|
+
}
|
|
323
|
+
heard.clear()
|
|
324
|
+
pc.close()
|
|
325
|
+
for (let tries = 0; !hasLeft(); tries++) {
|
|
326
|
+
try {
|
|
327
|
+
await open()
|
|
328
|
+
if (hasLeft()) {
|
|
329
|
+
pc.close()
|
|
330
|
+
return
|
|
331
|
+
}
|
|
332
|
+
// A stopped input is removed from sent immediately, even while
|
|
333
|
+
// the rebuild is awaiting a failing door or its backoff.
|
|
334
|
+
for (let [name, { track }] of [...sent]) {
|
|
335
|
+
if (hasLeft()) return
|
|
336
|
+
if (sent.get(name)?.track == track) await push(track, name)
|
|
337
|
+
}
|
|
338
|
+
if (hasLeft()) return
|
|
339
|
+
await wear()
|
|
340
|
+
if (hasLeft()) return
|
|
341
|
+
moved('live')
|
|
342
|
+
return
|
|
343
|
+
} catch (e) {
|
|
344
|
+
if (hasLeft()) return
|
|
345
|
+
if (e instanceof Refused && e.code == 'limit') return moved('limit')
|
|
346
|
+
await backoff(Math.min(30_000, 1000 * 2 ** tries))
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}).finally(() => rebuilding = null)
|
|
350
|
+
|
|
351
|
+
let renew = async () => {
|
|
352
|
+
if (hasLeft() || rebuilding) return
|
|
353
|
+
try {
|
|
354
|
+
await ask('POST', on('/renew'))
|
|
355
|
+
if (hasLeft()) return
|
|
356
|
+
moved('live')
|
|
357
|
+
await wear()
|
|
358
|
+
} catch (e) {
|
|
359
|
+
if (hasLeft() || !(e instanceof Refused)) return
|
|
360
|
+
if (e.code == 'limit') moved('limit')
|
|
361
|
+
else if (e.status == 404) void rebuild()
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// How loud the microphone is, off the sender's own statistics, so nothing
|
|
366
|
+
// here needs an AudioContext.
|
|
367
|
+
let listen = async () => {
|
|
368
|
+
let voice = [...sent.values()][0]
|
|
369
|
+
let level = 0
|
|
370
|
+
if (voice && !muted) {
|
|
371
|
+
for (let r of (await voice.tx.sender.getStats()).values()) {
|
|
372
|
+
if (r.type == 'media-source' && typeof r.audioLevel == 'number') {
|
|
373
|
+
level = r.audioLevel
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
if (hasLeft()) return
|
|
378
|
+
let now = voice && !muted ? voiced(level, talking) : false
|
|
379
|
+
if (now != talking) {
|
|
380
|
+
talking = now
|
|
381
|
+
await wear()
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
try {
|
|
386
|
+
await open()
|
|
387
|
+
} catch (e) {
|
|
388
|
+
if (e instanceof Refused) moved(e.code == 'limit' ? 'limit' : 'refused')
|
|
389
|
+
throw e
|
|
390
|
+
}
|
|
391
|
+
try {
|
|
392
|
+
await wear()
|
|
393
|
+
} catch (error) {
|
|
394
|
+
// An asynchronous graph refusal during setup must not leave an open RTC
|
|
395
|
+
// session with no Call handle that could close it.
|
|
396
|
+
leaving.abort()
|
|
397
|
+
pc.close()
|
|
398
|
+
throw error
|
|
399
|
+
}
|
|
400
|
+
if (hasLeft()) {
|
|
401
|
+
pc.close()
|
|
402
|
+
throw new Error('The call has left')
|
|
403
|
+
}
|
|
404
|
+
moved('live')
|
|
405
|
+
let renewing = setInterval(renew, RENEW)
|
|
406
|
+
let hearing = setInterval(() => void listen().catch(() => {}), 200)
|
|
407
|
+
|
|
408
|
+
let call: Call = {
|
|
409
|
+
get session() {
|
|
410
|
+
return session
|
|
411
|
+
},
|
|
412
|
+
get state() {
|
|
413
|
+
return state
|
|
414
|
+
},
|
|
415
|
+
publish: (track, name = VOICE) =>
|
|
416
|
+
serial(async () => {
|
|
417
|
+
if (hasLeft()) throw new Error('The call has left')
|
|
418
|
+
await push(track, name)
|
|
419
|
+
if (hasLeft() || track.readyState == 'ended') {
|
|
420
|
+
let held = sent.get(name)
|
|
421
|
+
if (held?.track == track) {
|
|
422
|
+
sent.delete(name)
|
|
423
|
+
await held.tx.sender.replaceTrack(null).catch(() => {})
|
|
424
|
+
}
|
|
425
|
+
throw new Error('The call or microphone has ended')
|
|
426
|
+
}
|
|
427
|
+
try {
|
|
428
|
+
await wear()
|
|
429
|
+
if (hasLeft()) throw new Error('The call has left')
|
|
430
|
+
} catch (error) {
|
|
431
|
+
// If the graph refuses the write, do not strand a sender without
|
|
432
|
+
// a stop handle. The media is detached even if renegotiation fails.
|
|
433
|
+
let held = sent.get(name)
|
|
434
|
+
if (held?.track == track) {
|
|
435
|
+
sent.delete(name)
|
|
436
|
+
if (held.tx == voice) await voice.sender.replaceTrack(null)
|
|
437
|
+
else await close([held.tx]).catch(() => {})
|
|
438
|
+
}
|
|
439
|
+
throw error
|
|
440
|
+
}
|
|
441
|
+
return {
|
|
442
|
+
name,
|
|
443
|
+
stop: async () => {
|
|
444
|
+
let held = sent.get(name)
|
|
445
|
+
if (!held || held.track != track) return
|
|
446
|
+
sent.delete(name)
|
|
447
|
+
// Presence and outgoing audio must go away now, not after a
|
|
448
|
+
// reconnect's 30-second backoff in the negotiation queue.
|
|
449
|
+
if (held.tx == voice) {
|
|
450
|
+
await held.tx.sender.replaceTrack(null).catch(() => {})
|
|
451
|
+
} else {
|
|
452
|
+
// Stop sending even if a reconnection holds the negotiation queue.
|
|
453
|
+
held.tx.stop()
|
|
454
|
+
let at = pc
|
|
455
|
+
void serial(async () => {
|
|
456
|
+
if (!hasLeft() && at == pc) await close([held.tx])
|
|
457
|
+
}).catch(() => {})
|
|
458
|
+
}
|
|
459
|
+
await wear()
|
|
460
|
+
},
|
|
461
|
+
}
|
|
462
|
+
}),
|
|
463
|
+
diagnose: async (name = VOICE) => {
|
|
464
|
+
let selected = sent.get(name)
|
|
465
|
+
if (!selected) return null
|
|
466
|
+
let stats = await selected.tx.sender.getStats()
|
|
467
|
+
let level: number | null = null
|
|
468
|
+
let energy: number | null = null
|
|
469
|
+
let duration: number | null = null
|
|
470
|
+
let packets: number | null = null
|
|
471
|
+
for (let r of stats.values()) {
|
|
472
|
+
if (r.type == 'media-source') {
|
|
473
|
+
if (typeof r.audioLevel == 'number') level = r.audioLevel
|
|
474
|
+
if (typeof r.totalAudioEnergy == 'number') energy = r.totalAudioEnergy
|
|
475
|
+
if (typeof r.totalSamplesDuration == 'number') {
|
|
476
|
+
duration = r.totalSamplesDuration
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (
|
|
480
|
+
r.type == 'outbound-rtp' && r.kind == 'audio' &&
|
|
481
|
+
typeof r.packetsSent == 'number'
|
|
482
|
+
) packets = r.packetsSent
|
|
483
|
+
}
|
|
484
|
+
return {
|
|
485
|
+
ready: selected.track.readyState == 'live',
|
|
486
|
+
enabled: selected.track.enabled,
|
|
487
|
+
connected: pc.connectionState == 'connected',
|
|
488
|
+
level,
|
|
489
|
+
energy,
|
|
490
|
+
duration,
|
|
491
|
+
packets,
|
|
492
|
+
}
|
|
493
|
+
},
|
|
494
|
+
mute: (on) => {
|
|
495
|
+
muted = on
|
|
496
|
+
for (let { track } of sent.values()) track.enabled = !on
|
|
497
|
+
if (on) talking = false
|
|
498
|
+
void wear().catch(() => {})
|
|
499
|
+
},
|
|
500
|
+
hear: (from, name) =>
|
|
501
|
+
serial(async () => {
|
|
502
|
+
if (hasLeft() || state == 'limit') return null
|
|
503
|
+
let res = await ask('POST', on('/tracks/new'), {
|
|
504
|
+
tracks: [{ location: 'remote', sessionId: from, trackName: name }],
|
|
505
|
+
})
|
|
506
|
+
let got = res.tracks?.[0]
|
|
507
|
+
if (!got?.mid || got.errorCode) return null
|
|
508
|
+
await pc.setRemoteDescription(res.sessionDescription)
|
|
509
|
+
await pc.setLocalDescription(await pc.createAnswer())
|
|
510
|
+
await ask('PUT', on('/renegotiate'), {
|
|
511
|
+
sessionDescription: pc.localDescription,
|
|
512
|
+
})
|
|
513
|
+
let tx = pc.getTransceivers().find((t) => t.mid == got.mid)
|
|
514
|
+
if (!tx) return null
|
|
515
|
+
let stream = new MediaStream([tx.receiver.track])
|
|
516
|
+
let el = new Audio()
|
|
517
|
+
el.muted = true
|
|
518
|
+
el.srcObject = stream
|
|
519
|
+
el.play().catch(() => {})
|
|
520
|
+
let mark = {
|
|
521
|
+
dead: false,
|
|
522
|
+
detach: () => {
|
|
523
|
+
el.srcObject = null
|
|
524
|
+
},
|
|
525
|
+
}
|
|
526
|
+
heard.add(mark)
|
|
527
|
+
let at = pc
|
|
528
|
+
return {
|
|
529
|
+
stream,
|
|
530
|
+
get live() {
|
|
531
|
+
return !mark.dead
|
|
532
|
+
},
|
|
533
|
+
stop: () =>
|
|
534
|
+
serial(async () => {
|
|
535
|
+
mark.detach()
|
|
536
|
+
if (mark.dead) return
|
|
537
|
+
mark.dead = true
|
|
538
|
+
heard.delete(mark)
|
|
539
|
+
if (at == pc && !hasLeft()) await close([tx])
|
|
540
|
+
}),
|
|
541
|
+
}
|
|
542
|
+
}),
|
|
543
|
+
// Leave cannot wait behind a reconnect's backoff or a stuck door.
|
|
544
|
+
// Its caller may immediately join again as this hero; the presence write
|
|
545
|
+
// is performed before this promise settles.
|
|
546
|
+
leave: async () => {
|
|
547
|
+
if (hasLeft()) return
|
|
548
|
+
clearInterval(renewing)
|
|
549
|
+
clearInterval(hearing)
|
|
550
|
+
moved('left')
|
|
551
|
+
leaving.abort()
|
|
552
|
+
cancelBackoff?.()
|
|
553
|
+
for (let h of heard) {
|
|
554
|
+
h.dead = true
|
|
555
|
+
h.detach()
|
|
556
|
+
}
|
|
557
|
+
heard.clear()
|
|
558
|
+
sent.clear()
|
|
559
|
+
pc.close()
|
|
560
|
+
await writePresence(null)
|
|
561
|
+
},
|
|
562
|
+
}
|
|
563
|
+
return call
|
|
564
|
+
}
|
package/loop.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// A page's own sound, played so the browser's echo canceller hears it.
|
|
2
|
+
//
|
|
3
|
+
// Chrome cancels what a media element plays from the microphone, and not what
|
|
4
|
+
// Web Audio plays: a page that places voices in space with Web Audio sends
|
|
5
|
+
// each listener's loudspeakers back into their microphone, and every speaker
|
|
6
|
+
// hears themselves a moment later. Played through an <audio> element it is
|
|
7
|
+
// cancelled, but an element fed straight from a MediaStreamDestination is not
|
|
8
|
+
// either; one fed from a remote WebRTC track is. So the loop is two
|
|
9
|
+
// RTCPeerConnections inside the page: Web Audio's mix goes into one, comes out
|
|
10
|
+
// of the other as a remote track, and plays through an <audio>.
|
|
11
|
+
//
|
|
12
|
+
// The mix stays stereo, since a voice placed in space is nothing without its
|
|
13
|
+
// left and right: Opus is asked for two channels at a bitrate for music, not
|
|
14
|
+
// for a voice. The loop adds some 40 ms (a 16 ms jitter buffer and a 20 ms
|
|
15
|
+
// Opus frame, measured in Chrome 150), so a page routes through it only while
|
|
16
|
+
// a microphone is open.
|
|
17
|
+
/** A loop: connect sound `into` it and it plays through an <audio> element
|
|
18
|
+
* once `ready`; `stop` ends it. */ // Opus in both directions as two channels, at up to 256 kbit/s.
|
|
19
|
+
let stereo = (d)=>{
|
|
20
|
+
let sdp = d.sdp ?? '';
|
|
21
|
+
let pt = /a=rtpmap:(\d+) opus\/48000\/2/i.exec(sdp)?.[1];
|
|
22
|
+
if (!pt) return d;
|
|
23
|
+
return {
|
|
24
|
+
type: d.type,
|
|
25
|
+
sdp: sdp.replace(new RegExp(`a=fmtp:${pt} (.*)`), (_, params)=>`a=fmtp:${pt} ${params};stereo=1;sprop-stereo=1;maxaveragebitrate=256000`)
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
/** A loop for Web Audio on `ctx` that the echo canceller hears. It is
|
|
29
|
+
* `ready` once the two ends have met and the element plays, a moment after it
|
|
30
|
+
* is made; until then, and if it never is, sound connected into it is not
|
|
31
|
+
* heard, so a page moves its mix over once it is. */ export let loopback = (ctx)=>{
|
|
32
|
+
let into = ctx.createMediaStreamDestination();
|
|
33
|
+
let send = new RTCPeerConnection();
|
|
34
|
+
let hear = new RTCPeerConnection();
|
|
35
|
+
let out = new Audio();
|
|
36
|
+
send.onicecandidate = (e)=>e.candidate && hear.addIceCandidate(e.candidate);
|
|
37
|
+
hear.onicecandidate = (e)=>e.candidate && send.addIceCandidate(e.candidate);
|
|
38
|
+
let track = new Promise((ok)=>hear.ontrack = (e)=>ok(e.track));
|
|
39
|
+
send.addTrack(into.stream.getAudioTracks()[0], into.stream);
|
|
40
|
+
let ready = (async ()=>{
|
|
41
|
+
let offer = await send.createOffer();
|
|
42
|
+
await send.setLocalDescription(offer);
|
|
43
|
+
await hear.setRemoteDescription(stereo(offer));
|
|
44
|
+
let answer = stereo(await hear.createAnswer());
|
|
45
|
+
await hear.setLocalDescription(answer);
|
|
46
|
+
await send.setRemoteDescription(answer);
|
|
47
|
+
out.srcObject = new MediaStream([
|
|
48
|
+
await track
|
|
49
|
+
]);
|
|
50
|
+
await out.play();
|
|
51
|
+
})();
|
|
52
|
+
return {
|
|
53
|
+
into,
|
|
54
|
+
ready,
|
|
55
|
+
stop: ()=>{
|
|
56
|
+
out.pause();
|
|
57
|
+
out.srcObject = null;
|
|
58
|
+
send.close();
|
|
59
|
+
hear.close();
|
|
60
|
+
into.disconnect();
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
//# sourceMappingURL=loop.js.map
|
package/loop.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loop.js","sources":["./loop.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,oEAAoE;AACpE,+EAA+E;AAC/E,gEAAgE;AAChE,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,wBAAwB;AAExB;iCACiC,GAGjC,gEAAgE;AAChE,IAAI,SAAS,CAAC;EACZ,IAAI,MAAM,EAAE,GAAG,IAAI;EACnB,IAAI,KAAK,iCAAiC,IAAI,CAAC,MAAM,CAAC,EAAE;EACxD,IAAI,CAAC,IAAI,OAAO;EAChB,OAAO;IACL,MAAM,EAAE,IAAI;IACZ,KAAK,IAAI,OAAO,CACd,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,KAAK,CAAC,GAC9B,CAAC,GAAG,SACF,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,OAAO,iDAAiD,CAAC;EAE/E;AACF;AAEA;;;mDAGmD,GACnD,OAAO,IAAI,WAAW,CAAC;EACrB,IAAI,OAAO,IAAI,4BAA4B;EAC3C,IAAI,OAAO,IAAI;EACf,IAAI,OAAO,IAAI;EACf,IAAI,MAAM,IAAI;EACd,KAAK,cAAc,GAAG,CAAC,IAAM,EAAE,SAAS,IAAI,KAAK,eAAe,CAAC,EAAE,SAAS;EAC5E,KAAK,cAAc,GAAG,CAAC,IAAM,EAAE,SAAS,IAAI,KAAK,eAAe,CAAC,EAAE,SAAS;EAC5E,IAAI,QAAQ,IAAI,QAA0B,CAAC,KACzC,KAAK,OAAO,GAAG,CAAC,IAAM,GAAG,EAAE,KAAK;EAElC,KAAK,QAAQ,CAAC,KAAK,MAAM,CAAC,cAAc,EAAE,CAAC,EAAE,EAAE,KAAK,MAAM;EAC1D,IAAI,QAAQ,CAAC;IACX,IAAI,QAAQ,MAAM,KAAK,WAAW;IAClC,MAAM,KAAK,mBAAmB,CAAC;IAC/B,MAAM,KAAK,oBAAoB,CAAC,OAAO;IACvC,IAAI,SAAS,OAAO,MAAM,KAAK,YAAY;IAC3C,MAAM,KAAK,mBAAmB,CAAC;IAC/B,MAAM,KAAK,oBAAoB,CAAC;IAChC,IAAI,SAAS,GAAG,IAAI,YAAY;MAAC,MAAM;KAAM;IAC7C,MAAM,IAAI,IAAI;EAChB,CAAC;EACD,OAAO;IACL;IACA;IACA,MAAM;MACJ,IAAI,KAAK;MACT,IAAI,SAAS,GAAG;MAChB,KAAK,KAAK;MACV,KAAK,KAAK;MACV,KAAK,UAAU;IACjB;EACF;AACF,EAAC"}
|