@blockcast/mmt-render 0.1.0-main.0399efef1f07

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 (76) hide show
  1. package/README.md +207 -0
  2. package/dist/.build-stamp +0 -0
  3. package/dist/audio/audio-buffer-plan.d.ts +27 -0
  4. package/dist/audio/audio-buffer-plan.d.ts.map +1 -0
  5. package/dist/audio/audio-render-pipeline.d.ts +83 -0
  6. package/dist/audio/audio-render-pipeline.d.ts.map +1 -0
  7. package/dist/audio/audio-render-pipeline.js +396 -0
  8. package/dist/audio/audio-render-pipeline.js.map +7 -0
  9. package/dist/audio/audio-ring-buffer.d.ts +55 -0
  10. package/dist/audio/audio-ring-buffer.d.ts.map +1 -0
  11. package/dist/audio/audio-ring-buffer.js +255 -0
  12. package/dist/audio/audio-ring-buffer.js.map +7 -0
  13. package/dist/audio/index.d.ts +9 -0
  14. package/dist/audio/index.d.ts.map +1 -0
  15. package/dist/audio/index.js +664 -0
  16. package/dist/audio/index.js.map +7 -0
  17. package/dist/audio/render-messages.d.ts +94 -0
  18. package/dist/audio/render-messages.d.ts.map +1 -0
  19. package/dist/audio/render-messages.js +1 -0
  20. package/dist/audio/render-messages.js.map +7 -0
  21. package/dist/audio/render-worklet.d.ts +13 -0
  22. package/dist/audio/render-worklet.d.ts.map +1 -0
  23. package/dist/audio/worklet-url.d.ts +25 -0
  24. package/dist/audio/worklet-url.d.ts.map +1 -0
  25. package/dist/audio/worklet-url.js +11 -0
  26. package/dist/audio/worklet-url.js.map +7 -0
  27. package/dist/index.d.ts +13 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +5 -0
  30. package/dist/index.js.map +7 -0
  31. package/dist/pacing/au-duration.d.ts +18 -0
  32. package/dist/pacing/au-duration.d.ts.map +1 -0
  33. package/dist/pacing/au-duration.js +23 -0
  34. package/dist/pacing/au-duration.js.map +7 -0
  35. package/dist/pacing/frame-pacer.d.ts +92 -0
  36. package/dist/pacing/frame-pacer.d.ts.map +1 -0
  37. package/dist/pacing/frame-pacer.js +113 -0
  38. package/dist/pacing/frame-pacer.js.map +7 -0
  39. package/dist/pacing/index.d.ts +6 -0
  40. package/dist/pacing/index.d.ts.map +1 -0
  41. package/dist/pacing/index.js +190 -0
  42. package/dist/pacing/index.js.map +7 -0
  43. package/dist/pacing/interleave-timing.d.ts +64 -0
  44. package/dist/pacing/interleave-timing.d.ts.map +1 -0
  45. package/dist/pacing/interleave-timing.js +58 -0
  46. package/dist/pacing/interleave-timing.js.map +7 -0
  47. package/dist/video/index.d.ts +4 -0
  48. package/dist/video/index.d.ts.map +1 -0
  49. package/dist/video/index.js +271 -0
  50. package/dist/video/index.js.map +7 -0
  51. package/dist/video/keyframe-gate.d.ts +21 -0
  52. package/dist/video/keyframe-gate.d.ts.map +1 -0
  53. package/dist/video/keyframe-gate.js +39 -0
  54. package/dist/video/keyframe-gate.js.map +7 -0
  55. package/dist/video/video-render-pipeline.d.ts +60 -0
  56. package/dist/video/video-render-pipeline.d.ts.map +1 -0
  57. package/dist/video/video-render-pipeline.js +271 -0
  58. package/dist/video/video-render-pipeline.js.map +7 -0
  59. package/dist/worklet/render-worklet.js +403 -0
  60. package/dist/worklet/render-worklet.js.map +7 -0
  61. package/package.json +101 -0
  62. package/src/audio/audio-buffer-plan.ts +62 -0
  63. package/src/audio/audio-render-pipeline.ts +313 -0
  64. package/src/audio/audio-ring-buffer.ts +281 -0
  65. package/src/audio/index.ts +14 -0
  66. package/src/audio/render-messages.ts +110 -0
  67. package/src/audio/render-worklet.ts +161 -0
  68. package/src/audio/worklet-url.ts +30 -0
  69. package/src/index.ts +13 -0
  70. package/src/pacing/au-duration.ts +34 -0
  71. package/src/pacing/frame-pacer.ts +156 -0
  72. package/src/pacing/index.ts +5 -0
  73. package/src/pacing/interleave-timing.ts +95 -0
  74. package/src/video/index.ts +7 -0
  75. package/src/video/keyframe-gate.ts +35 -0
  76. package/src/video/video-render-pipeline.ts +179 -0
@@ -0,0 +1,6 @@
1
+ export { FrameCountPacer } from './frame-pacer.js';
2
+ export type { FrameCountPacerOpts, PacerSnapshot } from './frame-pacer.js';
3
+ export { InterleaveTiming } from './interleave-timing.js';
4
+ export type { InterleaveTimingOpts } from './interleave-timing.js';
5
+ export { auDurationMsFromCodec, pictureDurationMs } from './au-duration.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/pacing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAClD,YAAY,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA;AAC1E,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AACzD,YAAY,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAA;AAClE,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAA"}
@@ -0,0 +1,190 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+ var __privateWrapper = (obj, member, setter, getter) => ({
9
+ set _(value) {
10
+ __privateSet(obj, member, value, setter);
11
+ },
12
+ get _() {
13
+ return __privateGet(obj, member, getter);
14
+ }
15
+ });
16
+
17
+ // src/pacing/frame-pacer.ts
18
+ var _frameCount, _anchorWallMs, _anchored;
19
+ var FrameCountPacer = class {
20
+ constructor(opts) {
21
+ __privateAdd(this, _frameCount, 0);
22
+ __privateAdd(this, _anchorWallMs, 0);
23
+ __privateAdd(this, _anchored, false);
24
+ if (!(opts.frameDurationMs > 0)) {
25
+ throw new Error("frameDurationMs must be > 0");
26
+ }
27
+ this.frameDurationMs = opts.frameDurationMs;
28
+ this.thresholdMs = opts.mapper.pacingThresholdMs;
29
+ this.warmupFrames = Math.max(0, opts.warmupFrames ?? 0);
30
+ }
31
+ /** Call on every emitted decoded frame (AU or picture). Anchors on first call. */
32
+ notifyFrame() {
33
+ if (!__privateGet(this, _anchored)) {
34
+ __privateSet(this, _anchorWallMs, now());
35
+ __privateSet(this, _anchored, true);
36
+ }
37
+ __privateWrapper(this, _frameCount)._++;
38
+ }
39
+ /**
40
+ * Compute sleep ms before reading the next MoQ object.
41
+ * Returns 0 when:
42
+ * - pacing is disabled (NullBlockMapper → threshold=0)
43
+ * - the anchor is not yet set
44
+ * - still in warmup
45
+ * - the caller reports a standing backlog (see `observedDelayMs`)
46
+ * - decoder is not ahead of wall clock by more than threshold
47
+ * Otherwise returns aheadMs - thresholdMs/2 (leaves half the threshold as headroom).
48
+ *
49
+ * `observedDelayMs` is how far this frame is behind the producer's own clock,
50
+ * measured by the caller against a producer-supplied sending instant (for
51
+ * MMTP, the header send-wall timestamp). It is optional because the anchored
52
+ * rate below is blind to it: `#anchorWallMs` is the wall time of the FIRST
53
+ * frame read, so `aheadMs` measures consumption against the join instant and
54
+ * not against the producer. Once `aheadMs` reaches the threshold the loop
55
+ * consumes at exactly the source rate, and recovering latency present at join
56
+ * requires consuming FASTER than the source rate. So without this argument a
57
+ * consumer that joined a live stream mid-block keeps that join latency for the
58
+ * life of the subscription.
59
+ *
60
+ * A caller that can measure the real distance from the producer passes it and
61
+ * gets a drain: while the backlog exceeds the threshold there is nothing to
62
+ * pace against, so return 0 and let the transport set the rate. At the live
63
+ * edge the anchored-rate behavior below applies unchanged.
64
+ *
65
+ * Callers with no producer clock omit it and keep the pure ATSC3-style
66
+ * anchored pacing (see the class doc), where a first-frame anchor is correct
67
+ * because a broadcast push has no live edge to catch up to.
68
+ */
69
+ computeSleepMs(observedDelayMs) {
70
+ if (this.thresholdMs <= 0) return 0;
71
+ if (!__privateGet(this, _anchored)) return 0;
72
+ if (__privateGet(this, _frameCount) <= this.warmupFrames) return 0;
73
+ if (observedDelayMs !== void 0 && Number.isFinite(observedDelayMs) && observedDelayMs > this.thresholdMs) {
74
+ return 0;
75
+ }
76
+ const mediaMs = __privateGet(this, _frameCount) * this.frameDurationMs;
77
+ const wallMs = now() - __privateGet(this, _anchorWallMs);
78
+ const aheadMs = mediaMs - wallMs;
79
+ if (aheadMs <= this.thresholdMs) return 0;
80
+ return aheadMs - this.thresholdMs / 2;
81
+ }
82
+ /** Reset anchor + counter. Call on source switch (MoQ ↔ multicast). */
83
+ reset() {
84
+ __privateSet(this, _frameCount, 0);
85
+ __privateSet(this, _anchorWallMs, 0);
86
+ __privateSet(this, _anchored, false);
87
+ }
88
+ get snapshot() {
89
+ const mediaMs = __privateGet(this, _frameCount) * this.frameDurationMs;
90
+ const wallMs = __privateGet(this, _anchored) ? now() - __privateGet(this, _anchorWallMs) : 0;
91
+ return {
92
+ frameCount: __privateGet(this, _frameCount),
93
+ mediaMs,
94
+ wallMs,
95
+ aheadMs: mediaMs - wallMs,
96
+ thresholdMs: this.thresholdMs,
97
+ anchored: __privateGet(this, _anchored)
98
+ };
99
+ }
100
+ };
101
+ _frameCount = new WeakMap();
102
+ _anchorWallMs = new WeakMap();
103
+ _anchored = new WeakMap();
104
+ function now() {
105
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
106
+ return performance.now();
107
+ }
108
+ return Date.now();
109
+ }
110
+
111
+ // src/pacing/interleave-timing.ts
112
+ var InterleaveTiming = class {
113
+ constructor(opts) {
114
+ if (!(opts.frameDurationUs > 0)) {
115
+ throw new Error("frameDurationUs must be > 0");
116
+ }
117
+ if (!Number.isFinite(opts.anchorMpuUs)) {
118
+ throw new Error("anchorMpuUs must be finite");
119
+ }
120
+ this.mapper = opts.mapper;
121
+ this.frameDurationUs = opts.frameDurationUs;
122
+ this.anchorMpuUs = opts.anchorMpuUs;
123
+ }
124
+ /**
125
+ * Presentation time (µs) for an AU at MoQ coords (group_id, object_id).
126
+ * Per draft §8.3 + Sony anchor.
127
+ */
128
+ presentationUs(groupId, objectId) {
129
+ const coords = this.mapper.derive(groupId, objectId);
130
+ return this.anchorMpuUs + coords.ssId * this.frameDurationUs;
131
+ }
132
+ /**
133
+ * Presentation time (µs) for an AU identified by its flat SS_ID
134
+ * (multicast FEC Payload ID path).
135
+ */
136
+ presentationUsFromSsId(ssId) {
137
+ return this.anchorMpuUs + ssId * this.frameDurationUs;
138
+ }
139
+ /**
140
+ * Inverse: which (group_id, object_id) AU is scheduled at the given
141
+ * wall offset (µs) from anchor? Clamps to ssId≥0.
142
+ */
143
+ frameAtOffset(offsetUs) {
144
+ const rawSsId = Math.max(0, Math.floor(offsetUs / this.frameDurationUs));
145
+ const { sbn, esi } = this.mapper.fromSsId(rawSsId);
146
+ const spg = this.mapper.symbolsPerGroup;
147
+ const groupInBlock = Math.floor(esi / spg);
148
+ const objectId = esi - groupInBlock * spg;
149
+ const groupId = sbn * this.mapper.d + groupInBlock;
150
+ return { groupId, objectId, ssId: rawSsId };
151
+ }
152
+ /**
153
+ * Block start/end in microseconds. Source blocks span `D × GOP_duration`
154
+ * of wall time; this returns the anchored wall range [startUs, endUs).
155
+ */
156
+ blockTimeRangeUs(sbn) {
157
+ const firstSsId = sbn * this.mapper.k;
158
+ const lastSsId = (sbn + 1) * this.mapper.k;
159
+ return {
160
+ startUs: this.anchorMpuUs + firstSsId * this.frameDurationUs,
161
+ endUs: this.anchorMpuUs + lastSsId * this.frameDurationUs
162
+ };
163
+ }
164
+ };
165
+
166
+ // src/pacing/au-duration.ts
167
+ function auDurationMsFromCodec(codec, sampleRate) {
168
+ if (!(sampleRate > 0)) throw new Error("sampleRate must be > 0");
169
+ if (codec.startsWith("opus") || codec.startsWith("Opus")) {
170
+ return 960 / sampleRate * 1e3;
171
+ }
172
+ if (codec.startsWith("mp4a") || codec.startsWith("AAC") || codec.startsWith("aac")) {
173
+ return 1024 / sampleRate * 1e3;
174
+ }
175
+ if (codec.startsWith("flac") || codec.startsWith("fLaC")) {
176
+ return 4096 / sampleRate * 1e3;
177
+ }
178
+ throw new Error(`unknown audio codec for AU duration derivation: ${codec}`);
179
+ }
180
+ function pictureDurationMs(framerate) {
181
+ if (!(framerate > 0)) throw new Error("framerate must be > 0");
182
+ return 1e3 / framerate;
183
+ }
184
+ export {
185
+ FrameCountPacer,
186
+ InterleaveTiming,
187
+ auDurationMsFromCodec,
188
+ pictureDurationMs
189
+ };
190
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/pacing/frame-pacer.ts", "../../src/pacing/interleave-timing.ts", "../../src/pacing/au-duration.ts"],
4
+ "sourcesContent": ["/**\n * FrameCountPacer \u2014 media-agnostic wall-clock pacer for MMT A/V decode loops.\n *\n * Why not use MPU timestamps? Under FEC interleaving, encoders pack multiple\n * Access Units (AUs) per MMTP MPU with a single mpu_timestamp. The observed\n * timestamp delta between MPUs is a fraction of the real per-AU duration\n * (e.g. 10.22ms between MPUs for 21.33ms AAC frames at D=2 interleave).\n * Pacing on that delta sees \"media \u2248 wall\" and never sleeps, letting burst\n * relay delivery saturate the decoder / ring buffer.\n *\n * The Sony libatsc3 pattern (atsc3_mmt_context_mfu_depacketizer) solves this\n * by anchoring wall-clock time to the first received AU and counting AUs:\n * media_elapsed_ms = au_count \u00D7 nominal_au_duration_ms\n * The MPU timestamp is used elsewhere as an absolute-time anchor, never as\n * an incremental clock.\n *\n * The sleep threshold comes from the catalog's FEC interleaveDepthMs (via\n * FecBlockMapper.pacingThresholdMs). When no FEC is configured, a\n * NullBlockMapper yields threshold=0 and this pacer never sleeps.\n *\n * One pacer instance = one track (e.g. audio, video) on one player.\n */\n\nimport type { FecBlockMapper } from '@blockcast/mmt-fec'\n\nexport interface FrameCountPacerOpts {\n /** Required: AU duration (audio) or picture interval (video), in ms. */\n frameDurationMs: number\n /** FEC mapper from @blockcast/mmt-fec. NullBlockMapper disables pacing. */\n mapper: FecBlockMapper\n /**\n * Number of frames to let through before pacing starts. Lets startup\n * burst drain populate the ring buffer / decoder queue. Default 0.\n */\n warmupFrames?: number\n}\n\nexport interface PacerSnapshot {\n /** Frames observed (from notifyFrame). */\n frameCount: number\n /** Computed media time: frameCount \u00D7 frameDurationMs. */\n mediaMs: number\n /** Wall-clock time since anchor. */\n wallMs: number\n /** mediaMs - wallMs. Positive \u2192 decoder ahead of realtime. */\n aheadMs: number\n /** Pacing threshold (ms) from the FEC mapper. */\n thresholdMs: number\n /** Has the first frame been observed (wall anchor set)? */\n anchored: boolean\n}\n\nexport class FrameCountPacer {\n readonly frameDurationMs: number\n readonly thresholdMs: number\n readonly warmupFrames: number\n\n #frameCount = 0\n #anchorWallMs = 0\n #anchored = false\n\n constructor(opts: FrameCountPacerOpts) {\n if (!(opts.frameDurationMs > 0)) {\n throw new Error('frameDurationMs must be > 0')\n }\n this.frameDurationMs = opts.frameDurationMs\n this.thresholdMs = opts.mapper.pacingThresholdMs\n this.warmupFrames = Math.max(0, opts.warmupFrames ?? 0)\n }\n\n /** Call on every emitted decoded frame (AU or picture). Anchors on first call. */\n notifyFrame(): void {\n if (!this.#anchored) {\n this.#anchorWallMs = now()\n this.#anchored = true\n }\n this.#frameCount++\n }\n\n /**\n * Compute sleep ms before reading the next MoQ object.\n * Returns 0 when:\n * - pacing is disabled (NullBlockMapper \u2192 threshold=0)\n * - the anchor is not yet set\n * - still in warmup\n * - the caller reports a standing backlog (see `observedDelayMs`)\n * - decoder is not ahead of wall clock by more than threshold\n * Otherwise returns aheadMs - thresholdMs/2 (leaves half the threshold as headroom).\n *\n * `observedDelayMs` is how far this frame is behind the producer's own clock,\n * measured by the caller against a producer-supplied sending instant (for\n * MMTP, the header send-wall timestamp). It is optional because the anchored\n * rate below is blind to it: `#anchorWallMs` is the wall time of the FIRST\n * frame read, so `aheadMs` measures consumption against the join instant and\n * not against the producer. Once `aheadMs` reaches the threshold the loop\n * consumes at exactly the source rate, and recovering latency present at join\n * requires consuming FASTER than the source rate. So without this argument a\n * consumer that joined a live stream mid-block keeps that join latency for the\n * life of the subscription.\n *\n * A caller that can measure the real distance from the producer passes it and\n * gets a drain: while the backlog exceeds the threshold there is nothing to\n * pace against, so return 0 and let the transport set the rate. At the live\n * edge the anchored-rate behavior below applies unchanged.\n *\n * Callers with no producer clock omit it and keep the pure ATSC3-style\n * anchored pacing (see the class doc), where a first-frame anchor is correct\n * because a broadcast push has no live edge to catch up to.\n */\n computeSleepMs(observedDelayMs?: number): number {\n if (this.thresholdMs <= 0) return 0\n if (!this.#anchored) return 0\n if (this.#frameCount <= this.warmupFrames) return 0\n // Only a finite measurement can license the drain. NaN/Infinity mean the\n // caller could not measure the distance, which is not the same claim as\n // \"the consumer is at the edge\", so fall through to anchored pacing.\n if (observedDelayMs !== undefined && Number.isFinite(observedDelayMs) && observedDelayMs > this.thresholdMs) {\n return 0\n }\n\n const mediaMs = this.#frameCount * this.frameDurationMs\n const wallMs = now() - this.#anchorWallMs\n const aheadMs = mediaMs - wallMs\n if (aheadMs <= this.thresholdMs) return 0\n return aheadMs - this.thresholdMs / 2\n }\n\n /** Reset anchor + counter. Call on source switch (MoQ \u2194 multicast). */\n reset(): void {\n this.#frameCount = 0\n this.#anchorWallMs = 0\n this.#anchored = false\n }\n\n get snapshot(): PacerSnapshot {\n const mediaMs = this.#frameCount * this.frameDurationMs\n const wallMs = this.#anchored ? now() - this.#anchorWallMs : 0\n return {\n frameCount: this.#frameCount,\n mediaMs,\n wallMs,\n aheadMs: mediaMs - wallMs,\n thresholdMs: this.thresholdMs,\n anchored: this.#anchored,\n }\n }\n}\n\nfunction now(): number {\n // performance.now() is available in main thread, workers, and AudioWorklet.\n // Fall back to Date.now() for exotic runtimes (shouldn't happen in browsers).\n if (typeof performance !== 'undefined' && typeof performance.now === 'function') {\n return performance.now()\n }\n return Date.now()\n}\n", "/**\n * InterleaveTiming \u2014 per-AU presentation-time reconstruction.\n *\n * When encoders pack multiple AUs per MMTP MPU with a single mpu_timestamp\n * (normal for FEC-interleaved audio, and for video with multi-picture MPUs),\n * the raw mpu_timestamp is ambiguous for per-AU scheduling. The FEC block\n * math (draft-ramadan-moq-fec-00 \u00A78.3) combined with the Sony libatsc3\n * pattern recovers correct per-AU time:\n *\n * au_index_in_block = groupInBlock \u00D7 symbolsPerGroup + objectId\n * ssId = sbn \u00D7 K + au_index_in_block\n * presentationUs = anchorMpuUs + ssId \u00D7 frameDurationUs\n *\n * The anchor (anchorMpuUs) is the mpu_timestamp of the first observed AU.\n * Every downstream per-AU time is then deterministic from FEC coordinates\n * + codec frame duration \u2014 identical whether the AU arrives via MoQ unicast\n * (group_id/object_id) or multicast UDP (SS_ID from FEC Payload ID).\n *\n * Consumers: CMAF segment assembler (block boundary \u2192 segment cut points),\n * debug overlays, cross-path FEC combining, sync diagnostics.\n */\n\nimport type { FecBlockMapper } from '@blockcast/mmt-fec'\n\nexport interface InterleaveTimingOpts {\n /** Track's FEC mapper (provides K, D, symbolsPerGroup). */\n mapper: FecBlockMapper\n /** Nominal AU duration in microseconds. */\n frameDurationUs: number\n /** Wall-time anchor: the mpu_timestamp of the first observed AU (\u00B5s). */\n anchorMpuUs: number\n}\n\nexport class InterleaveTiming {\n readonly mapper: FecBlockMapper\n readonly frameDurationUs: number\n readonly anchorMpuUs: number\n\n constructor(opts: InterleaveTimingOpts) {\n if (!(opts.frameDurationUs > 0)) {\n throw new Error('frameDurationUs must be > 0')\n }\n if (!Number.isFinite(opts.anchorMpuUs)) {\n throw new Error('anchorMpuUs must be finite')\n }\n this.mapper = opts.mapper\n this.frameDurationUs = opts.frameDurationUs\n this.anchorMpuUs = opts.anchorMpuUs\n }\n\n /**\n * Presentation time (\u00B5s) for an AU at MoQ coords (group_id, object_id).\n * Per draft \u00A78.3 + Sony anchor.\n */\n presentationUs(groupId: number, objectId: number): number {\n const coords = this.mapper.derive(groupId, objectId)\n return this.anchorMpuUs + coords.ssId * this.frameDurationUs\n }\n\n /**\n * Presentation time (\u00B5s) for an AU identified by its flat SS_ID\n * (multicast FEC Payload ID path).\n */\n presentationUsFromSsId(ssId: number): number {\n return this.anchorMpuUs + ssId * this.frameDurationUs\n }\n\n /**\n * Inverse: which (group_id, object_id) AU is scheduled at the given\n * wall offset (\u00B5s) from anchor? Clamps to ssId\u22650.\n */\n frameAtOffset(offsetUs: number): { groupId: number; objectId: number; ssId: number } {\n const rawSsId = Math.max(0, Math.floor(offsetUs / this.frameDurationUs))\n const { sbn, esi } = this.mapper.fromSsId(rawSsId)\n // Invert \u00A78.3: esi = groupInBlock * symbolsPerGroup + objectId\n const spg = this.mapper.symbolsPerGroup\n const groupInBlock = Math.floor(esi / spg)\n const objectId = esi - groupInBlock * spg\n const groupId = sbn * this.mapper.d + groupInBlock\n return { groupId, objectId, ssId: rawSsId }\n }\n\n /**\n * Block start/end in microseconds. Source blocks span `D \u00D7 GOP_duration`\n * of wall time; this returns the anchored wall range [startUs, endUs).\n */\n blockTimeRangeUs(sbn: number): { startUs: number; endUs: number } {\n const firstSsId = sbn * this.mapper.k\n const lastSsId = (sbn + 1) * this.mapper.k\n return {\n startUs: this.anchorMpuUs + firstSsId * this.frameDurationUs,\n endUs: this.anchorMpuUs + lastSsId * this.frameDurationUs,\n }\n }\n}\n", "/**\n * Nominal Access Unit duration helpers for common audio + video codecs.\n *\n * Kept in the pacing subpath (no mmt-container dep) so lean consumers like\n * moqtail's player.ts can import the pacer + AU duration without pulling\n * in the full audio-render-pipeline (which depends on @blockcast/mmt-container).\n */\n\n/**\n * Nominal AU duration in ms for common audio codecs at the given sample rate.\n * AAC-LC: 1024 samples. Opus (default 20ms): 960 samples @ 48kHz.\n * Throws for unknown codecs so callers supply correct timing.\n */\nexport function auDurationMsFromCodec(codec: string, sampleRate: number): number {\n if (!(sampleRate > 0)) throw new Error('sampleRate must be > 0')\n if (codec.startsWith('opus') || codec.startsWith('Opus')) {\n return (960 / sampleRate) * 1000\n }\n if (codec.startsWith('mp4a') || codec.startsWith('AAC') || codec.startsWith('aac')) {\n return (1024 / sampleRate) * 1000\n }\n if (codec.startsWith('flac') || codec.startsWith('fLaC')) {\n return (4096 / sampleRate) * 1000\n }\n throw new Error(`unknown audio codec for AU duration derivation: ${codec}`)\n}\n\n/**\n * Nominal picture duration in ms from framerate.\n */\nexport function pictureDurationMs(framerate: number): number {\n if (!(framerate > 0)) throw new Error('framerate must be > 0')\n return 1000 / framerate\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAoDO,IAAM,kBAAN,MAAsB;AAAA,EAS3B,YAAY,MAA2B;AAJvC,oCAAc;AACd,sCAAgB;AAChB,kCAAY;AAGV,QAAI,EAAE,KAAK,kBAAkB,IAAI;AAC/B,YAAM,IAAI,MAAM,6BAA6B;AAAA,IAC/C;AACA,SAAK,kBAAkB,KAAK;AAC5B,SAAK,cAAc,KAAK,OAAO;AAC/B,SAAK,eAAe,KAAK,IAAI,GAAG,KAAK,gBAAgB,CAAC;AAAA,EACxD;AAAA;AAAA,EAGA,cAAoB;AAClB,QAAI,CAAC,mBAAK,YAAW;AACnB,yBAAK,eAAgB,IAAI;AACzB,yBAAK,WAAY;AAAA,IACnB;AACA,2BAAK,aAAL;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgCA,eAAe,iBAAkC;AAC/C,QAAI,KAAK,eAAe,EAAG,QAAO;AAClC,QAAI,CAAC,mBAAK,WAAW,QAAO;AAC5B,QAAI,mBAAK,gBAAe,KAAK,aAAc,QAAO;AAIlD,QAAI,oBAAoB,UAAa,OAA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AAC5E;AAKO,SAAS,kBAAkB,WAA2B;AAC3D,MAAI,EAAE,YAAY,GAAI,OAAM,IAAI,MAAM,uBAAuB;AAC7D,SAAO,MAAO;AAChB;",
6
+ "names": []
7
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * InterleaveTiming — per-AU presentation-time reconstruction.
3
+ *
4
+ * When encoders pack multiple AUs per MMTP MPU with a single mpu_timestamp
5
+ * (normal for FEC-interleaved audio, and for video with multi-picture MPUs),
6
+ * the raw mpu_timestamp is ambiguous for per-AU scheduling. The FEC block
7
+ * math (draft-ramadan-moq-fec-00 §8.3) combined with the Sony libatsc3
8
+ * pattern recovers correct per-AU time:
9
+ *
10
+ * au_index_in_block = groupInBlock × symbolsPerGroup + objectId
11
+ * ssId = sbn × K + au_index_in_block
12
+ * presentationUs = anchorMpuUs + ssId × frameDurationUs
13
+ *
14
+ * The anchor (anchorMpuUs) is the mpu_timestamp of the first observed AU.
15
+ * Every downstream per-AU time is then deterministic from FEC coordinates
16
+ * + codec frame duration — identical whether the AU arrives via MoQ unicast
17
+ * (group_id/object_id) or multicast UDP (SS_ID from FEC Payload ID).
18
+ *
19
+ * Consumers: CMAF segment assembler (block boundary → segment cut points),
20
+ * debug overlays, cross-path FEC combining, sync diagnostics.
21
+ */
22
+ import type { FecBlockMapper } from '@blockcast/mmt-fec';
23
+ export interface InterleaveTimingOpts {
24
+ /** Track's FEC mapper (provides K, D, symbolsPerGroup). */
25
+ mapper: FecBlockMapper;
26
+ /** Nominal AU duration in microseconds. */
27
+ frameDurationUs: number;
28
+ /** Wall-time anchor: the mpu_timestamp of the first observed AU (µs). */
29
+ anchorMpuUs: number;
30
+ }
31
+ export declare class InterleaveTiming {
32
+ readonly mapper: FecBlockMapper;
33
+ readonly frameDurationUs: number;
34
+ readonly anchorMpuUs: number;
35
+ constructor(opts: InterleaveTimingOpts);
36
+ /**
37
+ * Presentation time (µs) for an AU at MoQ coords (group_id, object_id).
38
+ * Per draft §8.3 + Sony anchor.
39
+ */
40
+ presentationUs(groupId: number, objectId: number): number;
41
+ /**
42
+ * Presentation time (µs) for an AU identified by its flat SS_ID
43
+ * (multicast FEC Payload ID path).
44
+ */
45
+ presentationUsFromSsId(ssId: number): number;
46
+ /**
47
+ * Inverse: which (group_id, object_id) AU is scheduled at the given
48
+ * wall offset (µs) from anchor? Clamps to ssId≥0.
49
+ */
50
+ frameAtOffset(offsetUs: number): {
51
+ groupId: number;
52
+ objectId: number;
53
+ ssId: number;
54
+ };
55
+ /**
56
+ * Block start/end in microseconds. Source blocks span `D × GOP_duration`
57
+ * of wall time; this returns the anchored wall range [startUs, endUs).
58
+ */
59
+ blockTimeRangeUs(sbn: number): {
60
+ startUs: number;
61
+ endUs: number;
62
+ };
63
+ }
64
+ //# sourceMappingURL=interleave-timing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interleave-timing.d.ts","sourceRoot":"","sources":["../../src/pacing/interleave-timing.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAExD,MAAM,WAAW,oBAAoB;IACnC,2DAA2D;IAC3D,MAAM,EAAE,cAAc,CAAA;IACtB,2CAA2C;IAC3C,eAAe,EAAE,MAAM,CAAA;IACvB,yEAAyE;IACzE,WAAW,EAAE,MAAM,CAAA;CACpB;AAED,qBAAa,gBAAgB;IAC3B,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAA;IAC/B,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAA;IAChC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;gBAEhB,IAAI,EAAE,oBAAoB;IAYtC;;;OAGG;IACH,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM;IAKzD;;;OAGG;IACH,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAI5C;;;OAGG;IACH,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE;IAWpF;;;OAGG;IACH,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE;CAQlE"}
@@ -0,0 +1,58 @@
1
+ // src/pacing/interleave-timing.ts
2
+ var InterleaveTiming = class {
3
+ constructor(opts) {
4
+ if (!(opts.frameDurationUs > 0)) {
5
+ throw new Error("frameDurationUs must be > 0");
6
+ }
7
+ if (!Number.isFinite(opts.anchorMpuUs)) {
8
+ throw new Error("anchorMpuUs must be finite");
9
+ }
10
+ this.mapper = opts.mapper;
11
+ this.frameDurationUs = opts.frameDurationUs;
12
+ this.anchorMpuUs = opts.anchorMpuUs;
13
+ }
14
+ /**
15
+ * Presentation time (µs) for an AU at MoQ coords (group_id, object_id).
16
+ * Per draft §8.3 + Sony anchor.
17
+ */
18
+ presentationUs(groupId, objectId) {
19
+ const coords = this.mapper.derive(groupId, objectId);
20
+ return this.anchorMpuUs + coords.ssId * this.frameDurationUs;
21
+ }
22
+ /**
23
+ * Presentation time (µs) for an AU identified by its flat SS_ID
24
+ * (multicast FEC Payload ID path).
25
+ */
26
+ presentationUsFromSsId(ssId) {
27
+ return this.anchorMpuUs + ssId * this.frameDurationUs;
28
+ }
29
+ /**
30
+ * Inverse: which (group_id, object_id) AU is scheduled at the given
31
+ * wall offset (µs) from anchor? Clamps to ssId≥0.
32
+ */
33
+ frameAtOffset(offsetUs) {
34
+ const rawSsId = Math.max(0, Math.floor(offsetUs / this.frameDurationUs));
35
+ const { sbn, esi } = this.mapper.fromSsId(rawSsId);
36
+ const spg = this.mapper.symbolsPerGroup;
37
+ const groupInBlock = Math.floor(esi / spg);
38
+ const objectId = esi - groupInBlock * spg;
39
+ const groupId = sbn * this.mapper.d + groupInBlock;
40
+ return { groupId, objectId, ssId: rawSsId };
41
+ }
42
+ /**
43
+ * Block start/end in microseconds. Source blocks span `D × GOP_duration`
44
+ * of wall time; this returns the anchored wall range [startUs, endUs).
45
+ */
46
+ blockTimeRangeUs(sbn) {
47
+ const firstSsId = sbn * this.mapper.k;
48
+ const lastSsId = (sbn + 1) * this.mapper.k;
49
+ return {
50
+ startUs: this.anchorMpuUs + firstSsId * this.frameDurationUs,
51
+ endUs: this.anchorMpuUs + lastSsId * this.frameDurationUs
52
+ };
53
+ }
54
+ };
55
+ export {
56
+ InterleaveTiming
57
+ };
58
+ //# sourceMappingURL=interleave-timing.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/pacing/interleave-timing.ts"],
4
+ "sourcesContent": ["/**\n * InterleaveTiming \u2014 per-AU presentation-time reconstruction.\n *\n * When encoders pack multiple AUs per MMTP MPU with a single mpu_timestamp\n * (normal for FEC-interleaved audio, and for video with multi-picture MPUs),\n * the raw mpu_timestamp is ambiguous for per-AU scheduling. The FEC block\n * math (draft-ramadan-moq-fec-00 \u00A78.3) combined with the Sony libatsc3\n * pattern recovers correct per-AU time:\n *\n * au_index_in_block = groupInBlock \u00D7 symbolsPerGroup + objectId\n * ssId = sbn \u00D7 K + au_index_in_block\n * presentationUs = anchorMpuUs + ssId \u00D7 frameDurationUs\n *\n * The anchor (anchorMpuUs) is the mpu_timestamp of the first observed AU.\n * Every downstream per-AU time is then deterministic from FEC coordinates\n * + codec frame duration \u2014 identical whether the AU arrives via MoQ unicast\n * (group_id/object_id) or multicast UDP (SS_ID from FEC Payload ID).\n *\n * Consumers: CMAF segment assembler (block boundary \u2192 segment cut points),\n * debug overlays, cross-path FEC combining, sync diagnostics.\n */\n\nimport type { FecBlockMapper } from '@blockcast/mmt-fec'\n\nexport interface InterleaveTimingOpts {\n /** Track's FEC mapper (provides K, D, symbolsPerGroup). */\n mapper: FecBlockMapper\n /** Nominal AU duration in microseconds. */\n frameDurationUs: number\n /** Wall-time anchor: the mpu_timestamp of the first observed AU (\u00B5s). */\n anchorMpuUs: number\n}\n\nexport class InterleaveTiming {\n readonly mapper: FecBlockMapper\n readonly frameDurationUs: number\n readonly anchorMpuUs: number\n\n constructor(opts: InterleaveTimingOpts) {\n if (!(opts.frameDurationUs > 0)) {\n throw new Error('frameDurationUs must be > 0')\n }\n if (!Number.isFinite(opts.anchorMpuUs)) {\n throw new Error('anchorMpuUs must be finite')\n }\n this.mapper = opts.mapper\n this.frameDurationUs = opts.frameDurationUs\n this.anchorMpuUs = opts.anchorMpuUs\n }\n\n /**\n * Presentation time (\u00B5s) for an AU at MoQ coords (group_id, object_id).\n * Per draft \u00A78.3 + Sony anchor.\n */\n presentationUs(groupId: number, objectId: number): number {\n const coords = this.mapper.derive(groupId, objectId)\n return this.anchorMpuUs + coords.ssId * this.frameDurationUs\n }\n\n /**\n * Presentation time (\u00B5s) for an AU identified by its flat SS_ID\n * (multicast FEC Payload ID path).\n */\n presentationUsFromSsId(ssId: number): number {\n return this.anchorMpuUs + ssId * this.frameDurationUs\n }\n\n /**\n * Inverse: which (group_id, object_id) AU is scheduled at the given\n * wall offset (\u00B5s) from anchor? Clamps to ssId\u22650.\n */\n frameAtOffset(offsetUs: number): { groupId: number; objectId: number; ssId: number } {\n const rawSsId = Math.max(0, Math.floor(offsetUs / this.frameDurationUs))\n const { sbn, esi } = this.mapper.fromSsId(rawSsId)\n // Invert \u00A78.3: esi = groupInBlock * symbolsPerGroup + objectId\n const spg = this.mapper.symbolsPerGroup\n const groupInBlock = Math.floor(esi / spg)\n const objectId = esi - groupInBlock * spg\n const groupId = sbn * this.mapper.d + groupInBlock\n return { groupId, objectId, ssId: rawSsId }\n }\n\n /**\n * Block start/end in microseconds. Source blocks span `D \u00D7 GOP_duration`\n * of wall time; this returns the anchored wall range [startUs, endUs).\n */\n blockTimeRangeUs(sbn: number): { startUs: number; endUs: number } {\n const firstSsId = sbn * this.mapper.k\n const lastSsId = (sbn + 1) * this.mapper.k\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SAAS,KAAK,cAAc,YAAY,KAAK;AAAA,MAC7C,OAAO,KAAK,cAAc,WAAW,KAAK;AAAA,IAC5C;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,4 @@
1
+ export { KeyframeGate } from './keyframe-gate.js';
2
+ export { VideoRenderPipeline } from './video-render-pipeline.js';
3
+ export type { VideoRenderPipelineOpts, VideoFrameMeta, VideoFrameCallback, } from './video-render-pipeline.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/video/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAA;AAChE,YAAY,EACV,uBAAuB,EACvB,cAAc,EACd,kBAAkB,GACnB,MAAM,4BAA4B,CAAA"}
@@ -0,0 +1,271 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
+ var __privateWrapper = (obj, member, setter, getter) => ({
10
+ set _(value) {
11
+ __privateSet(obj, member, value, setter);
12
+ },
13
+ get _() {
14
+ return __privateGet(obj, member, getter);
15
+ }
16
+ });
17
+
18
+ // src/video/keyframe-gate.ts
19
+ var _open;
20
+ var KeyframeGate = class {
21
+ constructor() {
22
+ __privateAdd(this, _open, false);
23
+ }
24
+ get isOpen() {
25
+ return __privateGet(this, _open);
26
+ }
27
+ /**
28
+ * Decide whether to pass a frame through.
29
+ * Opens permanently once the first keyframe is seen.
30
+ */
31
+ allow(keyframe) {
32
+ if (__privateGet(this, _open)) return true;
33
+ if (keyframe) {
34
+ __privateSet(this, _open, true);
35
+ return true;
36
+ }
37
+ return false;
38
+ }
39
+ /** Re-close the gate. Next keyframe reopens it. */
40
+ reset() {
41
+ __privateSet(this, _open, false);
42
+ }
43
+ };
44
+ _open = new WeakMap();
45
+
46
+ // src/video/video-render-pipeline.ts
47
+ import { MmtpDecodePipeline } from "@blockcast/mmt-container/mmtp-decode-pipeline";
48
+
49
+ // src/pacing/frame-pacer.ts
50
+ var _frameCount, _anchorWallMs, _anchored;
51
+ var FrameCountPacer = class {
52
+ constructor(opts) {
53
+ __privateAdd(this, _frameCount, 0);
54
+ __privateAdd(this, _anchorWallMs, 0);
55
+ __privateAdd(this, _anchored, false);
56
+ if (!(opts.frameDurationMs > 0)) {
57
+ throw new Error("frameDurationMs must be > 0");
58
+ }
59
+ this.frameDurationMs = opts.frameDurationMs;
60
+ this.thresholdMs = opts.mapper.pacingThresholdMs;
61
+ this.warmupFrames = Math.max(0, opts.warmupFrames ?? 0);
62
+ }
63
+ /** Call on every emitted decoded frame (AU or picture). Anchors on first call. */
64
+ notifyFrame() {
65
+ if (!__privateGet(this, _anchored)) {
66
+ __privateSet(this, _anchorWallMs, now());
67
+ __privateSet(this, _anchored, true);
68
+ }
69
+ __privateWrapper(this, _frameCount)._++;
70
+ }
71
+ /**
72
+ * Compute sleep ms before reading the next MoQ object.
73
+ * Returns 0 when:
74
+ * - pacing is disabled (NullBlockMapper → threshold=0)
75
+ * - the anchor is not yet set
76
+ * - still in warmup
77
+ * - the caller reports a standing backlog (see `observedDelayMs`)
78
+ * - decoder is not ahead of wall clock by more than threshold
79
+ * Otherwise returns aheadMs - thresholdMs/2 (leaves half the threshold as headroom).
80
+ *
81
+ * `observedDelayMs` is how far this frame is behind the producer's own clock,
82
+ * measured by the caller against a producer-supplied sending instant (for
83
+ * MMTP, the header send-wall timestamp). It is optional because the anchored
84
+ * rate below is blind to it: `#anchorWallMs` is the wall time of the FIRST
85
+ * frame read, so `aheadMs` measures consumption against the join instant and
86
+ * not against the producer. Once `aheadMs` reaches the threshold the loop
87
+ * consumes at exactly the source rate, and recovering latency present at join
88
+ * requires consuming FASTER than the source rate. So without this argument a
89
+ * consumer that joined a live stream mid-block keeps that join latency for the
90
+ * life of the subscription.
91
+ *
92
+ * A caller that can measure the real distance from the producer passes it and
93
+ * gets a drain: while the backlog exceeds the threshold there is nothing to
94
+ * pace against, so return 0 and let the transport set the rate. At the live
95
+ * edge the anchored-rate behavior below applies unchanged.
96
+ *
97
+ * Callers with no producer clock omit it and keep the pure ATSC3-style
98
+ * anchored pacing (see the class doc), where a first-frame anchor is correct
99
+ * because a broadcast push has no live edge to catch up to.
100
+ */
101
+ computeSleepMs(observedDelayMs) {
102
+ if (this.thresholdMs <= 0) return 0;
103
+ if (!__privateGet(this, _anchored)) return 0;
104
+ if (__privateGet(this, _frameCount) <= this.warmupFrames) return 0;
105
+ if (observedDelayMs !== void 0 && Number.isFinite(observedDelayMs) && observedDelayMs > this.thresholdMs) {
106
+ return 0;
107
+ }
108
+ const mediaMs = __privateGet(this, _frameCount) * this.frameDurationMs;
109
+ const wallMs = now() - __privateGet(this, _anchorWallMs);
110
+ const aheadMs = mediaMs - wallMs;
111
+ if (aheadMs <= this.thresholdMs) return 0;
112
+ return aheadMs - this.thresholdMs / 2;
113
+ }
114
+ /** Reset anchor + counter. Call on source switch (MoQ ↔ multicast). */
115
+ reset() {
116
+ __privateSet(this, _frameCount, 0);
117
+ __privateSet(this, _anchorWallMs, 0);
118
+ __privateSet(this, _anchored, false);
119
+ }
120
+ get snapshot() {
121
+ const mediaMs = __privateGet(this, _frameCount) * this.frameDurationMs;
122
+ const wallMs = __privateGet(this, _anchored) ? now() - __privateGet(this, _anchorWallMs) : 0;
123
+ return {
124
+ frameCount: __privateGet(this, _frameCount),
125
+ mediaMs,
126
+ wallMs,
127
+ aheadMs: mediaMs - wallMs,
128
+ thresholdMs: this.thresholdMs,
129
+ anchored: __privateGet(this, _anchored)
130
+ };
131
+ }
132
+ };
133
+ _frameCount = new WeakMap();
134
+ _anchorWallMs = new WeakMap();
135
+ _anchored = new WeakMap();
136
+ function now() {
137
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
138
+ return performance.now();
139
+ }
140
+ return Date.now();
141
+ }
142
+
143
+ // src/video/video-render-pipeline.ts
144
+ function deriveVideoReorderWindow(framerate, mapper) {
145
+ const framesPerGroup = Math.ceil(framerate * mapper.gopDurationMs / 1e3);
146
+ return mapper.d * framesPerGroup;
147
+ }
148
+ var _pacer, _gate, _opts, _decoder, _pipeline, _closed, _VideoRenderPipeline_instances, init_fn, configureDecoder_fn;
149
+ var VideoRenderPipeline = class {
150
+ constructor(opts) {
151
+ __privateAdd(this, _VideoRenderPipeline_instances);
152
+ __privateAdd(this, _pacer);
153
+ __privateAdd(this, _gate, new KeyframeGate());
154
+ __privateAdd(this, _opts);
155
+ __privateAdd(this, _decoder, null);
156
+ __privateAdd(this, _pipeline, null);
157
+ __privateAdd(this, _closed, false);
158
+ if (!(opts.framerate > 0)) throw new Error("framerate must be > 0");
159
+ __privateSet(this, _opts, opts);
160
+ __privateSet(this, _pacer, new FrameCountPacer({
161
+ frameDurationMs: 1e3 / opts.framerate,
162
+ mapper: opts.mapper,
163
+ warmupFrames: opts.warmupFrames ?? 3
164
+ }));
165
+ __privateMethod(this, _VideoRenderPipeline_instances, init_fn).call(this);
166
+ }
167
+ feedMoqObject(packet) {
168
+ __privateGet(this, _pipeline)?.feedMoqObject(packet);
169
+ }
170
+ paceSleepMs() {
171
+ return __privateGet(this, _pacer).computeSleepMs();
172
+ }
173
+ get pacerSnapshot() {
174
+ return __privateGet(this, _pacer).snapshot;
175
+ }
176
+ /** Request a fresh keyframe after a decoder error (or source switch). */
177
+ reset() {
178
+ __privateGet(this, _gate).reset();
179
+ __privateGet(this, _pacer).reset();
180
+ try {
181
+ __privateGet(this, _decoder)?.reset();
182
+ } catch {
183
+ }
184
+ __privateMethod(this, _VideoRenderPipeline_instances, configureDecoder_fn).call(this);
185
+ }
186
+ close() {
187
+ if (__privateGet(this, _closed)) return;
188
+ __privateSet(this, _closed, true);
189
+ try {
190
+ __privateGet(this, _decoder)?.close();
191
+ } catch {
192
+ }
193
+ try {
194
+ __privateGet(this, _pipeline)?.dispose();
195
+ } catch {
196
+ }
197
+ __privateSet(this, _decoder, null);
198
+ __privateSet(this, _pipeline, null);
199
+ }
200
+ };
201
+ _pacer = new WeakMap();
202
+ _gate = new WeakMap();
203
+ _opts = new WeakMap();
204
+ _decoder = new WeakMap();
205
+ _pipeline = new WeakMap();
206
+ _closed = new WeakMap();
207
+ _VideoRenderPipeline_instances = new WeakSet();
208
+ // ─── Private ─────────────────────────────────────────────────────
209
+ init_fn = function() {
210
+ __privateMethod(this, _VideoRenderPipeline_instances, configureDecoder_fn).call(this);
211
+ const pipeline = new MmtpDecodePipeline();
212
+ const reorderWindow = __privateGet(this, _opts).reorderWindow ?? deriveVideoReorderWindow(__privateGet(this, _opts).framerate, __privateGet(this, _opts).mapper);
213
+ pipeline.configure({
214
+ codec: __privateGet(this, _opts).codec,
215
+ packetId: __privateGet(this, _opts).packetId,
216
+ description: __privateGet(this, _opts).description,
217
+ reorderWindow,
218
+ framerate: __privateGet(this, _opts).framerate,
219
+ groupDurationMs: __privateGet(this, _opts).mapper.gopDurationMs,
220
+ reassemblyPolicy: __privateGet(this, _opts).reassemblyPolicy
221
+ });
222
+ if (__privateGet(this, _opts).fecClient) pipeline.setFecClient(__privateGet(this, _opts).fecClient);
223
+ pipeline.onFrame((codecData, meta) => {
224
+ if (__privateGet(this, _closed) || !__privateGet(this, _decoder)) return;
225
+ if (codecData.byteLength === 0) return;
226
+ if (!__privateGet(this, _gate).allow(meta.keyframe)) return;
227
+ __privateGet(this, _pacer).notifyFrame();
228
+ try {
229
+ __privateGet(this, _decoder).decode(new EncodedVideoChunk({
230
+ type: meta.keyframe ? "key" : "delta",
231
+ data: codecData,
232
+ timestamp: meta.timestamp
233
+ }));
234
+ } catch (err) {
235
+ __privateGet(this, _opts).onError?.(err);
236
+ this.reset();
237
+ }
238
+ });
239
+ __privateSet(this, _pipeline, pipeline);
240
+ };
241
+ configureDecoder_fn = function() {
242
+ try {
243
+ __privateGet(this, _decoder)?.close();
244
+ } catch {
245
+ }
246
+ const userMeta = { timestamp: 0, keyframe: false, packetId: 0 };
247
+ const decoder = new VideoDecoder({
248
+ output: (frame) => {
249
+ userMeta.timestamp = frame.timestamp;
250
+ __privateGet(this, _opts).onFrame(frame, userMeta);
251
+ },
252
+ error: (err) => {
253
+ __privateGet(this, _opts).onError?.(err);
254
+ __privateGet(this, _gate).reset();
255
+ }
256
+ });
257
+ const config = {
258
+ codec: __privateGet(this, _opts).codec,
259
+ codedWidth: __privateGet(this, _opts).width,
260
+ codedHeight: __privateGet(this, _opts).height,
261
+ ...__privateGet(this, _opts).description ? { description: __privateGet(this, _opts).description } : {},
262
+ ...__privateGet(this, _opts).hardwareAcceleration ? { hardwareAcceleration: __privateGet(this, _opts).hardwareAcceleration } : {}
263
+ };
264
+ decoder.configure(config);
265
+ __privateSet(this, _decoder, decoder);
266
+ };
267
+ export {
268
+ KeyframeGate,
269
+ VideoRenderPipeline
270
+ };
271
+ //# sourceMappingURL=index.js.map