@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
@@ -0,0 +1,134 @@
1
+ // biome-ignore-all lint/complexity/useLiteralKeys: TypeScript requires bracket access for index signatures.
2
+ /** Independent MSF catalog reader, extracted from Video.js parse-catalog.ts. */
3
+ function isString(value) {
4
+ return typeof value === 'string';
5
+ }
6
+ function isPlainObject(value) {
7
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
8
+ }
9
+ function pruneUndefined(value) {
10
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
11
+ }
12
+ function base64ToBytes(base64) {
13
+ const binary = atob(base64);
14
+ const bytes = new Uint8Array(binary.length);
15
+ for (let i = 0; i < binary.length; i++)
16
+ bytes[i] = binary.charCodeAt(i);
17
+ return bytes;
18
+ }
19
+ /**
20
+ * Split a catalog namespace string into its tuple fields. msf-01 does not say how a tuple is spelled in catalog
21
+ * JSON; this dialect (Video.js, and `buildMsfCatalog`) joins the fields with `/`, which the builder therefore
22
+ * rejects inside a field. Empty fields are dropped.
23
+ */
24
+ function parseNamespaceString(namespace) {
25
+ return namespace.split('/').filter((field) => field.length > 0);
26
+ }
27
+ function parseInitDataList(raw) {
28
+ const initData = new Map();
29
+ if (!Array.isArray(raw))
30
+ return initData;
31
+ for (const entry of raw) {
32
+ if (!isPlainObject(entry))
33
+ continue;
34
+ const { id, type, data } = entry;
35
+ if (!isString(id) || !isString(data))
36
+ continue;
37
+ if (type !== undefined && type !== 'inline')
38
+ continue;
39
+ initData.set(id, base64ToBytes(data));
40
+ }
41
+ return initData;
42
+ }
43
+ const number = (value) => (typeof value === 'number' ? value : undefined);
44
+ /** Counts (pixels, bits per second, hertz, milliseconds) are read only when integral. */
45
+ const integer = (value) => (Number.isInteger(value) ? value : undefined);
46
+ const string = (value) => (isString(value) ? value : undefined);
47
+ function parseCatalogTrack(raw, catalogNamespace, initDataList) {
48
+ const name = raw['name'];
49
+ if (!isString(name))
50
+ return null;
51
+ const initRef = string(raw['initRef']);
52
+ return {
53
+ namespace: isString(raw['namespace']) ? parseNamespaceString(raw['namespace']) : [...catalogNamespace],
54
+ name,
55
+ packaging: string(raw['packaging']) ?? '',
56
+ isLive: raw['isLive'] === true,
57
+ ...pruneUndefined({
58
+ role: string(raw['role']),
59
+ codec: string(raw['codec']),
60
+ width: integer(raw['width']),
61
+ height: integer(raw['height']),
62
+ framerate: number(raw['framerate']),
63
+ samplerate: integer(raw['samplerate']),
64
+ channelConfig: string(raw['channelConfig']),
65
+ bitrate: integer(raw['bitrate']),
66
+ renderGroup: integer(raw['renderGroup']),
67
+ altGroup: integer(raw['altGroup']),
68
+ mimetype: string(raw['mimetype']),
69
+ depends: Array.isArray(raw['depends']) ? raw['depends'].filter(isString) : undefined,
70
+ initData: initRef === undefined ? undefined : initDataList.get(initRef),
71
+ }),
72
+ };
73
+ }
74
+ // §5.1.1: a subscriber MUST NOT parse a catalog version it does not understand. Versions follow the 'draft-XX'
75
+ // convention; the bare '1' is a lenient alias deployed producers emit.
76
+ const SUPPORTED_MSF_VERSIONS = new Set(['draft-01', '1']);
77
+ /**
78
+ * Read an independent MSF catalog object's payload into its track descriptions.
79
+ *
80
+ * Throws on a payload that is not a UTF-8 JSON object, a missing or unsupported `version`, a missing `tracks` array,
81
+ * or a delta update (`deltaUpdate`, not supported). Everything else is lenient, as msf-01 requires: unknown fields
82
+ * and fields of the wrong type are ignored, track entries without a string `name` are skipped, and packaging is
83
+ * returned as declared, not interpreted.
84
+ */
85
+ export function parseMsfCatalog(payload, options) {
86
+ const raw = JSON.parse(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(payload));
87
+ if (!isPlainObject(raw))
88
+ throw new Error('MSF catalog is not a JSON object');
89
+ if (raw['deltaUpdate'] !== undefined)
90
+ throw new Error('MSF delta updates are not supported');
91
+ if (!isString(raw['version']))
92
+ throw new Error('MSF catalog is missing its version');
93
+ if (!SUPPORTED_MSF_VERSIONS.has(raw['version'])) {
94
+ throw new Error(`unsupported MSF catalog version ${raw['version']}`);
95
+ }
96
+ if (!Array.isArray(raw['tracks']))
97
+ throw new Error('MSF catalog is missing its tracks array');
98
+ const initDataList = parseInitDataList(raw['initDataList']);
99
+ const tracks = raw['tracks']
100
+ .filter(isPlainObject)
101
+ .map((entry) => parseCatalogTrack(entry, options.catalogNamespace, initDataList))
102
+ .filter((track) => track !== null);
103
+ const generatedAt = integer(raw['generatedAt']);
104
+ return {
105
+ version: raw['version'],
106
+ ...(generatedAt === undefined ? {} : { generatedAt }),
107
+ isComplete: raw['isComplete'] === true,
108
+ tracks,
109
+ };
110
+ }
111
+ /**
112
+ * Group catalog tracks into the sets a viewer picks one track from, in order of each set's first track: tracks
113
+ * sharing a render group and an alternate group form one set, and every other track is a set of its own. A viewer
114
+ * plays one track from each set of a render group, and moves between alternates with `want(..., { until })`.
115
+ */
116
+ export function groupMsfTracks(tracks) {
117
+ const groups = [];
118
+ const alternates = new Map();
119
+ for (const track of tracks) {
120
+ const { renderGroup, altGroup } = track;
121
+ const key = altGroup === undefined ? undefined : `${renderGroup ?? ''}/${altGroup}`;
122
+ const existing = key === undefined ? undefined : alternates.get(key);
123
+ if (existing) {
124
+ existing.tracks.push(track);
125
+ continue;
126
+ }
127
+ const group = { ...pruneUndefined({ renderGroup, altGroup }), tracks: [track] };
128
+ groups.push(group);
129
+ if (key !== undefined)
130
+ alternates.set(key, group);
131
+ }
132
+ return groups;
133
+ }
134
+ //# sourceMappingURL=parse-catalog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parse-catalog.js","sourceRoot":"","sources":["../src/parse-catalog.ts"],"names":[],"mappings":"AAAA,4GAA4G;AAC5G,gFAAgF;AAChF,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC;AACnC,CAAC;AACD,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AACD,SAAS,cAAc,CAAmB,KAAQ;IAChD,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,CAEzF,CAAC;AACJ,CAAC;AA0DD,SAAS,aAAa,CAAC,MAAc;IACnC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;IAC5B,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAE5C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAExE,OAAO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AAQ,EAAE,CAAC;QACpF,MAAM,QAAQ,GAAG,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACrE,IAAI,QAAQ,EAAE,CAAC;YACb,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAC5B,SAAS;QACX,CAAC;QACD,MAAM,KAAK,GAAkB,EAAE,GAAG,cAAc,CAAC,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC;QAC/F,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACnB,IAAI,GAAG,KAAK,SAAS;YAAE,UAAU,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACpD,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * When an `AudioContext` renders, on `performance.now()`'s clock. Every engine exposes the context's render position
3
+ * as `currentTime` (or as `currentFrame` inside an `AudioWorklet`), and anything that observes it from the main thread
4
+ * sees it late by however long the observation took to arrive: a message from the worklet, or the main thread's own
5
+ * turn. The earliest observation in a short window is the best estimate of when the context rendered.
6
+ *
7
+ * Why not `AudioContext.getOutputTimestamp()`: Chromium returns the context time reaching the speaker and when, as the
8
+ * Web Audio spec says. Firefox (148) returns `currentTime − outputLatency` and `performance.now() − outputLatency`,
9
+ * which is the render pair shifted by the output delay, and it steps with each audio callback. A recipe that adds the
10
+ * output delay to `contextTime` is right in Chromium and stamps audio early by the output delay in Firefox.
11
+ */
12
+ /** One observation: context time `contextUs` had been rendered by `atUs` on `performance.now()`'s clock. */
13
+ export interface RenderObservation {
14
+ /** Context time, in microseconds: `currentTime × 1e6`, or a worklet frame count over its sample rate. */
15
+ contextUs: number;
16
+ /** When it was observed, in `performance.now()` microseconds. */
17
+ atUs: number;
18
+ }
19
+ /** Options for {@link createRenderClock}. */
20
+ export interface RenderClockOptions {
21
+ /** How long an observation is kept, in µs. Default 1,000,000: drift over a second is far below a millisecond. */
22
+ windowUs?: number;
23
+ }
24
+ /** The context's render clock against `performance.now()`, from the earliest observation in a sliding window. */
25
+ export interface RenderClock {
26
+ /** Record an observation. Observations must arrive in `atUs` order. */
27
+ observe(contextUs: number, atUs: number): void;
28
+ /**
29
+ * The observation in the window that arrived soonest after its render, as a calibration pair for
30
+ * `SourceTimeline.calibrate(contextUs, atUs)`; `undefined` before the first observation.
31
+ */
32
+ best(): RenderObservation | undefined;
33
+ /** When context time `contextUs` renders, in `performance.now()` microseconds; `undefined` before any observation. */
34
+ renderedAtUs(contextUs: number): number | undefined;
35
+ }
36
+ /** Create a render clock for one `AudioContext`. A replaced context needs a new one: its time restarts at zero. */
37
+ export declare function createRenderClock({ windowUs }?: RenderClockOptions): RenderClock;
38
+ //# sourceMappingURL=render-clock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-clock.d.ts","sourceRoot":"","sources":["../src/render-clock.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,4GAA4G;AAC5G,MAAM,WAAW,iBAAiB;IAChC,yGAAyG;IACzG,SAAS,EAAE,MAAM,CAAC;IAClB,iEAAiE;IACjE,IAAI,EAAE,MAAM,CAAC;CACd;AAED,6CAA6C;AAC7C,MAAM,WAAW,kBAAkB;IACjC,iHAAiH;IACjH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,iHAAiH;AACjH,MAAM,WAAW,WAAW;IAC1B,uEAAuE;IACvE,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/C;;;OAGG;IACH,IAAI,IAAI,iBAAiB,GAAG,SAAS,CAAC;IACtC,sHAAsH;IACtH,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;CACrD;AAED,mHAAmH;AACnH,wBAAgB,iBAAiB,CAAC,EAAE,QAAoB,EAAE,GAAE,kBAAuB,GAAG,WAAW,CAsBhG"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * When an `AudioContext` renders, on `performance.now()`'s clock. Every engine exposes the context's render position
3
+ * as `currentTime` (or as `currentFrame` inside an `AudioWorklet`), and anything that observes it from the main thread
4
+ * sees it late by however long the observation took to arrive: a message from the worklet, or the main thread's own
5
+ * turn. The earliest observation in a short window is the best estimate of when the context rendered.
6
+ *
7
+ * Why not `AudioContext.getOutputTimestamp()`: Chromium returns the context time reaching the speaker and when, as the
8
+ * Web Audio spec says. Firefox (148) returns `currentTime − outputLatency` and `performance.now() − outputLatency`,
9
+ * which is the render pair shifted by the output delay, and it steps with each audio callback. A recipe that adds the
10
+ * output delay to `contextTime` is right in Chromium and stamps audio early by the output delay in Firefox.
11
+ */
12
+ /** Create a render clock for one `AudioContext`. A replaced context needs a new one: its time restarts at zero. */
13
+ export function createRenderClock({ windowUs = 1_000_000 } = {}) {
14
+ if (!(windowUs > 0))
15
+ throw new RangeError('windowUs must be positive');
16
+ // A monotonic deque: lags (atUs − contextUs) increase from front to back, so the front is the window's minimum.
17
+ const kept = [];
18
+ const lag = (observation) => observation.atUs - observation.contextUs;
19
+ return {
20
+ observe(contextUs, atUs) {
21
+ if (!Number.isFinite(contextUs) || !Number.isFinite(atUs))
22
+ throw new RangeError('Observations must be finite');
23
+ const observation = { contextUs, atUs };
24
+ while (kept.length > 0 && lag(kept[kept.length - 1]) >= lag(observation))
25
+ kept.pop();
26
+ kept.push(observation);
27
+ while (kept[0].atUs < atUs - windowUs)
28
+ kept.shift();
29
+ },
30
+ best() {
31
+ const first = kept[0];
32
+ return first && { ...first };
33
+ },
34
+ renderedAtUs(contextUs) {
35
+ const first = kept[0];
36
+ return first && contextUs + lag(first);
37
+ },
38
+ };
39
+ }
40
+ //# sourceMappingURL=render-clock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-clock.js","sourceRoot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YACtB,OAAO,KAAK,IAAI,SAAS,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC;QACzC,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The frame sequencer: turns one track's objects, which arrive in any order across group streams, into frames in
3
+ * decode order, and drops what is too late against a playout clock. It is the engine of a frame reader; it has no
4
+ * timers and no transport. See spec/behavior.md, "Media subscribing".
5
+ */
6
+ import type { KeyValuePair, MoqtObject } from '@caprid/moq-core';
7
+ import type { PlayoutClock } from './clock.js';
8
+ /** Why the frame is not the one decoded after the frame before it. A decoder resets there. */
9
+ export type FrameDiscontinuity =
10
+ /** Frames before this one were skipped: missing, reset, or too late. */
11
+ 'gap'
12
+ /** Nothing arrived within the target latency for one target latency; the sequencer reset the clock. */
13
+ | 'resync'
14
+ /** The subscription was replaced: a want's Restart or Move. */
15
+ | 'restart';
16
+ /** One frame in decode order. */
17
+ export interface SequencedFrame {
18
+ /** The object's group. */
19
+ groupId: number;
20
+ /** The object's ID within its group. */
21
+ objectId: number;
22
+ /** The LOC timestamp in microseconds on the broadcast timeline. */
23
+ timestampUs: number;
24
+ /** Whether the frame starts its group: a keyframe under keyframe grouping, every frame under frame grouping. */
25
+ key: boolean;
26
+ /** The object payload. */
27
+ payload: Uint8Array;
28
+ /** The object properties as received. */
29
+ properties: KeyValuePair[];
30
+ /** Set on the first frame after a skip, a resync, or a restart. */
31
+ discontinuity?: FrameDiscontinuity;
32
+ /**
33
+ * The groups between the last frame delivered and this one of which nothing was delivered: never received, reset, or
34
+ * dropped as late or behind. Inclusive bounds. Absent when no group ID was skipped, and on the first frame after a
35
+ * restart, since group IDs start over there.
36
+ */
37
+ missingGroups?: MissingGroups;
38
+ }
39
+ /** An inclusive range of group IDs of which nothing was delivered: what an application may act on, such as a FETCH. */
40
+ export interface MissingGroups {
41
+ /** The first group ID missing. */
42
+ firstGroupId: number;
43
+ /** The last group ID missing. */
44
+ lastGroupId: number;
45
+ }
46
+ /** Options for {@link createFrameSequencer}. */
47
+ export interface FrameSequencerOptions {
48
+ /** The broadcast's playout clock. It holds the target latency and is where lateness is measured. */
49
+ clock: PlayoutClock;
50
+ /**
51
+ * `'keyframe'` (default): a keyframe opens each group and later objects depend on it, as video. `'frame'`: every
52
+ * group is independently decodable, as audio.
53
+ */
54
+ grouping?: 'keyframe' | 'frame';
55
+ /** The track properties from SUBSCRIBE_OK, which may declare the Timescale. */
56
+ trackProperties?: readonly KeyValuePair[];
57
+ /**
58
+ * Frame grouping only: how far behind the clock's position a frame may still be delivered, in microseconds. Default:
59
+ * the clock's `lateDropUs`, which every track on the clock shares. A listener set to drop late audio sets it near
60
+ * its playout target; a reader that wants every frame, such as speech-to-text, sets `Infinity`. Not negative.
61
+ */
62
+ lateDropUs?: number;
63
+ /**
64
+ * Frame grouping only: how long, in microseconds of the clock's local time, a frame waits for an earlier group that
65
+ * has not arrived, counted from when the frame arrived. Default 0: frames go out at once and an earlier group that
66
+ * arrives after a later one is dropped as behind. A frame that turns late while it waits is dropped as late. For a
67
+ * reader that wants every frame of a talker, set it to at least the publisher's delivery timeout: a group the
68
+ * publisher's transport is still resending can arrive that long after the group that follows it. Finite, not
69
+ * negative.
70
+ */
71
+ reorderWindowUs?: number;
72
+ /**
73
+ * Signal a catch-up when frames keep arriving late with none delivered: from the first frame dropped as late to the
74
+ * latest is at least this long, in microseconds of the clock's local time. Late means past the late-drop limit
75
+ * (frame grouping) or the target latency (keyframe grouping), as when a relay holds a growing backlog for this
76
+ * subscriber. The poll after that frame returns `catchUp: true`, once, until a frame is delivered again; whoever owns
77
+ * the subscription then replaces it at the live edge (a supervised subscriber's `catchUp(key)`), which drops the
78
+ * relay's backlog, and restarts the sequencer. Set it below the clock's target latency, or a resync re-anchors on
79
+ * the late frames first. Default: never. Positive and finite.
80
+ */
81
+ catchUpAfterUs?: number;
82
+ }
83
+ /** What {@link FrameSequencer.poll} returns. */
84
+ export interface SequencerPoll {
85
+ /** The frames ready now, in decode order. */
86
+ frames: SequencedFrame[];
87
+ /**
88
+ * Poll again after this many microseconds, when a wait can end; 0 when more is ready now (past `maxFrames`, or a
89
+ * resync that takes a poll of its own); `undefined` when only new objects can change it.
90
+ */
91
+ waitUs: number | undefined;
92
+ /** Present, and `true`, on the one poll that signals a catch-up: see {@link FrameSequencerOptions.catchUpAfterUs}. */
93
+ catchUp?: true;
94
+ }
95
+ /** Counters, cumulative across restarts. */
96
+ export interface FrameSequencerStats {
97
+ /** Frames returned by `poll()`. */
98
+ delivered: number;
99
+ /** Frames discarded: too late, or behind what was already delivered. */
100
+ late: number;
101
+ /** Groups abandoned or passed over without being delivered whole. */
102
+ skippedGroups: number;
103
+ /** Resyncs: deliveries after nothing arrived within the target latency. */
104
+ resyncs: number;
105
+ /** Objects without a LOC timestamp, which cannot be sequenced. */
106
+ untimed: number;
107
+ }
108
+ /** One track's frame sequencer. Feed it the subscription's events, then `poll()` for frames. */
109
+ export interface FrameSequencer {
110
+ /** The track properties used to read timestamps; set from each SUBSCRIBE_OK. */
111
+ trackProperties: readonly KeyValuePair[];
112
+ /** An object arrived. */
113
+ object(object: MoqtObject): void;
114
+ /** A group's stream ended cleanly: no further objects of it will come. */
115
+ groupEnded(groupId: number): void;
116
+ /** A group's stream was reset: its remaining objects will not come. */
117
+ groupReset(groupId: number): void;
118
+ /** The subscription was replaced (a Restart or a Move): forget everything and reset the clock; group IDs start over. */
119
+ restart(): void;
120
+ /**
121
+ * Take the frames that are ready, at most `maxFrames` (default all), and when to poll again. A reader that cannot
122
+ * take frames as they come polls one at a time, so each is judged late when it is taken.
123
+ */
124
+ poll(maxFrames?: number): SequencerPoll;
125
+ /** Counters. */
126
+ readonly stats: Readonly<FrameSequencerStats>;
127
+ }
128
+ /** Create a frame sequencer for one track. */
129
+ export declare function createFrameSequencer(options: FrameSequencerOptions): FrameSequencer;
130
+ //# sourceMappingURL=sequencer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sequencer.d.ts","sourceRoot":"","sources":["../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