@caprid/moq-media 0.1.0 → 0.2.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.
package/NOTICE CHANGED
@@ -4,3 +4,30 @@ Copyright 2025-present Video.js contributors.
4
4
  Licensed under the Apache License, Version 2.0. See LICENSE.
5
5
 
6
6
  See UPSTREAM.json for the source revision, original file hashes, and adaptations.
7
+
8
+ The audio player's loss concealment embeds libopus 1.5.2 (decoder only), compiled to WebAssembly by
9
+ scripts/build-opus-wasm.sh into src/opus-decoder-wasm.ts. libopus is distributed under this license:
10
+
11
+ Copyright 2001-2023 Xiph.Org, Skype Limited, Octasic, Jean-Marc Valin, Timothy B. Terriberry,
12
+ CSIRO, Gregory Maxwell, Mark Borgerding, Erik de Castro Lopo, Mozilla, Amazon
13
+
14
+ Redistribution and use in source and binary forms, with or without modification, are permitted
15
+ provided that the following conditions are met:
16
+
17
+ - Redistributions of source code must retain the above copyright notice, this list of conditions
18
+ and the following disclaimer.
19
+ - Redistributions in binary form must reproduce the above copyright notice, this list of
20
+ conditions and the following disclaimer in the documentation and/or other materials provided
21
+ with the distribution.
22
+ - Neither the name of Internet Society, IETF or IETF Trust, nor the names of specific
23
+ contributors, may be used to endorse or promote products derived from this software without
24
+ specific prior written permission.
25
+
26
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
27
+ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
28
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
32
+ IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33
+ OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,57 +1,63 @@
1
1
  # MoQ media formats
2
2
 
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).
3
+ `@caprid/moq-media` holds pure format helpers for LOC (`draft-ietf-moq-loc-04`) and independent MSF
4
+ (`draft-ietf-moq-msf-01`) catalogs, plus the clocks, frame sequencer, and audio player that sit on top of them. It
5
+ depends only on `@caprid/moq-core`. It needs no encoder, transport library, or Relay connection.
6
+
7
+ ```ts
8
+ import { buildMsfCatalog, composeMoqSource, locProperties, locTrackProperties, parseMsfCatalog } from '@caprid/moq-media';
9
+
10
+ const catalog = buildMsfCatalog({
11
+ namespace: ['room', 'live'],
12
+ video: { codec: 'avc1.42E01F', width: 640, height: 360, initData: avcc },
13
+ audio: { codec: 'opus' },
14
+ });
15
+ const video = publisher.registerTrack({ track: 'video', trackProperties: locTrackProperties() });
16
+ await group.write(encodedFrame, { properties: locProperties(timestampUs, { videoConfig: avcc }) });
17
+ const source = composeMoqSource('https://relay.example', ['room', 'live'], { token });
18
+
19
+ const { tracks } = parseMsfCatalog(catalogObject.payload, { catalogNamespace: ['room', 'live'] });
20
+ ```
21
+
22
+ Shared test vectors live in `spec/vectors/media.json` and `spec/vectors/clock.json`. `UPSTREAM.json` records the
23
+ Video.js provenance.
24
+
25
+ ## Catalogs
26
+
27
+ `buildMsfCatalog` emits compact UTF-8 JSON bytes. It follows these rules:
28
+
29
+ - It withholds `avc1` and `avc3` until non-empty init data exists. It derives the profile, constraint, and level suffix
30
+ from the avcC, and keeps `avc3` as `avc3`.
31
+ - It forces Opus to 48 kHz.
32
+ - It rejects empty or duplicate track names, and media roles on data tracks.
33
+ - Catalog namespaces use the player's slash-joined dialect, so it rejects a field that is empty or contains `/`. Source
34
+ URLs can escape a literal slash in a tuple field.
35
+ - Omitted fields never become JSON nulls. Empty init data is left out for every codec.
36
+ - Catalog strings must be valid Unicode, with no lone surrogates.
37
+
38
+ `buildMsfCatalog` describes a live broadcast and leaves `isComplete` out. msf-01 §5.1.3 forbids the field while it is
39
+ false, and once a catalog carries it, it can never be removed. To end a broadcast on purpose, follow msf-01 §11.3:
40
+
41
+ 1. Close the media tracks. Each close tells subscribers that the track ended.
42
+ 2. If the catalog track has demand, write `buildMsfEndCatalog({ generatedAt })` to it.
43
+ 3. Close the catalog track.
44
+
45
+ Do not send the end catalog after a crash or a lost connection.
46
+
47
+ `parseMsfCatalog` reads an independent catalog object's payload back into track descriptions. Each description has the
48
+ namespace tuple, name, packaging, live status, role, codec, dimensions, rates, bitrate, render group, and init data,
49
+ resolved from `initRef` to bytes. The parser rejects unsupported versions and delta updates, and ignores unknown fields.
50
+ It returns a packaging other than `loc`, such as moq-rs `cmaf`, as declared.
51
+
52
+ For simulcast layers or a second source, pass `media`, a list of `{ role: 'video', ... }` and `{ role: 'audio', ... }`
53
+ entries. Each entry takes an optional `renderGroup` and `altGroup`:
54
+
55
+ - `renderGroup` (default 1) names tracks that play together.
56
+ - `altGroup` names alternate versions of one content, of which a viewer plays one. Members of an alternate group share a
57
+ role and a render group.
58
+
59
+ `parseMsfCatalog` returns both fields, and `groupMsfTracks(catalog.tracks)` lists the sets that a viewer picks one track
60
+ from. See [several media tracks](https://github.com/caprids/relay-sdks/blob/main/spec/media-layer.md#several-media-tracks).
55
61
 
56
62
  ```ts
57
63
  const catalog = buildMsfCatalog({
@@ -65,41 +71,67 @@ const catalog = buildMsfCatalog({
65
71
  });
66
72
  ```
67
73
 
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.
74
+ ## LOC frames from WebCodecs
75
+
76
+ LOC helpers take nonnegative microsecond timestamps and a positive timescale, both safe integers (up to 2^53−1). A custom
77
+ timescale rounds to the nearest tick, with ties rounding up. Pass decoder configs only on keyframes, declare the same
78
+ timescale on the track, and keep the init data in the catalog too.
72
79
 
73
- The publisher path below works in Chromium, Firefox and Safari:
80
+ The primary browser input is native WebCodecs. The helpers use WebCodecs types but need no browser globals at import
81
+ time.
82
+
83
+ - `videoTrackFromDecoderConfig` maps an AVC decoder config with four-byte NAL lengths. A decoder config carries no
84
+ bitrate or framerate, so a caller that knows them spreads them into the returned `VideoTrackInfo`.
85
+ - `audioTrackFromDecoderConfig` maps an Opus decoder config.
86
+ - Both copy the description buffer, including the exact range of a view.
87
+ - `chunkToLocFrame` takes an `EncodedVideoChunk` or `EncodedAudioChunk` and returns
88
+ `{ payload, timestampUs, key, properties }`. It copies the encoded bytes unchanged and attaches supplied configs only
89
+ on key chunks. It takes the same `timescale` and config options as `locProperties`, plus an integer
90
+ `timestampOffsetUs` for a shared track timeline. The final timestamp must be a nonnegative safe integer. Keep chunks
91
+ in encoder output order, even when presentation timestamps are reordered.
92
+
93
+ TypeScript takes the decoder config and length-prefixed H.264 packets that an encoder or demuxer provides.
94
+ `avcCodecString` inspects the avcC header. It does not parse the SPS or validate a bitstream. TypeScript has no Annex B
95
+ parsing, SPS or PPS reconstruction, or access-unit conversion. Python keeps its Annex B helpers for the PyAV publisher.
96
+
97
+ See the [direct WebCodecs publishing example](https://github.com/caprids/relay-sdks/blob/main/ts/examples/webcodecs/README.md) for live browser video, catalog
98
+ serving, groups, bounded buffering, and cleanup. For files that need demuxing, use the optional
99
+ [Mediabunny packet adapter](https://github.com/caprids/relay-sdks/blob/main/ts/packages/moq-mediabunny/README.md).
100
+
101
+ ## Shared timeline and playout clock
102
+
103
+ Every media track shares one timeline. LOC timestamps are capture times in microseconds since the Unix epoch, with
104
+ Timescale 1,000,000 declared on each track. `createBroadcastClock()` pins the `performance.now()` clock to `Date.now()`
105
+ once and counts from there, so broadcasts from different publishers line up as closely as their system clocks do.
106
+
107
+ The publisher path below works in Chromium, Firefox, and Safari:
74
108
 
75
109
  - **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).
110
+ - **Audio.** Route the microphone through an `AudioContext` and an `AudioWorklet`. Stamp audio from the context clock
111
+ through `clock.sourceTimeline()`. Calibrate the source timeline with the context's render clock, a pair of a context
112
+ time and when it was rendered, taken from the worklet block that reached the main thread soonest after its render. Do
113
+ not calibrate from `getOutputTimestamp()`. Firefox returns that render pair shifted back by the output delay, which
114
+ stamps audio that much early. The WebCodecs example's `capture-microphone.ts` calibrates this way.
115
+ - **Device changes.** The context resamples whatever device is connected and keeps running while devices change, so
116
+ switching microphones does not shift the timeline.
117
+ - **Chromium alternative.** Where `MediaStreamTrackProcessor` exists, its timestamps count from the system's monotonic
118
+ zero, so map them through an uncalibrated `sourceTimeline()`.
119
+ - **Microphone latency.** No browser reports a microphone's own input latency. Measured on macOS, it is about 30 ms for
120
+ a MacBook's built-in microphone and 190 ms for AirPods. Set it as `captureLatencyUs` on the source timeline, at
121
+ creation or whenever the device changes, and the timeline subtracts it from every timestamp. See
122
+ [capture latency](https://github.com/caprids/relay-sdks/blob/main/spec/media-layer.md#capture-latency).
123
+
124
+ On the player, `createPlayoutClock()` makes audio the master. Report what is audible with `reportAudio(mediaUs, atUs)`:
125
+ the context time rendered now, less `baseLatency + outputLatency`. Read those two fresh on each report, because the
126
+ output delay changes with the device. Video calls `due(timestampUs)` and gets a `wait`, `show`, or `drop` decision. With
127
+ no audio, the clock paces by wall clock. Neither clock needs the DOM. See
128
+ [shared timeline and playout clock](https://github.com/caprids/relay-sdks/blob/main/spec/media-layer.md#shared-timeline-and-playout-clock).
97
129
 
98
130
  ```ts
99
131
  const clock = createBroadcastClock();
100
132
  const video = new VideoFrame(canvas, { timestamp: clock.now() });
101
133
 
102
- // AudioWorklet blocks carry their context time. `renderedUs` / `arrivedUs`: the best pair of the last second.
134
+ // AudioWorklet blocks carry their context time. `renderedUs` and `arrivedUs` are the best pair of the last second.
103
135
  const context = clock.sourceTimeline({ captureLatencyUs: 30_000 });
104
136
  context.calibrate(renderedUs, arrivedUs);
105
137
  const audioTimestampUs = context.timestampUs(blockContextUs);
@@ -112,18 +144,32 @@ const decision = playout.due(frame.timestamp);
112
144
  if (decision.action === 'wait') setTimeout(retry, decision.waitUs / 1000);
113
145
  ```
114
146
 
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.
147
+ ## Reading subscribed media
148
+
149
+ A subscriber reads an object's timestamp with `locTimestampUs(object.properties, { trackProperties })`, passing the
150
+ track properties from `subscription.subscribed`. It applies whichever Timescale the object or the track declares, rather
151
+ than assuming that the relay rescaled to microseconds.
118
152
 
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).
153
+ `createFrameSequencer({ clock })` turns one subscribed track's objects into frames in decode order. Objects can arrive
154
+ out of order across group streams, and the sequencer drops what is too late against the playout clock.
155
+ `createFrameReader` in `@caprid/relay/media` drives it from a subscription (see
156
+ [subscribing to media](https://github.com/caprids/relay-sdks/blob/main/ts/GUIDE.md#subscribing-to-media)). Per track, `lateDropUs`, `reorderWindowUs`, and
157
+ `catchUpAfterUs` tune audio delivery for a listener or for speech-to-text. `missingGroups` on a frame names the groups
158
+ skipped before it (see [voice delivery](https://github.com/caprids/relay-sdks/blob/main/ts/GUIDE.md#voice-delivery-per-direction)).
159
+
160
+ The combined `register_media` publishing handle is still a proposal in `spec/media-layer.md`. `@caprid/relay/media`
161
+ ships the frame writer and catalog service that it would compose.
162
+
163
+ ## Media timeline
164
+
165
+ msf-01's Media Timeline track maps media time to group locations, for seeking and playlists, with one record per video
166
+ group. On this timeline, media time is already wall-clock time, so a record's two times agree. Announce the track with
167
+ `mediaTimeline: {}` in `buildMsfCatalog`, which lists the video and audio tracks in its `depends`.
168
+
169
+ `createMediaTimeline` keeps one broadcast's records, 512 by default. Each time a keyframe has opened a video group,
170
+ `add` returns the document to send. Write it as a new timeline group, and again whenever the relay subscribes. The
171
+ [WebCodecs example](https://github.com/caprids/relay-sdks/blob/main/ts/examples/webcodecs/README.md) does this. See
172
+ [media timeline track](https://github.com/caprids/relay-sdks/blob/main/spec/media-layer.md#media-timeline-track).
127
173
 
128
174
  ```ts
129
175
  const timeline = createMediaTimeline();
@@ -133,56 +179,43 @@ if (timelineTrack.hasDemand) await timelineTrack.write(document); // one object,
133
179
  const read = parseMediaTimeline(timelineObject.payload);
134
180
  ```
135
181
 
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
182
  ## Audio playout
162
183
 
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
+ `createAudioPlayer({ context })` plays decoded audio with no UI. Each `player.addInput({ clock, decoderConfig })` takes
185
+ the frames it is pushed and does the following:
186
+
187
+ - It decodes them. Opus decodes with libopus compiled to WebAssembly, which fills a lost frame by packet-loss
188
+ concealment, or rebuilds it from the next frame's in-band FEC. Other codecs decode with WebCodecs, as does every input
189
+ when you pass `lossConcealment: false` or WebAssembly is unavailable. `audioDecoderConfigFromTrack` reads the decoder
190
+ config from a catalog track.
191
+ - It holds them in an adaptive jitter buffer in an `AudioWorklet`: 60 ms to start, adapting between 20 ms and 400 ms.
192
+ - It reports what is audible to the broadcast's playout clock.
193
+ - It plays them through its own gain into `player.output`, the one mix that the application routes.
194
+
195
+ Inputs and helpers:
196
+
197
+ - `input.cut({ fromUs, untilUs })` drops received audio in a timeline range.
198
+ - A talker's interrupt track (`INTERRUPT_TRACK`) carries cut ranges. Read one with `parseInterrupt`, and apply it with
199
+ `input.cut(parseInterrupt(object.payload))`. `buildInterrupt({ untilUs })` writes one.
200
+ - A talker's transcript track (`TRANSCRIPT_TRACK`) carries the text of its audio. Read each segment with
201
+ `parseTranscriptSegment` and keep the segments in `createTranscript()`. Cut the transcript on each interrupt with
202
+ `transcript.cut(interrupt, clock.position())`, and show `transcript.linesAt(clock.position())`.
203
+ `buildTranscriptSegment` writes a segment.
204
+ - `createEchoCancellationLoopback(context, node)` plays a node through a local WebRTC loopback, so Chromium's echo
205
+ canceller hears it.
206
+ - `input.playbackRate`, from 0.5 to 2, lets a player that owns its latency nudge it.
207
+ - An input's clock can be the player's own `AudioInputClock`. Each report passes it the input's stats, including
208
+ `playStarts`, `heldUntilUs`, and `dryAtUs`.
209
+ - `createRenderClock` times an `AudioContext`'s renders on the `performance.now()` clock, for capture and playout alike.
210
+
211
+ Give an audio-only broadcast's playout clock `AUDIO_ONLY_TARGET_LATENCY_US` (500 ms) as its `targetLatencyUs`. The 2 s
212
+ default waits for keyframe intervals.
213
+
214
+ The player takes structural Web Audio types, so it imports no DOM library. Its tests run under a fake context that runs
215
+ the real worklet. See [playing audio](https://github.com/caprids/relay-sdks/blob/main/ts/GUIDE.md#playing-audio) and
216
+ [audio player](https://github.com/caprids/relay-sdks/blob/main/spec/media-layer.md#audio-player).
184
217
 
185
218
  ## Stability
186
219
 
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).
220
+ Before 1.0, a minor version can break the API. This package releases together with `@caprid/relay` at the same version.
221
+ See the [changelog](https://github.com/caprids/relay-sdks/blob/main/ts/CHANGELOG.md).
@@ -1,7 +1,8 @@
1
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".
2
+ * A headless audio player: decodes each input's frames (Opus with libopus WebAssembly, other codecs with WebCodecs),
3
+ * holds them in an adaptive jitter buffer in an `AudioWorklet`, mixes every input into one output node, and reports
4
+ * what is audible to each input's playout clock. No UI and no transport: frames in, a node and clock reports out. See
5
+ * spec/media-layer.md, "Audio player".
5
6
  */
6
7
  import type { FrameDiscontinuity, SequencedFrame } from './sequencer.js';
7
8
  /** The part of an `AudioNode` the player uses. A Web Audio node qualifies. */
@@ -39,6 +40,14 @@ export interface AudioPlayerContext {
39
40
  export interface AudioPlayerOptions<Context extends AudioPlayerContext> {
40
41
  /** The one context every input plays through. Create or resume it from a user gesture. */
41
42
  context: Context;
43
+ /**
44
+ * Fill lost Opus frames instead of playing silence. Default true: Opus inputs decode with libopus compiled to
45
+ * WebAssembly, which conceals a missing frame (packet-loss concealment) and rebuilds it from the next frame's in-band
46
+ * FEC when the encoder sent one; WebCodecs' AudioDecoder can do neither. False, or where WebAssembly is
47
+ * unavailable: every input decodes with WebCodecs, and a lost frame plays as silence. Other codecs always use
48
+ * WebCodecs.
49
+ */
50
+ lossConcealment?: boolean;
42
51
  }
43
52
  /** One encoded audio frame: a `SequencedFrame` from a frame reader qualifies. */
44
53
  export type AudioPlayerFrame = Pick<SequencedFrame, 'timestampUs' | 'payload'> & {
@@ -78,7 +87,7 @@ export interface AudioInputOptions {
78
87
  playbackRate?: number;
79
88
  /** How much audio to hold before playing, at the start and after each underrun. Default 60,000. */
80
89
  jitterTargetUs?: number;
81
- /** The least the target shrinks to while playback is smooth. Default 40,000. */
90
+ /** The least the target shrinks to while playback is smooth. Default 20,000. */
82
91
  minJitterTargetUs?: number;
83
92
  /**
84
93
  * The most the target grows to after underruns. Default 400,000, and never more than the clock's target latency
@@ -130,6 +139,10 @@ export interface AudioInputStats {
130
139
  trimmedUs: number;
131
140
  /** Silence played in place of frames that never came. */
132
141
  concealedUs: number;
142
+ /** Audio synthesized in place of frames that never came: libopus packet-loss concealment. */
143
+ synthesizedUs: number;
144
+ /** Audio rebuilt for frames that never came from the next frame's in-band FEC. */
145
+ recoveredUs: number;
133
146
  /** Audio dropped by `cut()`. */
134
147
  cutUs: number;
135
148
  /** Clock reports made. */
@@ -1 +1 @@
1
- {"version":3,"file":"audio-player.d.ts","sourceRoot":"","sources":["../src/audio-player.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAWH,OAAO,KAAK,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEzE,8EAA8E;AAC9E,MAAM,WAAW,eAAe;IAC9B,gDAAgD;IAChD,OAAO,CAAC,WAAW,EAAE,eAAe,GAAG,OAAO,CAAC;IAC/C,yDAAyD;IACzD,UAAU,CAAC,WAAW,CAAC,EAAE,eAAe,GAAG,IAAI,CAAC;CACjD;AAED,gDAAgD;AAChD,MAAM,WAAW,mBAAoB,SAAQ,eAAe;IAC1D,+CAA+C;IAC/C,QAAQ,CAAC,IAAI,EAAE;QACb,gDAAgD;QAChD,KAAK,EAAE,MAAM,CAAC;KACf,CAAC;CACH;AAED,2FAA2F;AAC3F,MAAM,WAAW,kBAAkB;IACjC,kGAAkG;IAClG,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,yDAAyD;IACzD,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,gFAAgF;IAChF,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,0DAA0D;IAC1D,QAAQ,CAAC,YAAY,EAAE;QACrB,wCAAwC;QACxC,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;KACvC,CAAC;IACF,yDAAyD;IACzD,UAAU,IAAI,mBAAmB,CAAC;CACnC;AAED,6CAA6C;AAC7C,MAAM,WAAW,kBAAkB,CAAC,OAAO,SAAS,kBAAkB;IACpE,0FAA0F;IAC1F,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,iFAAiF;AACjF,MAAM,MAAM,gBAAgB,GAAG,IAAI,CAAC,cAAc,EAAE,aAAa,GAAG,SAAS,CAAC,GAAG;IAC/E,iHAAiH;IACjH,aAAa,CAAC,EAAE,kBA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