@caprid/relay 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +1 -1
  2. package/dist/client-diagnostics.d.ts +18 -4
  3. package/dist/client-diagnostics.d.ts.map +1 -1
  4. package/dist/client-diagnostics.js +33 -7
  5. package/dist/client-diagnostics.js.map +1 -1
  6. package/dist/cmcd.d.ts +99 -0
  7. package/dist/cmcd.d.ts.map +1 -0
  8. package/dist/cmcd.js +631 -0
  9. package/dist/cmcd.js.map +1 -0
  10. package/dist/connect-session.d.ts +30 -10
  11. package/dist/connect-session.d.ts.map +1 -1
  12. package/dist/connect-session.js +74 -13
  13. package/dist/connect-session.js.map +1 -1
  14. package/dist/connect.d.ts +9 -1
  15. package/dist/connect.d.ts.map +1 -1
  16. package/dist/connect.js +3 -2
  17. package/dist/connect.js.map +1 -1
  18. package/dist/diagnostics-report.d.ts +15 -6
  19. package/dist/diagnostics-report.d.ts.map +1 -1
  20. package/dist/diagnostics-report.js +38 -13
  21. package/dist/diagnostics-report.js.map +1 -1
  22. package/dist/diagnostics.d.ts +3 -0
  23. package/dist/diagnostics.d.ts.map +1 -1
  24. package/dist/diagnostics.js +3 -0
  25. package/dist/diagnostics.js.map +1 -1
  26. package/dist/frame-reader.d.ts +8 -5
  27. package/dist/frame-reader.d.ts.map +1 -1
  28. package/dist/frame-reader.js +22 -4
  29. package/dist/frame-reader.js.map +1 -1
  30. package/dist/frame-writer.d.ts +3 -2
  31. package/dist/frame-writer.d.ts.map +1 -1
  32. package/dist/frame-writer.js +23 -5
  33. package/dist/frame-writer.js.map +1 -1
  34. package/dist/media-track-properties.d.ts +3 -2
  35. package/dist/media-track-properties.d.ts.map +1 -1
  36. package/dist/media-track-properties.js +3 -2
  37. package/dist/media-track-properties.js.map +1 -1
  38. package/dist/publish.d.ts +19 -6
  39. package/dist/publish.d.ts.map +1 -1
  40. package/dist/publish.js +17 -4
  41. package/dist/publish.js.map +1 -1
  42. package/dist/relay-session.d.ts.map +1 -1
  43. package/dist/relay-session.js +3 -1
  44. package/dist/relay-session.js.map +1 -1
  45. package/dist/replaceable-track.d.ts +2 -2
  46. package/dist/replaceable-track.d.ts.map +1 -1
  47. package/dist/replaceable-track.js +8 -2
  48. package/dist/replaceable-track.js.map +1 -1
  49. package/dist/subscription.d.ts.map +1 -1
  50. package/dist/subscription.js +22 -8
  51. package/dist/subscription.js.map +1 -1
  52. package/dist/supervised-publisher.d.ts +15 -1
  53. package/dist/supervised-publisher.d.ts.map +1 -1
  54. package/dist/supervised-publisher.js +8 -2
  55. package/dist/supervised-publisher.js.map +1 -1
  56. package/dist/supervised-relay.d.ts +15 -1
  57. package/dist/supervised-relay.d.ts.map +1 -1
  58. package/dist/supervised-relay.js +8 -2
  59. package/dist/supervised-relay.js.map +1 -1
  60. package/dist/supervised-subscriber.d.ts +18 -6
  61. package/dist/supervised-subscriber.d.ts.map +1 -1
  62. package/dist/supervised-subscriber.js +18 -4
  63. package/dist/supervised-subscriber.js.map +1 -1
  64. package/dist/supervision.d.ts +18 -0
  65. package/dist/supervision.d.ts.map +1 -1
  66. package/dist/supervision.js +34 -0
  67. package/dist/supervision.js.map +1 -1
  68. package/dist/supervisor.d.ts +15 -10
  69. package/dist/supervisor.d.ts.map +1 -1
  70. package/dist/supervisor.js +171 -16
  71. package/dist/supervisor.js.map +1 -1
  72. package/dist/version.d.ts +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/write-slot.d.ts +11 -0
  75. package/dist/write-slot.d.ts.map +1 -1
  76. package/dist/write-slot.js +16 -1
  77. package/dist/write-slot.js.map +1 -1
  78. package/package.json +7 -7
package/dist/cmcd.js ADDED
@@ -0,0 +1,631 @@
1
+ import { DIAGNOSTICS_TRACKS, diagnosticsPriority, } from './client-diagnostics.js';
2
+ import { createFrameWriter } from './frame-writer.js';
3
+ import { encodeJSON } from './payload.js';
4
+ import { DEFAULT_PUBLISHER_PRIORITY } from './validation.js';
5
+ /** Keys draft-wilaw-moq-cmcd-event-timeline-00 (§3) bans: they carry HTTP request semantics. */
6
+ const BANNED_KEYS = new Set([
7
+ 'ab',
8
+ 'cmsdd',
9
+ 'cmsds',
10
+ 'd',
11
+ 'dl',
12
+ 'h',
13
+ 'lab',
14
+ 'nor',
15
+ 'nr',
16
+ 'ot',
17
+ 'rc',
18
+ 'rtp',
19
+ 'sf',
20
+ 'smrt',
21
+ 'su',
22
+ 'tab',
23
+ 'ttfb',
24
+ 'ttfbb',
25
+ 'ttlb',
26
+ 'url',
27
+ // `ts` is the record's `T`, never a key of its data.
28
+ 'ts',
29
+ ]);
30
+ /** Keys the draft allows in a record, `v` included. */
31
+ const ALLOWED_KEYS = new Set([
32
+ 'bl',
33
+ 'bg',
34
+ 'br',
35
+ 'bs',
36
+ 'bsa',
37
+ 'bsd',
38
+ 'bsda',
39
+ 'cen',
40
+ 'cid',
41
+ 'cs',
42
+ 'dfa',
43
+ 'e',
44
+ 'ec',
45
+ 'lb',
46
+ 'ltc',
47
+ 'msd',
48
+ 'mtp',
49
+ 'pb',
50
+ 'pr',
51
+ 'pt',
52
+ 'sid',
53
+ 'sn',
54
+ 'st',
55
+ 'sta',
56
+ 'tb',
57
+ 'tbl',
58
+ 'tpb',
59
+ 'v',
60
+ ]);
61
+ /** Every key the SDK derives. */
62
+ const DEFAULT_KEYS = [
63
+ 'bg',
64
+ 'bl',
65
+ 'br',
66
+ 'bs',
67
+ 'bsa',
68
+ 'bsd',
69
+ 'bsda',
70
+ 'cid',
71
+ 'dfa',
72
+ 'ec',
73
+ 'msd',
74
+ 'mtp',
75
+ 'sid',
76
+ 'sn',
77
+ 'st',
78
+ 'sta',
79
+ 'tbl',
80
+ ];
81
+ const EVENT_TYPES = ['t', 'ps', 'e', 'b'];
82
+ /** Keys an application's `keys` cannot set. */
83
+ const SDK_KEYS = new Set(['v', 'e', 'sn', 'sid']);
84
+ const DEFAULT_INTERVAL_MS = 30_000;
85
+ /** The least `t` interval: the draft (§6) asks a client to coerce lower ones up. */
86
+ const MIN_INTERVAL_MS = 5_000;
87
+ /** Between a want's errors and those of the connection, the most error codes held for one record. */
88
+ const MAX_PENDING = 32;
89
+ /** How often the remote tracks are looked at while `diag.cmcd` has demand: play states and byte rates. */
90
+ const LOOK_MS = 1_000;
91
+ /** The window byte rates are measured over, and the least span that gives one. */
92
+ const RATE_WINDOW_MS = 10_000;
93
+ const RATE_MIN_SPAN_MS = 1_000;
94
+ /** A video track that has read no object for longer than this is rebuffering. */
95
+ const VIDEO_STALL_MS = 1_000;
96
+ /** The Default Publisher Priority of `diag.cmcd`, between `diag.events` (224) and `diag.stats` (240). */
97
+ const CMCD_PRIORITY = 232;
98
+ /** CTA-5004-B's longest `cid`. */
99
+ const MAX_CID = 128;
100
+ /**
101
+ * Publish CMCD v2 records on `diag.cmcd` of the publication, derived from what the recorder holds: one record per
102
+ * remote media track (a frame reader that reads a want, with `cid` its namespace and track) at each trigger, or one
103
+ * without `cid` while there is none. Nothing is sent while the relay has no subscription to the track. Each group
104
+ * carries one record, or a batch, as an MSF Event Timeline array; group IDs start at 0. Publish it beside
105
+ * {@link publishDiagnostics}, on the same publication.
106
+ *
107
+ * ```ts
108
+ * const publication = publishCmcd(diagnostics, relay.publish(['diag', 'player', id, viewer]), {
109
+ * events: ['t', 'ps', 'e'],
110
+ * intervalMs: 10_000,
111
+ * });
112
+ * ```
113
+ */
114
+ export function publishCmcd(diagnostics, publisher, options = {}) {
115
+ if (typeof options !== 'object' || options === null)
116
+ throw new TypeError('options must be an object');
117
+ const events = eventsOption(options.events);
118
+ const intervalMs = intervalOption(options.intervalMs);
119
+ const enabled = keysOption(options.enabledKeys);
120
+ const sid = options.sid ?? diagnostics.instance;
121
+ if (typeof sid !== 'string' || sid.length === 0 || sid.length > 64) {
122
+ throw new TypeError('sid must be a string of 1 to 64 characters');
123
+ }
124
+ const batchCount = positiveInteger(options.batchCount, 'batchCount');
125
+ const batchIntervalMs = positiveInteger(options.batchIntervalMs, 'batchIntervalMs');
126
+ const priority = diagnosticsPriority(options.priority, CMCD_PRIORITY, 'priority');
127
+ const appKeys = options.keys;
128
+ if (appKeys !== undefined && typeof appKeys !== 'function')
129
+ throw new TypeError('keys must be a function');
130
+ const track = publisher.registerTrack({
131
+ track: DIAGNOSTICS_TRACKS.cmcd,
132
+ trackProperties: [{ type: DEFAULT_PUBLISHER_PRIORITY, value: priority }],
133
+ });
134
+ // Records carry no delivery timeout: a starvation's duration and an error code are reported once.
135
+ const writer = createFrameWriter(track, { grouping: 'frame', maxBacklog: 64 });
136
+ const tracks = new Map();
137
+ const gaps = new Map();
138
+ const dropouts = new Map();
139
+ /** Which cid each want reads, by the scope that reported it and its key. */
140
+ const wantCids = new Map();
141
+ /**
142
+ * Error codes not yet reported: a want's, by cid; the connection's, held by each track until its own record, and
143
+ * here while there is no track, for the tracks the next look finds or else the next record without one.
144
+ */
145
+ const wantErrors = new Map();
146
+ let linkErrors = [];
147
+ const linkError = (code) => {
148
+ if (tracks.size === 0)
149
+ pushCapped(linkErrors, code);
150
+ for (const state of tracks.values())
151
+ pushCapped(state.linkCodes, code);
152
+ };
153
+ /** The cids whose want failed for good, until a want subscribes to one again. */
154
+ const failed = new Set();
155
+ /** The session's first `first-object`: how long the first want took to its first object. */
156
+ let mediaStartMs;
157
+ let msdSent = false;
158
+ let looked = false;
159
+ let sn = 0;
160
+ let batch = [];
161
+ let batchTimer;
162
+ let closed = false;
163
+ const starvationsOf = (map, scope) => {
164
+ let found = map.get(scope);
165
+ if (!found) {
166
+ found = { count: 0, totalMs: 0, pending: [] };
167
+ map.set(scope, found);
168
+ }
169
+ return found;
170
+ };
171
+ const pushCapped = (list, code) => {
172
+ if (list.includes(code))
173
+ return;
174
+ list.push(code);
175
+ if (list.length > MAX_PENDING)
176
+ list.shift();
177
+ };
178
+ /** Take in one recorder event. Returns the trigger it makes, if any, and the cid it is for. */
179
+ const consume = (event) => {
180
+ const scope = event.source ?? '';
181
+ if (event.kind === 'arrival-gap' || event.kind === 'audio-dropout') {
182
+ const ms = event['ms'];
183
+ if (typeof ms !== 'number' || !Number.isFinite(ms))
184
+ return undefined;
185
+ const starvation = starvationsOf(event.kind === 'arrival-gap' ? gaps : dropouts, scope);
186
+ starvation.count++;
187
+ starvation.totalMs += Math.round(ms);
188
+ starvation.pending.push(Math.round(ms));
189
+ if (starvation.pending.length > MAX_PENDING)
190
+ starvation.pending.shift();
191
+ return undefined;
192
+ }
193
+ if (event.kind === 'want') {
194
+ const key = `${scope}\u0000${String(event['want'])}`;
195
+ const what = event['what'];
196
+ if (what === 'subscribed' && typeof event['namespace'] === 'string' && typeof event['track'] === 'string') {
197
+ const cid = cidOf(event['namespace'], event['track']);
198
+ wantCids.set(key, cid);
199
+ failed.delete(cid);
200
+ }
201
+ else if (what === 'switched' && typeof event['to'] === 'string') {
202
+ const cid = event['to'].slice(-MAX_CID);
203
+ wantCids.set(key, cid);
204
+ failed.delete(cid);
205
+ }
206
+ else if (what === 'first-object' && mediaStartMs === undefined && typeof event['firstObjectMs'] === 'number') {
207
+ mediaStartMs = Math.round(event['firstObjectMs']);
208
+ }
209
+ else if (what === 'error') {
210
+ const cid = wantCids.get(key);
211
+ const code = typeof event['code'] === 'string' ? event['code'] : 'error';
212
+ if (cid === undefined) {
213
+ linkError(code);
214
+ return { type: 'e' };
215
+ }
216
+ let list = wantErrors.get(cid);
217
+ if (!list) {
218
+ list = [];
219
+ wantErrors.set(cid, list);
220
+ }
221
+ pushCapped(list, code);
222
+ failed.add(cid);
223
+ return { type: 'e', cid };
224
+ }
225
+ return undefined;
226
+ }
227
+ if (event.kind === 'link' && typeof event['error'] === 'string') {
228
+ linkError(typeof event['code'] === 'string' ? event['code'] : 'error');
229
+ return { type: 'e' };
230
+ }
231
+ if (event.kind === 'page' && (event['what'] === 'hidden' || event['what'] === 'visible'))
232
+ return { type: 'b' };
233
+ return undefined;
234
+ };
235
+ // What the recorder already holds counts: starvations since the session's start, errors not yet reported.
236
+ for (const event of diagnostics.events())
237
+ consume(event);
238
+ /** Look at the recorder now: the remote tracks, their byte counts and play states. Returns the snapshot. */
239
+ const look = () => {
240
+ const now = performance.now();
241
+ const snapshot = diagnostics.snapshot();
242
+ const seen = new Set();
243
+ const changed = [];
244
+ for (const [name, value] of Object.entries(snapshot)) {
245
+ if (name !== 'receive' && !name.endsWith('.receive'))
246
+ continue;
247
+ if (typeof value !== 'object' || value === null)
248
+ continue;
249
+ const receive = value;
250
+ const { namespace, track: trackName } = receive;
251
+ if (typeof namespace !== 'string' || typeof trackName !== 'string')
252
+ continue;
253
+ const scope = name === 'receive' ? '' : name.slice(0, -'.receive'.length);
254
+ const audioValue = snapshot[scope === '' ? 'audio' : `${scope}.audio`];
255
+ const audio = typeof audioValue === 'object' && audioValue !== null ? audioValue : undefined;
256
+ const objects = finite(receive['objects']) ?? 0;
257
+ const bytes = finite(receive['bytes']) ?? 0;
258
+ const cid = cidOf(namespace, trackName);
259
+ let state = tracks.get(scope);
260
+ if (!state || state.cid !== cid || bytes < (state.samples.at(-1)?.bytes ?? 0)) {
261
+ // A move or a new reader under the same scope: the codes the scope's track still holds go with it.
262
+ state = {
263
+ cid,
264
+ namespace,
265
+ track: trackName,
266
+ type: 'v',
267
+ scope,
268
+ samples: [],
269
+ objects,
270
+ linkCodes: state ? state.linkCodes : [],
271
+ sta: undefined,
272
+ receive,
273
+ audio,
274
+ };
275
+ tracks.set(scope, state);
276
+ }
277
+ seen.add(scope);
278
+ state.type = audio ? 'a' : 'v';
279
+ state.receive = receive;
280
+ state.audio = audio;
281
+ state.objects = objects;
282
+ // Only samples inside the window: after a stretch without demand, unlooked at, the rate starts again.
283
+ while (state.samples.length > 0 && state.samples[0].at < now - RATE_WINDOW_MS) {
284
+ state.samples.shift();
285
+ }
286
+ state.samples.push({ at: now, bytes });
287
+ const sta = failed.has(cid) ? 'f' : playState(state);
288
+ if (sta !== state.sta && (state.sta !== undefined || looked))
289
+ changed.push(state);
290
+ state.sta = sta;
291
+ }
292
+ for (const scope of [...tracks.keys()])
293
+ if (!seen.has(scope))
294
+ tracks.delete(scope);
295
+ // The connection's codes from while there was no track go to the tracks found now, once.
296
+ if (linkErrors.length > 0 && tracks.size > 0) {
297
+ for (const state of tracks.values())
298
+ for (const code of linkErrors)
299
+ pushCapped(state.linkCodes, code);
300
+ linkErrors = [];
301
+ }
302
+ looked = true;
303
+ return { snapshot, changed };
304
+ };
305
+ /** The byte rate of a track over the window, in kilobits per second, or `undefined` before a second of samples. */
306
+ const kbps = (state) => {
307
+ const first = state.samples[0];
308
+ const last = state.samples.at(-1);
309
+ if (!first || !last || last.at - first.at < RATE_MIN_SPAN_MS)
310
+ return undefined;
311
+ // Bytes per millisecond, times 8, is kilobits per second.
312
+ return ((last.bytes - first.bytes) * 8) / (last.at - first.at);
313
+ };
314
+ /**
315
+ * The record for one track; or, when `state` is absent, for the session, or for `cid` alone (a want that failed and
316
+ * whose reader is gone).
317
+ */
318
+ const recordFor = (T, type, state, snapshot, throughput, cid) => {
319
+ const derived = { st: 'll', sid };
320
+ if (throughput !== undefined)
321
+ derived['mtp'] = throughput;
322
+ if (backgrounded(snapshot))
323
+ derived['bg'] = true;
324
+ if (mediaStartMs !== undefined && !msdSent)
325
+ derived['msd'] = mediaStartMs;
326
+ const codes = state ? [...state.linkCodes] : [...linkErrors];
327
+ if (state) {
328
+ derived['cid'] = state.cid;
329
+ const token = state.type;
330
+ if (state.sta !== undefined)
331
+ derived['sta'] = state.sta;
332
+ const rate = kbps(state);
333
+ // Nothing arrived in the window says nothing of the encoded bitrate.
334
+ if (rate !== undefined && rate > 0)
335
+ derived['br'] = `(${Math.round(rate)};${token})`;
336
+ if (state.audio) {
337
+ const buffered = finite(state.audio['bufferedUs']);
338
+ if (buffered !== undefined)
339
+ derived['bl'] = `(${hundreds(buffered / 1000)};a)`;
340
+ const target = finite(state.audio['jitterTargetUs']);
341
+ if (target !== undefined)
342
+ derived['tbl'] = `(${hundreds(target / 1000)};a)`;
343
+ }
344
+ else {
345
+ const sequencer = state.receive['sequencer'];
346
+ if (typeof sequencer === 'object' && sequencer !== null) {
347
+ const { late, behind } = sequencer;
348
+ derived['dfa'] = (finite(late) ?? 0) + (finite(behind) ?? 0);
349
+ }
350
+ }
351
+ const starvation = (token === 'a' ? dropouts : gaps).get(state.scope);
352
+ if (starvation && starvation.count > 0) {
353
+ derived['bsa'] = `(${starvation.count};${token})`;
354
+ derived['bsda'] = `(${starvation.totalMs};${token})`;
355
+ if (starvation.pending.length > 0) {
356
+ derived['bsd'] = `(${starvation.pending.map((ms) => `${ms};${token}`).join(' ')})`;
357
+ }
358
+ }
359
+ if (state.sta === 'r' || (starvation?.pending.length ?? 0) > 0)
360
+ derived['bs'] = true;
361
+ for (const code of wantErrors.get(state.cid) ?? [])
362
+ if (!codes.includes(code))
363
+ codes.push(code);
364
+ }
365
+ else if (cid !== undefined) {
366
+ derived['cid'] = cid;
367
+ if (failed.has(cid))
368
+ derived['sta'] = 'f';
369
+ for (const code of wantErrors.get(cid) ?? [])
370
+ if (!codes.includes(code))
371
+ codes.push(code);
372
+ }
373
+ if (codes.length > 0)
374
+ derived['ec'] = `(${codes.map(sfString).join(' ')})`;
375
+ const data = {};
376
+ for (const [key, value] of Object.entries(derived))
377
+ if (enabled.has(key))
378
+ data[key] = value;
379
+ if (state && appKeys) {
380
+ let added;
381
+ try {
382
+ const { cid: trackCid, namespace, track: trackName, type: token, scope } = state;
383
+ added = appKeys({ cid: trackCid, namespace, track: trackName, type: token, scope, event: type });
384
+ }
385
+ catch (error) {
386
+ // biome-ignore lint/suspicious/noConsole: the application's callback failed and has no caller to report to
387
+ console.error(new Error('A CMCD keys callback threw; the record goes without its keys', { cause: error }));
388
+ }
389
+ if (typeof added === 'object' && added !== null) {
390
+ for (const [key, value] of Object.entries(added)) {
391
+ if (SDK_KEYS.has(key) || !enabled.has(key))
392
+ continue;
393
+ if (value === undefined)
394
+ delete data[key];
395
+ else if (appValue(key, value))
396
+ data[key] = value;
397
+ }
398
+ }
399
+ }
400
+ // CTA-5004-B: `e` on every event report, `sta` with `ps`, `ec` with `e`; the draft: `v` on every record.
401
+ data['e'] = type;
402
+ data['v'] = 2;
403
+ // An application's own value stands; one it left out is put back, since CTA-5004-B requires it.
404
+ if (type === 'ps' && data['sta'] === undefined && derived['sta'] !== undefined)
405
+ data['sta'] = derived['sta'];
406
+ if (type === 'e' && data['ec'] === undefined && derived['ec'] !== undefined)
407
+ data['ec'] = derived['ec'];
408
+ if (enabled.has('sn'))
409
+ data['sn'] = sn;
410
+ sn++;
411
+ // Once per session ID: on this record, and no other.
412
+ if ('msd' in data)
413
+ msdSent = true;
414
+ return { T, data: sorted(data) };
415
+ };
416
+ const write = (records) => {
417
+ // The writer reports what became of the group; a closed writer's rejection only means publishing has stopped.
418
+ writer.write({ payload: encodeJSON(records), key: true }).catch(() => { });
419
+ };
420
+ const flush = () => {
421
+ if (batchTimer !== undefined)
422
+ clearTimeout(batchTimer);
423
+ batchTimer = undefined;
424
+ if (batch.length > 0 && !closed && track.hasDemand)
425
+ write(batch);
426
+ batch = [];
427
+ };
428
+ const emit = (records) => {
429
+ if (batchCount === undefined && batchIntervalMs === undefined) {
430
+ for (const record of records)
431
+ write([record]);
432
+ return;
433
+ }
434
+ batch.push(...records);
435
+ let wrote = false;
436
+ if (batchCount !== undefined) {
437
+ while (batch.length >= batchCount) {
438
+ write(batch.splice(0, batchCount));
439
+ wrote = true;
440
+ }
441
+ }
442
+ // A group written ends its interval: what is left starts a group of its own, timed from now.
443
+ if (wrote || batch.length === 0) {
444
+ if (batchTimer !== undefined)
445
+ clearTimeout(batchTimer);
446
+ batchTimer = undefined;
447
+ }
448
+ if (batch.length > 0 && batchIntervalMs !== undefined && batchTimer === undefined) {
449
+ batchTimer = setTimeout(flush, batchIntervalMs);
450
+ }
451
+ };
452
+ /** Records for a trigger: one per remote track (or for `only`), or one for the session while there is none. */
453
+ const trigger = (type, only, seen) => {
454
+ if (closed || !track.hasDemand || !events.has(type))
455
+ return;
456
+ const view = seen ?? look();
457
+ const { snapshot } = view;
458
+ const T = Date.now();
459
+ const all = [...tracks.values()];
460
+ const chosen = only?.states ?? (only?.cid === undefined ? all : all.filter((state) => state.cid === only.cid));
461
+ // Measured throughput: what arrived, summed by type over every remote track that has a rate yet.
462
+ const sums = new Map();
463
+ for (const state of all) {
464
+ const rate = kbps(state);
465
+ if (rate !== undefined)
466
+ sums.set(state.type, (sums.get(state.type) ?? 0) + rate);
467
+ }
468
+ const measured = ['v', 'a'].filter((token) => sums.has(token));
469
+ const throughput = measured.length > 0
470
+ ? `(${measured.map((token) => `${hundreds(sums.get(token) ?? 0)};${token}`).join(' ')})`
471
+ : undefined;
472
+ let records;
473
+ if (chosen.length > 0)
474
+ records = chosen.map((state) => recordFor(T, type, state, snapshot, throughput));
475
+ else if (only?.states)
476
+ records = [];
477
+ else
478
+ records = [recordFor(T, type, undefined, snapshot, throughput, only?.cid)];
479
+ if (records.length === 0)
480
+ return;
481
+ // Reported once: starvation durations and errors for the tracks that had a record, the connection's for all.
482
+ for (const state of chosen) {
483
+ (state.type === 'a' ? dropouts : gaps).get(state.scope)?.pending.splice(0);
484
+ wantErrors.delete(state.cid);
485
+ }
486
+ if (only?.cid !== undefined)
487
+ wantErrors.delete(only.cid);
488
+ for (const state of chosen)
489
+ state.linkCodes = [];
490
+ // Each track holds the connection's codes itself; these went in the record without one.
491
+ if (chosen.length === 0)
492
+ linkErrors = [];
493
+ emit(records);
494
+ // A change this trigger's own look saw first is still a ps, after its records.
495
+ if (type !== 'ps' && !seen && view.changed.length > 0)
496
+ trigger('ps', { states: view.changed }, view);
497
+ };
498
+ const unlisten = diagnostics.listen((event) => {
499
+ const made = consume(event);
500
+ if (!made || closed)
501
+ return;
502
+ // Out of the recorder's call: a record reads every section, and an event may be recorded from inside one.
503
+ queueMicrotask(() => trigger(made.type, made.cid === undefined ? undefined : { cid: made.cid }));
504
+ });
505
+ const changes = track.demandChanges();
506
+ const watching = (async () => {
507
+ for await (const demanded of changes) {
508
+ if (!demanded) {
509
+ batch = [];
510
+ if (batchTimer !== undefined)
511
+ clearTimeout(batchTimer);
512
+ batchTimer = undefined;
513
+ }
514
+ }
515
+ })().catch(() => { });
516
+ const looking = setInterval(() => {
517
+ if (closed || !track.hasDemand)
518
+ return;
519
+ const seen = look();
520
+ if (seen.changed.length > 0)
521
+ trigger('ps', { states: seen.changed }, seen);
522
+ }, LOOK_MS);
523
+ const interval = setInterval(() => trigger('t'), intervalMs);
524
+ return {
525
+ async close() {
526
+ if (closed)
527
+ return;
528
+ closed = true;
529
+ clearInterval(looking);
530
+ clearInterval(interval);
531
+ if (batchTimer !== undefined)
532
+ clearTimeout(batchTimer);
533
+ unlisten();
534
+ await changes.return?.();
535
+ await watching;
536
+ await writer.close();
537
+ track.close();
538
+ },
539
+ };
540
+ }
541
+ /** A track's play state now, from its audio input when it has one, else from its reader's arrivals. */
542
+ function playState(state) {
543
+ if (state.audio) {
544
+ if (state.audio['playing'] === true)
545
+ return 'p';
546
+ return (finite(state.audio['playStarts']) ?? 0) > 0 ? 'r' : 's';
547
+ }
548
+ if (state.objects === 0)
549
+ return 's';
550
+ const since = finite(state.receive['sinceObjectMs']);
551
+ return since !== undefined && since > VIDEO_STALL_MS ? 'r' : 'p';
552
+ }
553
+ /** Whether a `page` section says the page is hidden. */
554
+ function backgrounded(snapshot) {
555
+ for (const [name, value] of Object.entries(snapshot)) {
556
+ if (name !== 'page' && !name.endsWith('.page'))
557
+ continue;
558
+ if (typeof value === 'object' && value !== null && value.visibility === 'hidden') {
559
+ return true;
560
+ }
561
+ }
562
+ return false;
563
+ }
564
+ /** A content ID: the namespace and the track joined with `/`, its last 128 characters when longer. */
565
+ function cidOf(namespace, track) {
566
+ return `${namespace}/${track}`.slice(-MAX_CID);
567
+ }
568
+ function finite(value) {
569
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
570
+ }
571
+ /** Rounded to the nearest 100, as CTA-5004-B asks of `bl`, `tbl` and `mtp`. */
572
+ function hundreds(value) {
573
+ return Math.round(value / 100) * 100;
574
+ }
575
+ /** A Structured Field String (RFC 8941 §3.3.3): quoted, with `"` and `\` escaped. */
576
+ function sfString(value) {
577
+ return `"${value.replace(/[\\"]/g, (match) => `\\${match}`)}"`;
578
+ }
579
+ function sorted(data) {
580
+ return Object.fromEntries(Object.entries(data).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
581
+ }
582
+ /** Whether an application's value may go in a record under `key`. */
583
+ function appValue(key, value) {
584
+ if (BANNED_KEYS.has(key))
585
+ return false;
586
+ if (!ALLOWED_KEYS.has(key))
587
+ return key.includes('-') && typeof value === 'string' && value.length <= 64;
588
+ if (typeof value === 'number')
589
+ return Number.isFinite(value);
590
+ return typeof value === 'string' || typeof value === 'boolean';
591
+ }
592
+ function eventsOption(value) {
593
+ if (value === undefined)
594
+ return new Set(EVENT_TYPES);
595
+ if (!Array.isArray(value) || value.length === 0)
596
+ throw new TypeError('events must be a non-empty array');
597
+ for (const type of value) {
598
+ if (!EVENT_TYPES.includes(type)) {
599
+ throw new RangeError(`events must be among ${EVENT_TYPES.join(', ')}: the SDK cannot see ${String(type)}`);
600
+ }
601
+ }
602
+ return new Set(value);
603
+ }
604
+ function intervalOption(value) {
605
+ if (value === undefined)
606
+ return DEFAULT_INTERVAL_MS;
607
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > 2_147_483_647) {
608
+ throw new RangeError('intervalMs must be a positive number of milliseconds, at most 2147483647');
609
+ }
610
+ return Math.max(MIN_INTERVAL_MS, Math.round(value));
611
+ }
612
+ function keysOption(value) {
613
+ if (value === undefined)
614
+ return new Set(DEFAULT_KEYS);
615
+ if (!Array.isArray(value) || value.some((key) => typeof key !== 'string')) {
616
+ throw new TypeError('enabledKeys must be an array of strings');
617
+ }
618
+ const banned = value.filter((key) => BANNED_KEYS.has(key));
619
+ if (banned.length > 0)
620
+ throw new RangeError(`enabledKeys has keys the draft bans: ${banned.join(', ')}`);
621
+ return new Set(value);
622
+ }
623
+ function positiveInteger(value, name) {
624
+ if (value === undefined)
625
+ return undefined;
626
+ if (!Number.isSafeInteger(value) || value < 1 || value > 2_147_483_647) {
627
+ throw new RangeError(`${name} must be an integer from 1 to 2147483647`);
628
+ }
629
+ return value;
630
+ }
631
+ //# sourceMappingURL=cmcd.js.map