@caprid/moq-media 0.0.0 → 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 -4
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2025-present Video.js contributors
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+
15
+ ------------------------------------------------------------------
16
+
17
+ Trademark Notice:
18
+ “Video.js” is a registered trademark of Brightcove Inc.
19
+ The project is maintained independently by the open-source community,
20
+ governed by the Video.js Technical Steering Committee.
package/NOTICE ADDED
@@ -0,0 +1,6 @@
1
+ Media format helpers are derived from Video.js media/moq modules and the Relay SDKs
2
+ Python Video.js example. The Python package ports the same format behavior.
3
+ Copyright 2025-present Video.js contributors.
4
+ Licensed under the Apache License, Version 2.0. See LICENSE.
5
+
6
+ See UPSTREAM.json for the source revision, original file hashes, and adaptations.
package/README.md CHANGED
@@ -1,3 +1,188 @@
1
- # @caprid/moq-media
1
+ # MoQ media formats
2
2
 
3
- Placeholder so the name can be set up for trusted publishing. Install 0.1.0 or later.
3
+ Pure LOC (`draft-ietf-moq-loc-04`) and independent MSF (`draft-ietf-moq-msf-01`) format helpers.
4
+ Depends only on the generic MoQ core. No encoders, transport libraries, or Relay connection required.
5
+
6
+ The catalog builder emits compact UTF-8 JSON bytes. It withholds `avc1`/`avc3` until non-empty init
7
+ data exists, derives their profile/constraint/level suffix from avcC (preserving `avc3`), forces Opus
8
+ to 48 kHz, and rejects duplicate names and media roles on data tracks. Catalog namespaces use the
9
+ player's slash-joined dialect, so fields containing `/` or empty fields are rejected. Source URLs
10
+ can escape literal slashes in tuple fields. Omitted fields never become JSON nulls. Empty init
11
+ data is omitted for every codec, and catalog strings must be valid Unicode (no lone surrogates).
12
+
13
+ LOC helpers accept nonnegative microsecond timestamps and a positive timescale, both safe integers
14
+ (up to 2^53−1). A custom timescale rounds to the nearest tick, ties upward. Pass decoder configs only
15
+ on keyframes, declare the same timescale on the track, and keep init data in the catalog too.
16
+
17
+ TypeScript consumes encoder/demuxer-provided decoder configuration and length-prefixed H.264
18
+ packets. `avcCodecString` inspects the avcC header; it does not parse SPS or validate a bitstream.
19
+ Annex B parsing, SPS/PPS reconstruction, and access-unit conversion are not exposed in TypeScript.
20
+ The primary browser input is native WebCodecs. `videoTrackFromDecoderConfig` maps AVC decoder
21
+ configuration (four-byte NAL lengths). A decoder config carries no bitrate or framerate, so a caller
22
+ that knows them spreads them into the returned `VideoTrackInfo`. `audioTrackFromDecoderConfig` maps Opus
23
+ configuration.
24
+ Both copy description buffers, including the exact range of a view. `chunkToLocFrame` accepts
25
+ `EncodedVideoChunk` or `EncodedAudioChunk` and returns `{ payload, timestampUs, key, properties }`.
26
+ It copies encoded bytes unchanged, attaches supplied configs only on key chunks, and accepts the
27
+ same timescale/config options as `locProperties`, plus an integer `timestampOffsetUs` for a shared
28
+ track timeline. The final timestamp must be a nonnegative safe integer. Preserve encoder output
29
+ order, even when presentation timestamps are reordered. These functions use WebCodecs types but
30
+ do not require browser globals at import time.
31
+
32
+ See the [direct WebCodecs publishing example](../../examples/webcodecs/README.md) for live browser
33
+ video, catalog serving, groups, bounded buffering, and cleanup. For files that need demuxing, use
34
+ the optional [Mediabunny packet adapter](../moq-mediabunny/README.md). Python retains its Annex B
35
+ helpers for the PyAV publisher.
36
+
37
+ `buildMsfCatalog` describes a live broadcast and leaves `isComplete` out: msf-01 §5.1.3 forbids the
38
+ field while false, and once a catalog carries it, it can never be removed. When a broadcast ends on
39
+ purpose, close the media tracks first (each close tells subscribers the track ended), then write
40
+ `buildMsfEndCatalog({ generatedAt })` to the catalog track if it has demand, then close it
41
+ (msf-01 §11.3). Do not send it after a crash or a lost connection.
42
+
43
+ `parseMsfCatalog` reads an independent catalog object's payload back into track descriptions:
44
+ namespace tuple, name, packaging, live status, role, codec, dimensions, rates, bitrate, render
45
+ group, and init data resolved from `initRef` to bytes. It rejects unsupported versions and delta
46
+ updates, ignores unknown fields, and returns non-`loc` packagings (such as moq-rs `cmaf`) as
47
+ declared.
48
+
49
+ For simulcast layers or a second source, pass `media`: a list of `{ role: 'video', ... }` and
50
+ `{ role: 'audio', ... }` entries, each with an optional `renderGroup` (default 1, tracks played
51
+ together) and `altGroup` (alternate versions of one content, of which a viewer plays one). Members
52
+ of an alternate group share a role and a render group. `parseMsfCatalog` returns both fields, and
53
+ `groupMsfTracks(catalog.tracks)` lists the sets a viewer picks one track from. See
54
+ [several media tracks](../../../spec/media-layer.md#several-media-tracks).
55
+
56
+ ```ts
57
+ const catalog = buildMsfCatalog({
58
+ namespace,
59
+ media: [
60
+ { role: 'video', name: 'video-hi', codec: 'vp8', width: 1280, height: 720, altGroup: 1 },
61
+ { role: 'video', name: 'video-lo', codec: 'vp8', width: 320, height: 180, altGroup: 1 },
62
+ { role: 'audio', name: 'audio' },
63
+ { role: 'video', name: 'screen', codec: 'vp9', renderGroup: 2 },
64
+ ],
65
+ });
66
+ ```
67
+
68
+ Every media track shares one timeline: LOC timestamps are capture times in microseconds since the
69
+ Unix epoch, with Timescale 1,000,000 declared on each track. `createBroadcastClock()` pins the
70
+ `performance.now()` clock to `Date.now()` once and counts from there, so broadcasts from different
71
+ publishers line up as closely as their system clocks do.
72
+
73
+ The publisher path below works in Chromium, Firefox and Safari:
74
+
75
+ - **Video.** Stamp frames drawn from the camera with `clock.now()`.
76
+ - **Audio.** Route the microphone through an `AudioContext` and an `AudioWorklet`. Stamp audio
77
+ from the context clock through `clock.sourceTimeline()`, calibrated with the context's render
78
+ clock: a context time and when it was rendered, from the worklet block that reached the main
79
+ thread soonest after its render. Do not calibrate from `getOutputTimestamp()`: Firefox returns
80
+ the render pair shifted back by the output delay, which stamps audio that much early. The
81
+ WebCodecs example's `capture-microphone.ts` does this.
82
+ - **Device changes.** The context resamples whatever device is connected and keeps running while
83
+ devices change, so switching microphones does not shift the timeline.
84
+ - **Chromium alternative.** Where `MediaStreamTrackProcessor` exists, its timestamps count from the
85
+ system's monotonic zero, so map them through an uncalibrated `sourceTimeline()`.
86
+ - **Microphone latency.** No browser reports a microphone's own input latency: about 30 ms for a
87
+ MacBook's built-in microphone and 190 ms for AirPods, measured on macOS. Set it as
88
+ `captureLatencyUs` on the source timeline, at creation or whenever the device changes, and it is
89
+ subtracted from every timestamp. See
90
+ [spec/media-layer.md](../../../spec/media-layer.md#capture-latency).
91
+
92
+ On the player, `createPlayoutClock()` makes audio the master. Report what is audible with
93
+ `reportAudio(mediaUs, atUs)`: the context time rendered now, less `baseLatency + outputLatency`
94
+ read fresh each time, because the output delay changes with the device. Video asks `due(timestampUs)` for a `wait`, `show`, or `drop`
95
+ decision. With no audio, the clock paces by wall clock. Neither clock needs the DOM; see
96
+ [spec/media-layer.md](../../../spec/media-layer.md#shared-timeline-and-playout-clock).
97
+
98
+ ```ts
99
+ const clock = createBroadcastClock();
100
+ const video = new VideoFrame(canvas, { timestamp: clock.now() });
101
+
102
+ // AudioWorklet blocks carry their context time. `renderedUs` / `arrivedUs`: the best pair of the last second.
103
+ const context = clock.sourceTimeline({ captureLatencyUs: 30_000 });
104
+ context.calibrate(renderedUs, arrivedUs);
105
+ const audioTimestampUs = context.timestampUs(blockContextUs);
106
+
107
+ const playout = createPlayoutClock();
108
+ // The context time audible now: rendered now, less the output delay read fresh on every report.
109
+ const latencyUs = (audioContext.baseLatency + audioContext.outputLatency) * 1e6;
110
+ playout.reportAudio(mediaTimestampAt(nowRenderedUs - latencyUs), performance.now() * 1000);
111
+ const decision = playout.due(frame.timestamp);
112
+ if (decision.action === 'wait') setTimeout(retry, decision.waitUs / 1000);
113
+ ```
114
+
115
+ A subscriber reads an object's timestamp with `locTimestampUs(object.properties, { trackProperties })`,
116
+ passing the track properties from `subscription.subscribed`. It applies whichever Timescale the
117
+ object or the track declares, rather than assuming the relay rescaled to microseconds.
118
+
119
+ msf-01's Media Timeline track maps media time to group locations, for seeking and playlists: one
120
+ record per video group. On this timeline media time already is wall-clock time, so a record's two
121
+ times agree. Announce it with `mediaTimeline: {}` in `buildMsfCatalog` (it lists the video and audio
122
+ tracks in `depends`). `createMediaTimeline` keeps one broadcast's records, 512 by default, and
123
+ returns the document to send each time a keyframe has opened a video group: write it as a new
124
+ timeline group, and again whenever the relay subscribes. The
125
+ [WebCodecs example](../../examples/webcodecs/README.md) does this; see
126
+ [spec/media-layer.md](../../../spec/media-layer.md#media-timeline-track).
127
+
128
+ ```ts
129
+ const timeline = createMediaTimeline();
130
+ // Once the keyframe that opened video group `groupId` is written:
131
+ const document = timeline.add({ timestampUs, group: groupId });
132
+ if (timelineTrack.hasDemand) await timelineTrack.write(document); // one object, one group
133
+ const read = parseMediaTimeline(timelineObject.payload);
134
+ ```
135
+
136
+ Shared vectors live in `spec/vectors/media.json` and `spec/vectors/clock.json`. See `UPSTREAM.json` for Video.js provenance.
137
+ `createFrameSequencer({ clock })` turns one subscribed track's objects, which can arrive out of
138
+ order across group streams, into frames in decode order, and drops what is too late against the
139
+ playout clock; `@caprid/relay/media`'s `createFrameReader` drives it from a subscription (see the
140
+ [guide](../../GUIDE.md#subscribing-to-media)). Per track, `lateDropUs`, `reorderWindowUs` and
141
+ `catchUpAfterUs` tune audio delivery for a listener or for speech-to-text, and `missingGroups` on a
142
+ frame names the groups skipped before it (see [voice delivery](../../GUIDE.md#voice-delivery-per-direction)). The combined `register_media` publishing handle is
143
+ still a proposal in `spec/media-layer.md`; `@caprid/relay/media` ships the frame writer and catalog
144
+ service it would compose.
145
+
146
+ ```ts
147
+ import { buildMsfCatalog, composeMoqSource, locProperties, locTrackProperties, parseMsfCatalog } from '@caprid/moq-media';
148
+
149
+ const catalog = buildMsfCatalog({
150
+ namespace: ['room', 'live'],
151
+ video: { codec: 'avc1.42E01F', width: 640, height: 360, initData: avcc },
152
+ audio: { codec: 'opus' },
153
+ });
154
+ const video = publisher.registerTrack({ track: 'video', trackProperties: locTrackProperties() });
155
+ await group.write(encodedFrame, { properties: locProperties(timestampUs, { videoConfig: avcc }) });
156
+ const source = composeMoqSource('https://relay.example', ['room', 'live'], { token });
157
+
158
+ const { tracks } = parseMsfCatalog(catalogObject.payload, { catalogNamespace: ['room', 'live'] });
159
+ ```
160
+
161
+ ## Audio playout
162
+
163
+ `createAudioPlayer({ context })` plays decoded audio with no UI: each `player.addInput({ clock,
164
+ decoderConfig })` decodes the frames it is pushed with WebCodecs (`audioDecoderConfigFromTrack` reads
165
+ the config from a catalog track), holds them in an adaptive jitter buffer in an `AudioWorklet`
166
+ (60 ms to start, 40–400 ms), reports what is audible to the broadcast's playout clock, and plays
167
+ through its own gain into `player.output`, the one mix the application routes. `input.cut({ fromUs,
168
+ untilUs })` drops received audio in a timeline range; an `Interrupt` read with `parseInterrupt`
169
+ from a talker's interrupt track (`INTERRUPT_TRACK`) is one, so `input.cut(parseInterrupt(object.payload))`
170
+ applies it, and `buildInterrupt({ untilUs })` writes one. A talker's transcript track
171
+ (`TRANSCRIPT_TRACK`) carries the text of its audio: read each segment with `parseTranscriptSegment`,
172
+ keep them in `createTranscript()`, cut it on each interrupt with `transcript.cut(interrupt,
173
+ clock.position())`, and show `transcript.linesAt(clock.position())`; `buildTranscriptSegment` writes one. `createEchoCancellationLoopback(context,
174
+ node)` plays a node through a local WebRTC loopback so Chromium's echo canceller hears it.
175
+ `input.playbackRate` (0.5 to 2) lets a player that owns its latency nudge it, and an input's clock
176
+ can be the player's own (`AudioInputClock`): each report passes it the input's stats, including
177
+ `playStarts`, `heldUntilUs` and `dryAtUs`.
178
+ `createRenderClock` times an `AudioContext`'s renders on `performance.now()`'s clock, for capture
179
+ and playout alike. Give an audio-only broadcast's clock `AUDIO_ONLY_TARGET_LATENCY_US` (500 ms): the
180
+ 2 s default waits for keyframe intervals. The player takes structural Web Audio types, so it imports
181
+ no DOM library and its tests run under a fake context that runs the real worklet. See the
182
+ [guide](../../GUIDE.md#playing-audio) and
183
+ [spec/media-layer.md](../../../spec/media-layer.md#audio-player).
184
+
185
+ ## Stability
186
+
187
+ Before 1.0, a minor version can break the API. This package releases together with `@caprid/relay`
188
+ at the same version; see the [changelog](../../CHANGELOG.md).
package/UPSTREAM.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "repository": "https://github.com/videojs/v10",
3
+ "revision": "dafbe32d615892fe2be9f9c893e04171b30cedc5",
4
+ "files": {
5
+ "packages/spf/src/media/moq/build-catalog.ts": "9d0c8f232704c579294f09682dd89be18dd6f66b0e8ebbe34edea501e738f799",
6
+ "packages/spf/src/media/moq/parse-source.ts": "ccda828ac59dbc7b85246bfcfd9ff7d5f1575f172ba2afff07e7e60acc461938",
7
+ "packages/spf/src/media/moq/avc-codec.ts": "2c7b296d298838f1dc6356618211f92488985d989c548a4a90bc16cc2e8a7712",
8
+ "packages/spf/src/media/moq/parse-catalog.ts": "b291eadeb3b93206df118df1be68d226ccba2f06683d5e36b8c8b7a23545f508"
9
+ },
10
+ "adaptations": [
11
+ "Relative imports use .js suffixes.",
12
+ "webcodecs.ts is original SDK code: standard decoder-config mapping and encoded-chunk to LOC conversion, independent of media engines.",
13
+ "Catalog building has one video track, default names and Opus defaults, validation, and avcC-derived H.264 codec strings. It emits UTF-8 bytes.",
14
+ "Source composition accepts explicit https/moqt URLs and namespace tuples, with RFC 3986 token escaping.",
15
+ "The catalog parser retains the independent-catalog path, public as parseMsfCatalog over UTF-8 payload bytes. Its types are renamed MsfCatalog/MsfCatalogTrack and trimmed to the fields both SDKs read; integral-count fields ignore non-integral values. Player presentation types, variable substitution, and delta updates are omitted.",
16
+ "LOC properties are ported from the Relay Python example, with validation shared through spec vectors. TypeScript consumes supplied avcC records and retains only codec-header inspection; Annex B conversion remains Python-only."
17
+ ],
18
+ "migration": "Attributed extraction for reuse by Video.js. Changes to format behavior should migrate upstream."
19
+ }
@@ -0,0 +1,206 @@
1
+ /**
2
+ * A headless audio player: decodes each input's frames with WebCodecs, holds them in an adaptive jitter buffer in an
3
+ * `AudioWorklet`, mixes every input into one output node, and reports what is audible to each input's playout clock.
4
+ * No UI and no transport: frames in, a node and clock reports out. See spec/media-layer.md, "Audio player".
5
+ */
6
+ import type { FrameDiscontinuity, SequencedFrame } from './sequencer.js';
7
+ /** The part of an `AudioNode` the player uses. A Web Audio node qualifies. */
8
+ export interface AudioPlayerNode {
9
+ /** Send this node's output to `destination`. */
10
+ connect(destination: AudioPlayerNode): unknown;
11
+ /** Disconnect from `destination`, or from everything. */
12
+ disconnect(destination?: AudioPlayerNode): void;
13
+ }
14
+ /** The part of a `GainNode` the player uses. */
15
+ export interface AudioPlayerGainNode extends AudioPlayerNode {
16
+ /** The gain applied to what passes through. */
17
+ readonly gain: {
18
+ /** The multiplier: 1 passes audio unchanged. */
19
+ value: number;
20
+ };
21
+ }
22
+ /** The part of an `AudioContext` the player uses. A Web Audio `AudioContext` qualifies. */
23
+ export interface AudioPlayerContext {
24
+ /** Frames per second the context renders at; decoded audio at another rate is resampled to it. */
25
+ readonly sampleRate: number;
26
+ /** Seconds between the graph and the audio subsystem. */
27
+ readonly baseLatency?: number;
28
+ /** Seconds from the audio subsystem to the speaker; changes with the device. */
29
+ readonly outputLatency?: number;
30
+ /** Where the jitter buffer's worklet module is loaded. */
31
+ readonly audioWorklet: {
32
+ /** Load a worklet module from a URL. */
33
+ addModule(url: string): Promise<void>;
34
+ };
35
+ /** Create a gain node: one per input, and the output. */
36
+ createGain(): AudioPlayerGainNode;
37
+ }
38
+ /** Options for {@link createAudioPlayer}. */
39
+ export interface AudioPlayerOptions<Context extends AudioPlayerContext> {
40
+ /** The one context every input plays through. Create or resume it from a user gesture. */
41
+ context: Context;
42
+ }
43
+ /** One encoded audio frame: a `SequencedFrame` from a frame reader qualifies. */
44
+ export type AudioPlayerFrame = Pick<SequencedFrame, 'timestampUs' | 'payload'> & {
45
+ /** Set where the frame does not follow the one before: a decoder resets, and a `resync` or `restart` flushes. */
46
+ discontinuity?: FrameDiscontinuity | undefined;
47
+ };
48
+ /**
49
+ * What an input calls on its clock. A `PlayoutClock` qualifies; so does a player's own clock, such as one that holds
50
+ * its position while the buffer is dry.
51
+ */
52
+ export interface AudioInputClock {
53
+ /** Caps the jitter buffer: it holds no more than this less the output delay and 40 ms. */
54
+ readonly targetLatencyUs: number;
55
+ /** The time source reports are measured on, in microseconds. */
56
+ localNow(): number;
57
+ /**
58
+ * The audio with this timeline timestamp is audible at local time `atUs`. `stats` are the input's, refreshed with
59
+ * this report: a newer `playStarts` says the audio is from after the buffer last ran dry, not the tail before it.
60
+ * The object is updated in place by later reports, so copy what you keep.
61
+ */
62
+ reportAudio(timestampUs: number, atUs: number, stats: Readonly<AudioInputStats>): void;
63
+ /** The input was removed. */
64
+ stopAudio(): void;
65
+ }
66
+ /** Options for {@link AudioPlayer.addInput}. Durations are microseconds. */
67
+ export interface AudioInputOptions {
68
+ /**
69
+ * The broadcast's playout clock. The input reports the audible timestamp to it about every 20 ms while it plays,
70
+ * and its target latency caps the jitter buffer. Without one, nothing is reported.
71
+ */
72
+ clock?: AudioInputClock;
73
+ /** How to decode. Default: Opus, 48 kHz, two channels; `audioDecoderConfigFromTrack` reads one from the catalog. */
74
+ decoderConfig?: AudioDecoderConfig;
75
+ /** The input's gain. Default 1. */
76
+ gain?: number;
77
+ /** Held audio played per output frame, from 0.5 to 2; see {@link AudioPlayerInput.playbackRate}. Default 1. */
78
+ playbackRate?: number;
79
+ /** How much audio to hold before playing, at the start and after each underrun. Default 60,000. */
80
+ jitterTargetUs?: number;
81
+ /** The least the target shrinks to while playback is smooth. Default 40,000. */
82
+ minJitterTargetUs?: number;
83
+ /**
84
+ * The most the target grows to after underruns. Default 400,000, and never more than the clock's target latency
85
+ * less the output delay and 40 ms: a frame further ahead of the clock than its target latency makes the frame
86
+ * sequencer resync.
87
+ */
88
+ maxJitterTargetUs?: number;
89
+ /** A decoder error. The input decodes again from the next frame, with a new decoder. */
90
+ onError?(error: unknown): void;
91
+ }
92
+ /** Which audio {@link AudioPlayerInput.cut} drops, by timeline timestamp in microseconds. */
93
+ export interface AudioCutRange {
94
+ /** Drop from this timestamp on. Default: from the oldest audio held. */
95
+ fromUs?: number;
96
+ /**
97
+ * Drop before this timestamp. Default: through the newest audio held. With it, frames that arrive later inside the
98
+ * range are dropped too, until a `restart`; a `resync` keeps the cut.
99
+ */
100
+ untilUs?: number;
101
+ }
102
+ /** An input's counters and jitter-buffer state. Counters are cumulative; durations are microseconds. */
103
+ export interface AudioInputStats {
104
+ /** Frames handed to the decoder. */
105
+ decoded: number;
106
+ /** Frames dropped on arrival: behind audio already decoded, or inside a cut. */
107
+ late: number;
108
+ /** Times the decoder was reset or replaced: at a discontinuity, a timestamp jump, or after an error. */
109
+ decoderResets: number;
110
+ /** Decoder errors. */
111
+ errors: number;
112
+ /** Times the buffer ran dry while playing and audio came back within the jitter-buffer ceiling. */
113
+ underruns: number;
114
+ /** Whether the buffer is playing, rather than filling to its target. */
115
+ playing: boolean;
116
+ /** Times playback started: at the start, after running dry, and after a flush or a cut that emptied the buffer. */
117
+ playStarts: number;
118
+ /** The timeline timestamp just past the newest audio held: the end of decoded audio. `null` when nothing is held. */
119
+ heldUntilUs: number | null;
120
+ /**
121
+ * The timeline timestamp where the buffer last ran dry while playing, until playback starts again; `null` otherwise,
122
+ * and after a flush or a cut that empties the buffer.
123
+ */
124
+ dryAtUs: number | null;
125
+ /** The audio held now. */
126
+ bufferedUs: number;
127
+ /** The jitter-buffer target now. */
128
+ jitterTargetUs: number;
129
+ /** Audio dropped to shed latency: held past what the target needed, or past the hard bound. */
130
+ trimmedUs: number;
131
+ /** Silence played in place of frames that never came. */
132
+ concealedUs: number;
133
+ /** Audio dropped by `cut()`. */
134
+ cutUs: number;
135
+ /** Clock reports made. */
136
+ reports: number;
137
+ }
138
+ /** One input of an {@link AudioPlayer}: one track, usually one speaker. */
139
+ export interface AudioPlayerInput {
140
+ /**
141
+ * Decode and buffer a frame, in decode order. A frame reader's `onFrame` can be this. A `resync` or `restart`
142
+ * discontinuity also flushes what is held: it belongs to the replaced timeline.
143
+ */
144
+ push(frame: AudioPlayerFrame): void;
145
+ /**
146
+ * Drop audio already received in a timeline range, held or still decoding, as at a talker's interruption. No range
147
+ * drops everything held, as a flush does.
148
+ */
149
+ cut(range?: AudioCutRange): void;
150
+ /** The input's gain. */
151
+ gain: number;
152
+ /**
153
+ * Held audio played per output frame, from the next render quantum: above 1 sheds latency, below 1 gains it, and
154
+ * pitch shifts with it (no time-stretching). From 0.5 to 2. Held audio, the jitter target, trims and the hard bound
155
+ * stay measured in held audio, and reports carry the timestamp at the fractional read position.
156
+ */
157
+ playbackRate: number;
158
+ /** Counters, refreshed with each report from the worklet. */
159
+ readonly stats: Readonly<AudioInputStats>;
160
+ /** Stop: the decoder closes, the worklet stops, and the clock goes to wall pacing. */
161
+ remove(): void;
162
+ /** Whether `remove()` or the player's `close()` was called. */
163
+ readonly removed: boolean;
164
+ }
165
+ /** Plays any number of inputs into one output node. */
166
+ export interface AudioPlayer<Output extends AudioPlayerGainNode = AudioPlayerGainNode> {
167
+ /** The context every input plays through. */
168
+ readonly context: AudioPlayerContext;
169
+ /**
170
+ * The mix of every input. Connect it to the context's destination, or route it through
171
+ * `createEchoCancellationLoopback` so Chromium's echo canceller hears it.
172
+ */
173
+ readonly output: Output;
174
+ /**
175
+ * Delay after the output that the context does not report, in microseconds, such as an echo-cancellation loopback.
176
+ * Added to every input's audible time. Default 0.
177
+ */
178
+ outputDelayUs: number;
179
+ /** Add an input. */
180
+ addInput(options?: AudioInputOptions): AudioPlayerInput;
181
+ /** The inputs not yet removed. */
182
+ readonly inputs: readonly AudioPlayerInput[];
183
+ /** Remove every input and disconnect the output. The context stays the caller's to close. */
184
+ close(): void;
185
+ }
186
+ /**
187
+ * How long an Opus packet plays, in microseconds, from its TOC byte (RFC 6716 §3.1); `undefined` when it cannot be
188
+ * read.
189
+ */
190
+ export declare function opusPacketDurationUs(packet: Uint8Array): number | undefined;
191
+ /**
192
+ * Create an audio player on `context`: it loads the jitter buffer's worklet once per context, so it resolves after
193
+ * that. Connect `player.output` yourself.
194
+ *
195
+ * ```ts
196
+ * const context = new AudioContext({ sampleRate: 48_000, latencyHint: 'interactive' });
197
+ * const player = await createAudioPlayer({ context });
198
+ * player.output.connect(context.destination);
199
+ * const clock = createPlayoutClock({ targetLatencyUs: AUDIO_ONLY_TARGET_LATENCY_US });
200
+ * const input = player.addInput({ clock, decoderConfig: audioDecoderConfigFromTrack(audioTrack) });
201
+ * const reader = createFrameReader(createFrameSequencer({ clock, grouping: 'frame' }), { onFrame: input.push });
202
+ * subscriber.subscribe({ namespace, track: 'audio' }, { ...reader, onError });
203
+ * ```
204
+ */
205
+ export declare function createAudioPlayer<Context extends AudioPlayerContext>(options: AudioPlayerOptions<Context>): Promise<AudioPlayer<ReturnType<Context['createGain']>>>;
206
+ //# sourceMappingURL=audio-player.d.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