@caprid/moq-media 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +20 -0
  2. package/NOTICE +6 -0
  3. package/README.md +187 -2
  4. package/UPSTREAM.json +19 -0
  5. package/dist/audio-player.d.ts +206 -0
  6. package/dist/audio-player.d.ts.map +1 -0
  7. package/dist/audio-player.js +480 -0
  8. package/dist/audio-player.js.map +1 -0
  9. package/dist/audio-worklet.d.ts +64 -0
  10. package/dist/audio-worklet.d.ts.map +1 -0
  11. package/dist/audio-worklet.js +355 -0
  12. package/dist/audio-worklet.js.map +1 -0
  13. package/dist/catalog.d.ts +141 -0
  14. package/dist/catalog.d.ts.map +1 -0
  15. package/dist/catalog.js +174 -0
  16. package/dist/catalog.js.map +1 -0
  17. package/dist/clock.d.ts +178 -0
  18. package/dist/clock.d.ts.map +1 -0
  19. package/dist/clock.js +190 -0
  20. package/dist/clock.js.map +1 -0
  21. package/dist/echo-loopback.d.ts +38 -0
  22. package/dist/echo-loopback.d.ts.map +1 -0
  23. package/dist/echo-loopback.js +100 -0
  24. package/dist/echo-loopback.js.map +1 -0
  25. package/dist/h264.d.ts +4 -0
  26. package/dist/h264.d.ts.map +1 -0
  27. package/dist/h264.js +8 -0
  28. package/dist/h264.js.map +1 -0
  29. package/dist/index.d.ts +15 -0
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +15 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/interrupt.d.ts +35 -0
  34. package/dist/interrupt.d.ts.map +1 -0
  35. package/dist/interrupt.js +44 -0
  36. package/dist/interrupt.js.map +1 -0
  37. package/dist/loc.d.ts +55 -0
  38. package/dist/loc.d.ts.map +1 -0
  39. package/dist/loc.js +74 -0
  40. package/dist/loc.js.map +1 -0
  41. package/dist/parse-catalog.d.ts +81 -0
  42. package/dist/parse-catalog.d.ts.map +1 -0
  43. package/dist/parse-catalog.js +134 -0
  44. package/dist/parse-catalog.js.map +1 -0
  45. package/dist/render-clock.d.ts +38 -0
  46. package/dist/render-clock.d.ts.map +1 -0
  47. package/dist/render-clock.js +40 -0
  48. package/dist/render-clock.js.map +1 -0
  49. package/dist/sequencer.d.ts +130 -0
  50. package/dist/sequencer.d.ts.map +1 -0
  51. package/dist/sequencer.js +599 -0
  52. package/dist/sequencer.js.map +1 -0
  53. package/dist/source.d.ts +21 -0
  54. package/dist/source.d.ts.map +1 -0
  55. package/dist/source.js +54 -0
  56. package/dist/source.js.map +1 -0
  57. package/dist/timeline.d.ts +69 -0
  58. package/dist/timeline.d.ts.map +1 -0
  59. package/dist/timeline.js +83 -0
  60. package/dist/timeline.js.map +1 -0
  61. package/dist/transcript.d.ts +84 -0
  62. package/dist/transcript.d.ts.map +1 -0
  63. package/dist/transcript.js +151 -0
  64. package/dist/transcript.js.map +1 -0
  65. package/dist/webcodecs.d.ts +32 -0
  66. package/dist/webcodecs.d.ts.map +1 -0
  67. package/dist/webcodecs.js +79 -0
  68. package/dist/webcodecs.js.map +1 -0
  69. package/package.json +34 -3
@@ -0,0 +1,174 @@
1
+ /** Independent LOC/MSF catalogs, adapted from Video.js build-catalog.ts. */
2
+ import { avcCodecString } from './h264.js';
3
+ import { AUDIO_TRACK, MEDIA_TIMELINE_TRACK, VIDEO_TRACK } from './loc.js';
4
+ /** Version emitted — the newest version `parseMsfCatalog` accepts. */
5
+ export const MSF_CATALOG_VERSION = 'draft-01';
6
+ function pruneUndefined(value) {
7
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
8
+ }
9
+ /** Inverse of `parseMsfCatalog`'s `base64ToBytes`. */
10
+ function bytesToBase64(bytes) {
11
+ let binary = '';
12
+ for (const byte of bytes)
13
+ binary += String.fromCharCode(byte);
14
+ return btoa(binary);
15
+ }
16
+ /**
17
+ * Register a track's init data and return the `initRef` naming it. Ids derive from the track name, which is unique
18
+ * within the catalog.
19
+ */
20
+ function registerInitData(entries, name, initData) {
21
+ if (initData === undefined || initData.length === 0)
22
+ return {};
23
+ const id = `${name}-init`;
24
+ entries.push({ id, type: 'inline', data: bytesToBase64(initData) });
25
+ return { initRef: id };
26
+ }
27
+ /**
28
+ * The render group (msf-01 §5.2.11) a video or audio entry joins unless it names another: tracks stamped on one
29
+ * broadcast timeline and meant to play together. The builder sets no target latency or buffer, which §5.2.8 and
30
+ * §5.2.9 require to be identical across a render group.
31
+ */
32
+ const MEDIA_RENDER_GROUP = 1;
33
+ const isGroupNumber = (value) => value === undefined || (Number.isSafeInteger(value) && value >= 0);
34
+ /**
35
+ * Build the publisher's independent MSF catalog JSON for a live broadcast.
36
+ *
37
+ * The catalog leaves `isComplete` out: msf-01 §5.1.3 forbids it while false, and once present it can never be
38
+ * removed. End a broadcast with {@link buildMsfEndCatalog}.
39
+ *
40
+ * Namespaces are emitted explicitly per track as the slash-joined string form `parseMsfCatalog` splits back into
41
+ * tuple fields — the catalog dialect's encoding, which msf-01 leaves open, so the pair stays self-consistent whatever
42
+ * the drafts settle on.
43
+ */
44
+ export function buildMsfCatalog(input) {
45
+ if (input.namespace.length === 0 || input.namespace.some((field) => !field || field.includes('/')))
46
+ throw new Error('catalog namespace fields must be non-empty and contain no slash');
47
+ const media = [
48
+ ...(input.video ? [{ ...input.video, role: 'video' }] : []),
49
+ ...(input.audio ? [{ ...input.audio, role: 'audio' }] : []),
50
+ ...(input.media ?? []),
51
+ ].map((track) => track.role === 'video'
52
+ ? { ...track, name: track.name ?? VIDEO_TRACK }
53
+ : { codec: 'opus', samplerate: 48000, channelConfig: '2', ...track, name: track.name ?? AUDIO_TRACK });
54
+ const timeline = input.mediaTimeline
55
+ ? { ...input.mediaTimeline, name: input.mediaTimeline.name ?? MEDIA_TIMELINE_TRACK }
56
+ : undefined;
57
+ const names = [...media, timeline, ...(input.data ?? [])]
58
+ .filter((track) => track !== undefined)
59
+ .map((track) => track.name);
60
+ if (names.some((name) => !name) || new Set(names).size !== names.length)
61
+ throw new Error('catalog track names must be non-empty and unique');
62
+ const mediaRoles = new Set(['video', 'audio', 'caption', 'subtitle', 'audiodescription', 'signlanguage']);
63
+ if (input.data?.some((track) => track.role !== undefined && mediaRoles.has(track.role)))
64
+ throw new Error('data tracks must not use media roles');
65
+ if (media.some((track) => track.role !== 'video' && track.role !== 'audio'))
66
+ throw new Error('media tracks must have the role video or audio');
67
+ if (media.some((track) => !isGroupNumber(track.renderGroup) || !isGroupNumber(track.altGroup)))
68
+ throw new Error('render and alternate groups must be non-negative safe integers');
69
+ const alternates = new Map();
70
+ for (const { altGroup, role, renderGroup = MEDIA_RENDER_GROUP } of media) {
71
+ if (altGroup === undefined)
72
+ continue;
73
+ const first = alternates.get(altGroup) ?? { role, renderGroup };
74
+ if (first.role !== role || first.renderGroup !== renderGroup)
75
+ throw new Error('alternate group members must share a role and a render group');
76
+ alternates.set(altGroup, first);
77
+ }
78
+ const mediaNames = media.map((track) => track.name);
79
+ const defaultDepends = ['video', 'audio']
80
+ .map((role) => media.find((track) => track.role === role)?.name)
81
+ .filter((name) => name !== undefined);
82
+ const depends = timeline ? [...(timeline.depends ?? defaultDepends)] : [];
83
+ if (timeline &&
84
+ (depends.length === 0 || new Set(depends).size !== depends.length || depends.some((n) => !mediaNames.includes(n))))
85
+ throw new Error('media timeline depends must name distinct video or audio tracks of this catalog');
86
+ const namespace = input.namespace.join('/');
87
+ const shared = { namespace, packaging: 'loc', isLive: true };
88
+ const initDataList = [];
89
+ const tracks = [];
90
+ for (const track of media) {
91
+ const groups = { renderGroup: track.renderGroup ?? MEDIA_RENDER_GROUP, altGroup: track.altGroup };
92
+ if (track.role === 'video') {
93
+ const h264 = /^(avc1|avc3)(\.|$)/.test(track.codec);
94
+ if (h264 && (track.initData === undefined || track.initData.length === 0))
95
+ continue;
96
+ const codec = h264 && track.initData ? track.codec.slice(0, 4) + avcCodecString(track.initData).slice(4) : track.codec;
97
+ tracks.push(pruneUndefined({
98
+ ...shared,
99
+ ...registerInitData(initDataList, track.name, track.initData),
100
+ name: track.name,
101
+ role: 'video',
102
+ ...groups,
103
+ codec,
104
+ width: track.width,
105
+ height: track.height,
106
+ framerate: track.framerate,
107
+ bitrate: track.bitrate,
108
+ }));
109
+ }
110
+ else {
111
+ tracks.push(pruneUndefined({
112
+ ...shared,
113
+ ...registerInitData(initDataList, track.name, track.initData),
114
+ name: track.name,
115
+ role: 'audio',
116
+ ...groups,
117
+ codec: track.codec,
118
+ samplerate: track.codec === 'opus' ? 48000 : track.samplerate,
119
+ channelConfig: track.channelConfig,
120
+ bitrate: track.bitrate,
121
+ }));
122
+ }
123
+ }
124
+ const listed = new Set(tracks.map(({ name }) => name));
125
+ const indexed = depends.filter((name) => listed.has(name));
126
+ if (timeline && indexed.length > 0) {
127
+ tracks.push({
128
+ ...shared,
129
+ packaging: 'mediatimeline',
130
+ name: timeline.name,
131
+ role: 'mediatimeline',
132
+ mimetype: 'application/json',
133
+ depends: indexed,
134
+ });
135
+ }
136
+ // Data tracks carry no media fields, so the player treats them as non-renderable.
137
+ for (const data of input.data ?? []) {
138
+ tracks.push(pruneUndefined({
139
+ ...shared,
140
+ name: data.name,
141
+ role: data.role,
142
+ }));
143
+ }
144
+ return encodeCatalog({
145
+ version: MSF_CATALOG_VERSION,
146
+ generatedAt: input.generatedAt,
147
+ tracks,
148
+ initDataList: initDataList.length > 0 ? initDataList : undefined,
149
+ });
150
+ }
151
+ /**
152
+ * Build the catalog that ends a broadcast (msf-01 §11.3): `isComplete: true` and no tracks.
153
+ *
154
+ * It commits that no track will be added and no content published, so send it only for a broadcast that ends on
155
+ * purpose, once every media track has ended (closing a track sends PUBLISH_DONE Track Ended), and never on a crash
156
+ * or lost connection.
157
+ */
158
+ export function buildMsfEndCatalog(input = {}) {
159
+ return encodeCatalog({ version: MSF_CATALOG_VERSION, generatedAt: input.generatedAt, isComplete: true, tracks: [] });
160
+ }
161
+ function encodeCatalog(catalog) {
162
+ return new TextEncoder().encode(JSON.stringify(pruneUndefined(catalog), (_key, value) => {
163
+ if (typeof value === 'string' && /[\uD800-\uDFFF]/u.test(value))
164
+ throw new Error('catalog strings must be valid Unicode');
165
+ if (typeof value === 'number') {
166
+ if (!Number.isFinite(value))
167
+ throw new Error('catalog numbers must be finite');
168
+ if (Number.isInteger(value) && !Number.isSafeInteger(value))
169
+ throw new Error('catalog integers must be safe integers');
170
+ }
171
+ return value;
172
+ }));
173
+ }
174
+ //# sourceMappingURL=catalog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAC1E,sEAAsE;AACtE,MAAM,CAAC,MAAM,mBAAmB,GAAG,UAAU,CAAC;AA4H9C,SAAS,cAAc,CAAC,KAA8B;IACpD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;AAC9F,CAAC;AAED,sDAAsD;AACtD,SAAS,aAAa,CAAC,KAAiB;IACtC,IAAI,MAAM,GAAG,EAAE,CAAC;IAEhB,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAE9D,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC;AASD;;;GAGG;AACH,SAAS,gBAAgB,CAAC,OAA2B,EAAE,IAAY,EAAE,QAAgC;IACnG,IAAI,QAAQ,KAAK,SAAS,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAE/D,MAAM,EAAE,GAAG,GAAG,IAAI,OAAO,CAAC;IAE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,CAAC,SAAS,CAAC,cAAc,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,KAAc,EAAE,EAAE;QAC/D,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC;YAC7D,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;QAC3D,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;YAC/E,IAAI,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC;gBACzD,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;QAC9D,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC,CACH,CAAC;AACJ,CAAC"}
@@ -0,0 +1,178 @@
1
+ /** A monotonic time source in microseconds. The default is `performance.now() * 1000`. */
2
+ export type MicrosecondClock = () => number;
3
+ /** Options for {@link createBroadcastClock}. */
4
+ export interface BroadcastClockOptions {
5
+ /** The time source, in microseconds. Defaults to `performance.now()`. */
6
+ now?: MicrosecondClock;
7
+ /**
8
+ * The moment on the source clock that is pinned to the system clock, in integer microseconds. Defaults to the
9
+ * source's time now, rounded to whole microseconds.
10
+ */
11
+ originUs?: number;
12
+ /**
13
+ * The origin as integer Unix-epoch microseconds. Defaults to `Date.now()` at creation less the
14
+ * source time elapsed since the origin, read once. `Date.now()` rather than `performance.timeOrigin +
15
+ * performance.now()`, which can fall behind the system clock by however long the page has slept.
16
+ */
17
+ originEpochUs?: number;
18
+ }
19
+ /** Options for {@link BroadcastClock.sampleTimeline}. */
20
+ export interface SampleTimelineOptions {
21
+ /** The broadcast time of sample 0, in integer Unix-epoch microseconds. Defaults to the clock's `now()`. */
22
+ firstSampleUs?: number;
23
+ }
24
+ /** Maps an audio sample counter onto the broadcast timeline. */
25
+ export interface SampleTimeline {
26
+ /** Samples per second, per channel. */
27
+ readonly sampleRate: number;
28
+ /** The broadcast time of sample 0. */
29
+ readonly firstSampleUs: number;
30
+ /** The broadcast time of the sample at this index: the first sample's time plus whole elapsed microseconds. */
31
+ timestampUs(sampleIndex: number): number;
32
+ }
33
+ /** Options for {@link BroadcastClock.sourceTimeline}. */
34
+ export interface SourceTimelineOptions {
35
+ /** How far a calibration may disagree with the current anchor before it replaces it, in µs. Default 5,000. */
36
+ toleranceUs?: number;
37
+ /** The capture device's input delay, subtracted from every timestamp, in integer µs. Default 0. */
38
+ captureLatencyUs?: number;
39
+ }
40
+ /**
41
+ * Maps timestamps from a clock with its own origin and rate onto the broadcast timeline: an `AudioContext`'s time
42
+ * (works in every browser), or Chromium's `MediaStreamTrackProcessor` timestamps, which count from the system's
43
+ * monotonic zero, not from `performance.now()`'s.
44
+ */
45
+ export interface SourceTimeline {
46
+ /** The source time of the current anchor; `undefined` until the first calibration or timestamp. */
47
+ readonly anchorSourceUs: number | undefined;
48
+ /**
49
+ * How long the capture device holds a sample before the source sees it, in integer microseconds, subtracted from
50
+ * every timestamp so it stays the capture time. No browser API reports it: set it from a known device latency, and
51
+ * again when the device changes. It does not affect calibration.
52
+ */
53
+ captureLatencyUs: number;
54
+ /**
55
+ * Record that source time `sourceUs` happened at `atUs` on the broadcast clock's own source (default: now), for
56
+ * example an `AudioContext` time and the `performance.now()` time it was rendered at, both in microseconds. The pair
57
+ * becomes the anchor when there is none, or when the current anchor predicts it more than `toleranceUs` off: the
58
+ * source drifted, or jumped, as an `AudioContext` does when it is replaced. Returns whether the anchor changed.
59
+ */
60
+ calibrate(sourceUs: number, atUs?: number): boolean;
61
+ /**
62
+ * The broadcast time of this source timestamp: the anchor's broadcast time plus the source's own elapsed time,
63
+ * rounded to whole microseconds, less the capture latency. Without an anchor, the first call anchors this timestamp
64
+ * at the clock's `now()`.
65
+ */
66
+ timestampUs(sourceUs: number): number;
67
+ }
68
+ /**
69
+ * A publisher's single clock: every track in the broadcast is stamped from it, in microseconds since the Unix epoch.
70
+ * One moment on a monotonic source is pinned to the system clock, and the timeline advances at the source's rate.
71
+ */
72
+ export interface BroadcastClock {
73
+ /** The pinned moment, on the source clock. */
74
+ readonly originUs: number;
75
+ /** The pinned moment as microseconds since the Unix epoch. */
76
+ readonly originEpochUs: number;
77
+ /** The timeline now: Unix-epoch microseconds. */
78
+ now(): number;
79
+ /**
80
+ * Map a timestamp on this clock's own source, such as `performance.now()` microseconds taken at capture, to the
81
+ * timeline: `originEpochUs + sourceUs − originUs`. For a capture clock with another origin, use
82
+ * {@link BroadcastClock.sourceTimeline}.
83
+ */
84
+ fromSourceUs(sourceUs: number): number;
85
+ /** Map a clock with its own origin and rate, kept on the broadcast timeline by calibration. */
86
+ sourceTimeline(options?: SourceTimelineOptions): SourceTimeline;
87
+ /**
88
+ * Anchor a sample counter that starts at zero. The device clock that drives it drifts against the source, so
89
+ * re-anchor with a fresh timeline when the two disagree by more than a frame.
90
+ */
91
+ sampleTimeline(sampleRate: number, options?: SampleTimelineOptions): SampleTimeline;
92
+ }
93
+ /** Pin a monotonic source to the system clock and map capture timestamps and sample counters onto the epoch. */
94
+ export declare function createBroadcastClock(options?: BroadcastClockOptions): BroadcastClock;
95
+ /**
96
+ * The target latency for a broadcast with no video: pass it as `targetLatencyUs`, since the 2 s default waits for
97
+ * keyframe intervals an audio-only track never reports. It covers the audio player's 400 ms jitter-buffer ceiling plus
98
+ * a wired output delay, and a frame sequencer resyncs after half a second of nothing on time instead of two.
99
+ */
100
+ export declare const AUDIO_ONLY_TARGET_LATENCY_US = 500000;
101
+ /** Options for {@link createPlayoutClock}. Durations are microseconds. */
102
+ export interface PlayoutClockOptions {
103
+ /** The time source, in microseconds. Defaults to `performance.now()`. */
104
+ now?: MicrosecondClock;
105
+ /** A frame later than this is dropped. Default 40,000 (EBU R37's audio-early limit). */
106
+ lateDropUs?: number;
107
+ /** The most a frame may lead the clock before the clock re-syncs. Default 1,000,000. */
108
+ maxVideoDelayUs?: number;
109
+ /**
110
+ * The target latency: how far behind the position a frame may still be delivered for decoding, and how late a frame
111
+ * must be before wall pacing re-anchors on it. Default: twice the longest of the last four keyframe intervals
112
+ * reported, or 2,000,000 before any is.
113
+ */
114
+ targetLatencyUs?: number;
115
+ /** Audio silent for longer than this hands pacing to the wall clock. Default 500,000. */
116
+ audioTimeoutUs?: number;
117
+ }
118
+ /** What to do with a video frame. `offsetUs` is its timestamp minus the clock's position: positive is early. */
119
+ export type PlayoutDecision = PlayoutWait | PlayoutShow | PlayoutDrop;
120
+ /** The frame is early: hold it and ask again after `waitUs`. */
121
+ export interface PlayoutWait {
122
+ /** Hold the frame. */
123
+ action: 'wait';
124
+ /** The frame's timestamp minus the clock's position, rounded to whole microseconds; positive. */
125
+ offsetUs: number;
126
+ /** How long to hold the frame: the offset, rounded up to whole microseconds. */
127
+ waitUs: number;
128
+ }
129
+ /** Show the frame now: it is on time, late within `lateDropUs`, or a re-sync. */
130
+ export interface PlayoutShow {
131
+ /** Show the frame now. */
132
+ action: 'show';
133
+ /** The frame's timestamp minus the clock's position, rounded to whole microseconds; the sync error to log. */
134
+ offsetUs: number;
135
+ }
136
+ /** The frame is later than `lateDropUs`: audio has moved past it. */
137
+ export interface PlayoutDrop {
138
+ /** Discard the frame. */
139
+ action: 'drop';
140
+ /** The frame's timestamp minus the clock's position, rounded to whole microseconds; negative. */
141
+ offsetUs: number;
142
+ }
143
+ /** `idle` before anything anchors it, `audio` while audio reports arrive, `wall` when paced by the local clock. */
144
+ export type PlayoutMode = 'idle' | 'audio' | 'wall';
145
+ /** A player's clock for one broadcast's timeline. Audio is the master; video asks it when each frame is due. */
146
+ export interface PlayoutClock {
147
+ /** What paces the clock now. */
148
+ readonly mode: PlayoutMode;
149
+ /**
150
+ * Report that the audio with this timeline timestamp is audible at local time `atUs` (default now): what was
151
+ * handed to the output, less the jitter-buffer depth, `AudioContext.outputLatency`, and any extra path.
152
+ */
153
+ reportAudio(timestampUs: number, atUs?: number): void;
154
+ /** Audio is muted or ended: pace by wall clock from the current position. */
155
+ stopAudio(): void;
156
+ /** Decide whether the frame with this timeline timestamp should wait, be shown now, or be dropped. */
157
+ due(timestampUs: number): PlayoutDecision;
158
+ /** The timeline position now, or `undefined` while idle. */
159
+ position(): number | undefined;
160
+ /** How late a frame may be shown, in microseconds: the `lateDropUs` option. */
161
+ readonly lateDropUs: number;
162
+ /** The target latency now: the option, or twice the longest of the last four keyframe intervals reported. */
163
+ readonly targetLatencyUs: number;
164
+ /** Report the spacing between two consecutive keyframes on the timeline; a frame reader does this. */
165
+ reportKeyframeInterval(intervalUs: number): void;
166
+ /** How many times `reset()` has been called: a frame reader sees from it that the timeline changed under it. */
167
+ readonly resets: number;
168
+ /** The clock's local time source now, in microseconds: what a frame reader measures its waits in. */
169
+ localNow(): number;
170
+ /**
171
+ * Forget every anchor, at a Restart, a Move, a resync, or a new catalog: the next frame anchors wall pacing. The
172
+ * keyframe intervals reported so far are kept.
173
+ */
174
+ reset(): void;
175
+ }
176
+ /** Create a playout clock. See spec/media-layer.md, "Playout clock (player)". */
177
+ export declare function createPlayoutClock(options?: PlayoutClockOptions): PlayoutClock;
178
+ //# sourceMappingURL=clock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clock.d.ts","sourceRoot":"","sources":["../src/clock.ts"],"names":[],"mappings":"AAOA,0FAA0F;AAC1F,MAAM,MAAM,gBAAgB,GAAG,MAAM,MAAM,CAAC;AAgB5C,gDAAgD;AAChD,MAAM,WAAW,qBAAqB;IACpC,yEAAyE;IACzE,GAAG,CAAC,EAAE,gBAAgB,CAAC;IACvB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,yDAAyD;AACzD,MAAM,WAAW,qBAAqB;IACpC,2GAA2G;IAC3G,aAAa,CAAC,EAAE,MAAM,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IAAI,CAAC;IAClB,sGAAsG;IACtG,GAAG,CAAC,WAAW,EAAE,MAAM,GAAG,eAAe,CAAC;IAC1C,4DAA4D;IAC5D,QAAQ,IAAI,MAAM,GAAG,SAAS,CAAC;IAC/B,+EAA+E;IAC/E,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,6GAA6G;IAC7G,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,sGAAsG;IACtG,sBAAsB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IACjD,gHAAgH;IAChH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,qGAAqG;IACrG,QAAQ,IAAI,MAAM,CAAC;IACnB;;;OAGG;IACH,KAAK,IAAI,IAAI,CAAC;CACf;AAED,iFAAiF;AACjF,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,mBAAwB,GAAG,YAAY,CAsFlF"}
package/dist/clock.js ADDED
@@ -0,0 +1,190 @@
1
+ /**
2
+ * One timeline for every broadcast, in Unix-epoch microseconds, and a playout clock for audio/video sync. No DOM, no
3
+ * transport: both clocks read an injected monotonic microsecond source. See spec/media-layer.md, "Shared timeline and
4
+ * playout clock".
5
+ */
6
+ import { MICROSECONDS_PER_SECOND } from './loc.js';
7
+ const performanceMicroseconds = () => performance.now() * 1000;
8
+ function finite(value, name) {
9
+ if (!Number.isFinite(value))
10
+ throw new RangeError(`${name} must be a finite number`);
11
+ return value;
12
+ }
13
+ function safeInteger(value, name, minimum) {
14
+ if (!Number.isSafeInteger(value) || value < minimum) {
15
+ throw new RangeError(`${name} must be a safe integer of at least ${minimum}`);
16
+ }
17
+ return value;
18
+ }
19
+ /** Pin a monotonic source to the system clock and map capture timestamps and sample counters onto the epoch. */
20
+ export function createBroadcastClock(options = {}) {
21
+ const source = options.now ?? performanceMicroseconds;
22
+ const createdUs = finite(source(), 'Source time');
23
+ const originUs = options.originUs === undefined ? Math.round(createdUs) : options.originUs;
24
+ safeInteger(originUs, 'originUs', Number.MIN_SAFE_INTEGER);
25
+ const originEpochUs = options.originEpochUs ?? Math.round(Date.now() * 1000 - (createdUs - originUs));
26
+ safeInteger(originEpochUs, 'originEpochUs', 0);
27
+ const fromSourceUs = (sourceUs) => originEpochUs + Math.round(finite(sourceUs, 'Source time') - originUs);
28
+ const now = () => fromSourceUs(source());
29
+ return {
30
+ originUs,
31
+ originEpochUs,
32
+ now,
33
+ fromSourceUs,
34
+ sourceTimeline({ toleranceUs = 5_000, captureLatencyUs = 0 } = {}) {
35
+ if (!(finite(toleranceUs, 'toleranceUs') >= 0))
36
+ throw new RangeError('toleranceUs must not be negative');
37
+ let latencyUs = safeInteger(captureLatencyUs, 'captureLatencyUs', 0);
38
+ let anchor;
39
+ return {
40
+ get anchorSourceUs() {
41
+ return anchor?.sourceUs;
42
+ },
43
+ get captureLatencyUs() {
44
+ return latencyUs;
45
+ },
46
+ set captureLatencyUs(value) {
47
+ latencyUs = safeInteger(value, 'captureLatencyUs', 0);
48
+ },
49
+ calibrate(sourceUs, atUs) {
50
+ finite(sourceUs, 'Source time');
51
+ const measured = atUs === undefined ? now() : fromSourceUs(atUs);
52
+ if (anchor &&
53
+ Math.abs(anchor.timestampUs + Math.round(sourceUs - anchor.sourceUs) - measured) <= toleranceUs) {
54
+ return false;
55
+ }
56
+ anchor = { sourceUs, timestampUs: measured };
57
+ return true;
58
+ },
59
+ timestampUs(sourceUs) {
60
+ finite(sourceUs, 'Source time');
61
+ anchor ??= { sourceUs, timestampUs: now() };
62
+ return anchor.timestampUs + Math.round(sourceUs - anchor.sourceUs) - latencyUs;
63
+ },
64
+ };
65
+ },
66
+ sampleTimeline(sampleRate, { firstSampleUs = now() } = {}) {
67
+ safeInteger(sampleRate, 'sampleRate', 1);
68
+ safeInteger(firstSampleUs, 'firstSampleUs', Number.MIN_SAFE_INTEGER);
69
+ return {
70
+ sampleRate,
71
+ firstSampleUs,
72
+ timestampUs(sampleIndex) {
73
+ safeInteger(sampleIndex, 'Sample index', 0);
74
+ // Whole seconds first, so the product stays exact past 2^53 sample-microseconds.
75
+ const seconds = Math.floor(sampleIndex / sampleRate);
76
+ const remainder = sampleIndex - seconds * sampleRate;
77
+ return (firstSampleUs +
78
+ seconds * MICROSECONDS_PER_SECOND +
79
+ Math.floor((remainder * MICROSECONDS_PER_SECOND) / sampleRate));
80
+ },
81
+ };
82
+ },
83
+ };
84
+ }
85
+ /** The target latency before any keyframe interval is known: twice a one-second keyframe interval. */
86
+ const DEFAULT_TARGET_LATENCY_US = 2_000_000;
87
+ /**
88
+ * The target latency for a broadcast with no video: pass it as `targetLatencyUs`, since the 2 s default waits for
89
+ * keyframe intervals an audio-only track never reports. It covers the audio player's 400 ms jitter-buffer ceiling plus
90
+ * a wired output delay, and a frame sequencer resyncs after half a second of nothing on time instead of two.
91
+ */
92
+ export const AUDIO_ONLY_TARGET_LATENCY_US = 500_000;
93
+ /** How many keyframe intervals the derived target latency looks back over. */
94
+ const KEYFRAME_INTERVALS_KEPT = 4;
95
+ /** Create a playout clock. See spec/media-layer.md, "Playout clock (player)". */
96
+ export function createPlayoutClock(options = {}) {
97
+ const source = options.now ?? performanceMicroseconds;
98
+ const lateDropUs = finite(options.lateDropUs ?? 40_000, 'lateDropUs');
99
+ const maxVideoDelayUs = finite(options.maxVideoDelayUs ?? 1_000_000, 'maxVideoDelayUs');
100
+ const audioTimeoutUs = finite(options.audioTimeoutUs ?? 500_000, 'audioTimeoutUs');
101
+ if (lateDropUs < 0)
102
+ throw new RangeError('lateDropUs must not be negative');
103
+ if (maxVideoDelayUs <= 0)
104
+ throw new RangeError('maxVideoDelayUs must be positive');
105
+ if (audioTimeoutUs <= 0)
106
+ throw new RangeError('audioTimeoutUs must be positive');
107
+ const fixedTargetUs = options.targetLatencyUs === undefined ? undefined : finite(options.targetLatencyUs, 'targetLatencyUs');
108
+ if (fixedTargetUs !== undefined && fixedTargetUs <= 0)
109
+ throw new RangeError('targetLatencyUs must be positive');
110
+ // The latest keyframe intervals: the longest, so that a forced keyframe does not shrink the budget.
111
+ const intervals = [];
112
+ let resets = 0;
113
+ const targetLatency = () => fixedTargetUs ?? (intervals.length > 0 ? 2 * Math.max(...intervals) : DEFAULT_TARGET_LATENCY_US);
114
+ // The timeline position `mediaUs` was current at local time `atUs`; it advances in real time from there.
115
+ // An audio anchor also keeps when its report arrived: silence is measured from arrival, not from `atUs`.
116
+ let anchor;
117
+ const modeAt = (now) => {
118
+ if (!anchor)
119
+ return 'idle';
120
+ const received = anchor.receivedUs;
121
+ return received !== undefined && now - received <= audioTimeoutUs ? 'audio' : 'wall';
122
+ };
123
+ const positionAt = (now) => (anchor ? anchor.mediaUs + (now - anchor.atUs) : undefined);
124
+ return {
125
+ get mode() {
126
+ return modeAt(source());
127
+ },
128
+ reportAudio(timestampUs, atUs) {
129
+ const mediaUs = finite(timestampUs, 'Audio timestamp');
130
+ const receivedUs = source();
131
+ anchor = { mediaUs, atUs: atUs === undefined ? receivedUs : finite(atUs, 'Audio report time'), receivedUs };
132
+ },
133
+ stopAudio() {
134
+ const now = source();
135
+ if (modeAt(now) === 'audio')
136
+ anchor = { mediaUs: positionAt(now), atUs: now };
137
+ },
138
+ due(timestampUs) {
139
+ finite(timestampUs, 'Frame timestamp');
140
+ const now = source();
141
+ const mode = modeAt(now);
142
+ const position = positionAt(now);
143
+ if (mode === 'idle' || position === undefined) {
144
+ anchor = { mediaUs: timestampUs, atUs: now };
145
+ return { action: 'show', offsetUs: 0 };
146
+ }
147
+ const offset = timestampUs - position;
148
+ const offsetUs = Math.round(offset);
149
+ if (mode === 'wall' && (offset > maxVideoDelayUs || offset < -targetLatency())) {
150
+ // A timeline jump or a stall: follow the video rather than drop or hold every later frame.
151
+ anchor = { mediaUs: timestampUs, atUs: now };
152
+ return { action: 'show', offsetUs };
153
+ }
154
+ // Audio stays the master: a frame that far ahead is not on its timeline, and holding it would freeze the picture.
155
+ if (offset > maxVideoDelayUs)
156
+ return { action: 'show', offsetUs };
157
+ if (offset > 0)
158
+ return { action: 'wait', offsetUs, waitUs: Math.ceil(offset) };
159
+ if (offset >= -lateDropUs)
160
+ return { action: 'show', offsetUs };
161
+ return { action: 'drop', offsetUs };
162
+ },
163
+ position() {
164
+ return positionAt(source());
165
+ },
166
+ lateDropUs,
167
+ get targetLatencyUs() {
168
+ return targetLatency();
169
+ },
170
+ reportKeyframeInterval(intervalUs) {
171
+ const interval = finite(intervalUs, 'Keyframe interval');
172
+ if (interval <= 0)
173
+ throw new RangeError('A keyframe interval must be positive');
174
+ intervals.push(interval);
175
+ if (intervals.length > KEYFRAME_INTERVALS_KEPT)
176
+ intervals.shift();
177
+ },
178
+ get resets() {
179
+ return resets;
180
+ },
181
+ localNow() {
182
+ return source();
183
+ },
184
+ reset() {
185
+ anchor = undefined;
186
+ resets++;
187
+ },
188
+ };
189
+ }
190
+ //# sourceMappingURL=clock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clock.js","sourceRoot":"","sources":["../src/clock.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,uBAAuB,EAAE,MAAM,UAAU,CAAC;AAKnD,MAAM,uBAAuB,GAAqB,GAAG,EAAE,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAEjF,SAAS,MAAM,CAAC,KAAa,EAAE,IAAY;IACzC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,UAAU,CAAC,GAAG,IAAI,0BAA0B,CAAC,CAAC;IACrF,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,WAAW,CAAC,KAAa,EAAE,IAAY,EAAE,OAAe;IAC/D,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,OAAO,EAAE,CAAC;QACpD,MAAM,IAAI,UAAU,CAAC,GAAG,IAAI,uCAAuC,OAAO,EAAE,CAAC,CAAC;IAChF,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAkGD,gH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YACN,OAAO,MAAM,EAAE,CAAC;QAClB,CAAC;QACD,KAAK;YACH,MAAM,GAAG,SAAS,CAAC;YACnB,MAAM,EAAE,CAAC;QACX,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Chromium's echo canceller takes only audio that WebRTC plays as its reference, so call audio played straight from an
3
+ * `AudioContext` reaches the far end again through the speakers. The standard workaround routes it through a pair of
4
+ * local `RTCPeerConnection`s into a media element. Firefox and Safari cancel echo from all page output and need none.
5
+ */
6
+ import type { AudioPlayerNode } from './audio-player.js';
7
+ /** The part of an `AudioContext` the loopback uses. */
8
+ export interface EchoCancellationContext {
9
+ /** Create the node whose stream the loopback sends. */
10
+ createMediaStreamDestination(): AudioPlayerNode & {
11
+ /** The `MediaStream` carrying what the node receives. */
12
+ readonly stream: unknown;
13
+ /** Channels the node mixes to; the loopback sets 2. */
14
+ channelCount: number;
15
+ };
16
+ }
17
+ /** Options for {@link createEchoCancellationLoopback}. */
18
+ export interface EchoCancellationLoopbackOptions {
19
+ /** The output device, as for `HTMLMediaElement.setSinkId`. Default: the system's. */
20
+ sinkId?: string;
21
+ /** How long to wait for the loopback to connect, in milliseconds. Default 5000. */
22
+ timeoutMs?: number;
23
+ }
24
+ /** A running loopback. Close it, and connect the node to the context's destination, to play directly again. */
25
+ export interface EchoCancellationLoopback {
26
+ /** Play on another output device. */
27
+ setSinkId(sinkId: string): Promise<void>;
28
+ /** Disconnect the node from the loopback and close both connections. */
29
+ close(): void;
30
+ }
31
+ /**
32
+ * Play `node` through a local WebRTC loopback so Chromium's echo canceller hears it. The node is connected to the
33
+ * loopback only once it is up; disconnect it from the context's destination yourself, or it plays twice. Rejects if
34
+ * the loopback cannot connect. It adds the WebRTC receiver's own buffering, which no API reports as output latency:
35
+ * set the audio player's `outputDelayUs` if video must stay in sync with it.
36
+ */
37
+ export declare function createEchoCancellationLoopback(context: EchoCancellationContext, node: AudioPlayerNode, options?: EchoCancellationLoopbackOptions): Promise<EchoCancellationLoopback>;
38
+ //# sourceMappingURL=echo-loopback.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"echo-loopback.d.ts","sourceRoot":"","sources":["../src/echo-loopback.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEzD,uDAAuD;AACvD,MAAM,WAAW,uBAAuB;IACtC,uDAAuD;IACvD,4BAA4B,IAAI,eAAe,GAAG;QAChD,yDAAyD;QACzD,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;QACzB,uDAAuD;QACvD,YAAY,EAAE,MAAM,CAAC;KACtB,CAAC;CACH;AAED,0DAA0D;AAC1D,MAAM,WAAW,+BAA+B;IAC9C,qFAAqF;IACrF,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,mFAAmF;IACnF,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,+GAA+G;AAC/G,MAAM,WAAW,wBAAwB;IACvC,qCAAqC;IACrC,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC,wEAAwE;IACxE,KAAK,IAAI,IAAI,CAAC;CACf;AAyDD;;;;;GAKG;AACH,wBAAsB,8BAA8B,CAClD,OAAO,EAAE,uBAAuB,EAChC,IAAI,EAAE,eAAe,EACrB,OAAO,GAAE,+BAAoC,GAC5C,OAAO,CAAC,wBAAwB,CAAC,CAwEnC"}