@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,664 @@
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/audio/audio-ring-buffer.ts
19
+ var _buffer, _writeIndex, _readIndex, _stalled, _startupFrames, _resumeFrames, _resumeFollowsStartup, _hasStarted, _capacityHeadroomFrames, _timestampAnchors, _diagEnabled, _diagReads, _diagFillSum, _diagOverflowSamples, _AudioRingBuffer_instances, pruneTimestampAnchors_fn, refillFrames_fn;
20
+ var AudioRingBuffer = class {
21
+ constructor(config) {
22
+ __privateAdd(this, _AudioRingBuffer_instances);
23
+ __privateAdd(this, _buffer);
24
+ __privateAdd(this, _writeIndex, 0);
25
+ __privateAdd(this, _readIndex, 0);
26
+ __privateAdd(this, _stalled);
27
+ __privateAdd(this, _startupFrames);
28
+ __privateAdd(this, _resumeFrames);
29
+ __privateAdd(this, _resumeFollowsStartup);
30
+ __privateAdd(this, _hasStarted);
31
+ __privateAdd(this, _capacityHeadroomFrames);
32
+ __privateAdd(this, _timestampAnchors, []);
33
+ __privateAdd(this, _diagEnabled);
34
+ __privateAdd(this, _diagReads, 0);
35
+ __privateAdd(this, _diagFillSum, 0);
36
+ __privateAdd(this, _diagOverflowSamples, 0);
37
+ if (!Number.isInteger(config.channels) || config.channels <= 0) {
38
+ throw new Error("invalid channels");
39
+ }
40
+ if (!Number.isFinite(config.rate) || config.rate <= 0) {
41
+ throw new Error("invalid sample rate");
42
+ }
43
+ if (!Number.isFinite(config.latencyMs) || config.latencyMs <= 0) {
44
+ throw new Error("invalid latency");
45
+ }
46
+ const latencyFrames = Math.ceil(config.rate * (config.latencyMs / 1e3));
47
+ const startupFrames = config.startupFrames ?? latencyFrames;
48
+ const resumeFrames = config.resumeFrames ?? startupFrames;
49
+ const thresholdFrames = Math.max(startupFrames, resumeFrames);
50
+ const capacityFrames = config.capacityFrames ?? Math.max(latencyFrames, thresholdFrames);
51
+ if (!Number.isSafeInteger(startupFrames) || startupFrames <= 0) {
52
+ throw new Error("invalid startup frames");
53
+ }
54
+ if (!Number.isSafeInteger(resumeFrames) || resumeFrames <= 0) {
55
+ throw new Error("invalid resume frames");
56
+ }
57
+ if (!Number.isSafeInteger(capacityFrames) || capacityFrames < thresholdFrames) {
58
+ throw new Error("invalid capacity frames");
59
+ }
60
+ this.channels = config.channels;
61
+ this.rate = config.rate;
62
+ __privateSet(this, _startupFrames, startupFrames);
63
+ __privateSet(this, _resumeFrames, resumeFrames);
64
+ __privateSet(this, _resumeFollowsStartup, config.resumeFrames === void 0);
65
+ __privateSet(this, _hasStarted, config.startUnstalled ?? false);
66
+ __privateSet(this, _capacityHeadroomFrames, capacityFrames - thresholdFrames);
67
+ __privateSet(this, _stalled, !(config.startUnstalled ?? false));
68
+ __privateSet(this, _diagEnabled, config.diag ?? false);
69
+ __privateSet(this, _buffer, Array.from(
70
+ { length: config.channels },
71
+ () => new Float32Array(capacityFrames)
72
+ ));
73
+ }
74
+ get stalled() {
75
+ return __privateGet(this, _stalled);
76
+ }
77
+ get startupFrames() {
78
+ return __privateGet(this, _startupFrames);
79
+ }
80
+ get capacity() {
81
+ return __privateGet(this, _buffer)[0].length;
82
+ }
83
+ get length() {
84
+ return __privateGet(this, _writeIndex) - __privateGet(this, _readIndex);
85
+ }
86
+ /** Timestamp of the next media sample after the PCM already emitted. */
87
+ get timestampUs() {
88
+ const anchor = __privateGet(this, _timestampAnchors)[0];
89
+ if (!anchor || anchor.sampleIndex > __privateGet(this, _readIndex)) return void 0;
90
+ return anchor.timestampUs + (__privateGet(this, _readIndex) - anchor.sampleIndex) / this.rate * 1e6;
91
+ }
92
+ write(timestampUs, data) {
93
+ if (data.length !== this.channels) throw new Error("wrong channel count");
94
+ if (!Number.isFinite(timestampUs)) throw new Error("invalid timestamp");
95
+ const samples = data[0].length;
96
+ if (samples === 0) return;
97
+ if (data.some((channel) => channel.length !== samples)) {
98
+ throw new Error("mismatched channel lengths");
99
+ }
100
+ const start = __privateGet(this, _writeIndex);
101
+ const end = start + samples;
102
+ __privateGet(this, _timestampAnchors).push({ sampleIndex: start, timestampUs });
103
+ const overflow = end - __privateGet(this, _readIndex) - this.capacity;
104
+ if (overflow > 0) {
105
+ __privateSet(this, _stalled, false);
106
+ __privateSet(this, _hasStarted, true);
107
+ __privateSet(this, _readIndex, __privateGet(this, _readIndex) + overflow);
108
+ if (__privateGet(this, _diagEnabled)) __privateSet(this, _diagOverflowSamples, __privateGet(this, _diagOverflowSamples) + overflow);
109
+ __privateMethod(this, _AudioRingBuffer_instances, pruneTimestampAnchors_fn).call(this);
110
+ }
111
+ const refillFrames = __privateGet(this, _hasStarted) ? __privateGet(this, _resumeFrames) : __privateGet(this, _startupFrames);
112
+ if (__privateGet(this, _stalled) && end - __privateGet(this, _readIndex) >= refillFrames) {
113
+ __privateSet(this, _stalled, false);
114
+ __privateSet(this, _hasStarted, true);
115
+ }
116
+ for (let channel = 0; channel < this.channels; channel++) {
117
+ const src = data[channel];
118
+ const dst = __privateGet(this, _buffer)[channel];
119
+ for (let i = 0; i < samples; i++) {
120
+ dst[(start + i) % dst.length] = src[i];
121
+ }
122
+ }
123
+ __privateSet(this, _writeIndex, end);
124
+ }
125
+ read(output) {
126
+ if (output.length !== this.channels) throw new Error("wrong channel count");
127
+ if (__privateGet(this, _stalled)) return 0;
128
+ const available = this.length;
129
+ if (available === 0) {
130
+ __privateSet(this, _stalled, true);
131
+ return 0;
132
+ }
133
+ const requested = output[0].length;
134
+ const readSamples = Math.min(available, requested);
135
+ for (let channel = 0; channel < this.channels; channel++) {
136
+ const dst = output[channel];
137
+ const src = __privateGet(this, _buffer)[channel];
138
+ for (let i = 0; i < readSamples; i++) {
139
+ dst[i] = src[(__privateGet(this, _readIndex) + i) % src.length];
140
+ }
141
+ for (let i = readSamples; i < requested; i++) dst[i] = 0;
142
+ }
143
+ __privateSet(this, _readIndex, __privateGet(this, _readIndex) + readSamples);
144
+ __privateMethod(this, _AudioRingBuffer_instances, pruneTimestampAnchors_fn).call(this);
145
+ if (readSamples < requested) __privateSet(this, _stalled, true);
146
+ if (__privateGet(this, _diagEnabled)) {
147
+ __privateWrapper(this, _diagReads)._++;
148
+ __privateSet(this, _diagFillSum, __privateGet(this, _diagFillSum) + available);
149
+ }
150
+ return readSamples;
151
+ }
152
+ /** Clear queued PCM; optionally treat the next fill as post-start recovery. */
153
+ reset(startUnstalled = false, resumeAfterReset = false) {
154
+ __privateSet(this, _writeIndex, 0);
155
+ __privateSet(this, _readIndex, 0);
156
+ __privateSet(this, _stalled, !startUnstalled);
157
+ __privateSet(this, _hasStarted, startUnstalled || resumeAfterReset);
158
+ __privateSet(this, _timestampAnchors, []);
159
+ __privateSet(this, _diagReads, 0);
160
+ __privateSet(this, _diagFillSum, 0);
161
+ __privateSet(this, _diagOverflowSamples, 0);
162
+ }
163
+ /**
164
+ * Change the startup latency while preserving the configured storage
165
+ * headroom above its buffering thresholds. Active playout keeps draining
166
+ * retained PCM; a stalled buffer waits for its startup or resume threshold.
167
+ */
168
+ resize(latencyMs) {
169
+ if (!Number.isFinite(latencyMs) || latencyMs <= 0) {
170
+ throw new Error("invalid latency");
171
+ }
172
+ const newStartupFrames = Math.ceil(this.rate * (latencyMs / 1e3));
173
+ if (!Number.isSafeInteger(newStartupFrames) || newStartupFrames <= 0) {
174
+ throw new Error("invalid latency");
175
+ }
176
+ const newResumeFrames = __privateGet(this, _resumeFollowsStartup) ? newStartupFrames : __privateGet(this, _resumeFrames);
177
+ const newCapacity = Math.max(newStartupFrames, newResumeFrames) + __privateGet(this, _capacityHeadroomFrames);
178
+ if (!Number.isSafeInteger(newCapacity) || newCapacity < Math.max(newStartupFrames, newResumeFrames)) {
179
+ throw new Error("invalid capacity frames");
180
+ }
181
+ const wasStalled = __privateGet(this, _stalled);
182
+ __privateSet(this, _startupFrames, newStartupFrames);
183
+ __privateSet(this, _resumeFrames, newResumeFrames);
184
+ if (newCapacity === this.capacity) {
185
+ if (wasStalled && this.length >= __privateMethod(this, _AudioRingBuffer_instances, refillFrames_fn).call(this)) {
186
+ __privateSet(this, _stalled, false);
187
+ __privateSet(this, _hasStarted, true);
188
+ }
189
+ return;
190
+ }
191
+ const next = Array.from(
192
+ { length: this.channels },
193
+ () => new Float32Array(newCapacity)
194
+ );
195
+ const samplesToKeep = Math.min(this.length, newCapacity);
196
+ const copyStart = __privateGet(this, _writeIndex) - samplesToKeep;
197
+ for (let channel = 0; channel < this.channels; channel++) {
198
+ const src = __privateGet(this, _buffer)[channel];
199
+ const dst = next[channel];
200
+ for (let i = 0; i < samplesToKeep; i++) {
201
+ const sampleIndex = copyStart + i;
202
+ dst[sampleIndex % dst.length] = src[sampleIndex % src.length];
203
+ }
204
+ }
205
+ __privateSet(this, _buffer, next);
206
+ __privateSet(this, _readIndex, copyStart);
207
+ __privateMethod(this, _AudioRingBuffer_instances, pruneTimestampAnchors_fn).call(this);
208
+ __privateSet(this, _stalled, samplesToKeep === 0 || wasStalled && samplesToKeep < __privateMethod(this, _AudioRingBuffer_instances, refillFrames_fn).call(this));
209
+ if (!__privateGet(this, _stalled)) __privateSet(this, _hasStarted, true);
210
+ }
211
+ getDiagAndReset() {
212
+ if (!__privateGet(this, _diagEnabled) || __privateGet(this, _diagReads) === 0) return null;
213
+ const result = {
214
+ reads: __privateGet(this, _diagReads),
215
+ avgFill: Math.round(__privateGet(this, _diagFillSum) / __privateGet(this, _diagReads)),
216
+ capacity: this.capacity,
217
+ skips: 0,
218
+ dups: 0,
219
+ overflowSamples: __privateGet(this, _diagOverflowSamples)
220
+ };
221
+ __privateSet(this, _diagReads, 0);
222
+ __privateSet(this, _diagFillSum, 0);
223
+ __privateSet(this, _diagOverflowSamples, 0);
224
+ return result;
225
+ }
226
+ };
227
+ _buffer = new WeakMap();
228
+ _writeIndex = new WeakMap();
229
+ _readIndex = new WeakMap();
230
+ _stalled = new WeakMap();
231
+ _startupFrames = new WeakMap();
232
+ _resumeFrames = new WeakMap();
233
+ _resumeFollowsStartup = new WeakMap();
234
+ _hasStarted = new WeakMap();
235
+ _capacityHeadroomFrames = new WeakMap();
236
+ _timestampAnchors = new WeakMap();
237
+ _diagEnabled = new WeakMap();
238
+ _diagReads = new WeakMap();
239
+ _diagFillSum = new WeakMap();
240
+ _diagOverflowSamples = new WeakMap();
241
+ _AudioRingBuffer_instances = new WeakSet();
242
+ pruneTimestampAnchors_fn = function() {
243
+ let keep = 0;
244
+ while (keep + 1 < __privateGet(this, _timestampAnchors).length && __privateGet(this, _timestampAnchors)[keep + 1].sampleIndex <= __privateGet(this, _readIndex)) {
245
+ keep++;
246
+ }
247
+ if (keep > 0) __privateGet(this, _timestampAnchors).splice(0, keep);
248
+ };
249
+ refillFrames_fn = function() {
250
+ return __privateGet(this, _hasStarted) ? __privateGet(this, _resumeFrames) : __privateGet(this, _startupFrames);
251
+ };
252
+
253
+ // src/audio/audio-buffer-plan.ts
254
+ function positive(value, label) {
255
+ if (!Number.isFinite(value) || value <= 0) throw new Error(`invalid ${label}`);
256
+ return value;
257
+ }
258
+ function deriveAudioBurstBufferPlan(input) {
259
+ const sampleRate = positive(input.sampleRate, "sample rate");
260
+ const chunkFrames = positive(input.chunkFrames, "audio chunk size");
261
+ const groupDurationMs = positive(input.groupDurationMs, "audio group duration");
262
+ if (!Number.isInteger(chunkFrames)) throw new Error("invalid audio chunk size");
263
+ const chunkDurationMs = 1e3 * chunkFrames / sampleRate;
264
+ const groupChunks = Math.max(1, Math.round(groupDurationMs / chunkDurationMs));
265
+ const deliveryWindowChunks = input.deliveryWindowMs === void 0 ? 0 : Math.max(
266
+ 1,
267
+ Math.ceil(positive(input.deliveryWindowMs, "audio delivery window") / chunkDurationMs)
268
+ );
269
+ const deliveryChunks = Math.max(groupChunks, deliveryWindowChunks);
270
+ const deliveryFrames = deliveryChunks * chunkFrames;
271
+ const capacityFrames = deliveryFrames + deliveryFrames;
272
+ if (!Number.isSafeInteger(deliveryFrames) || !Number.isSafeInteger(capacityFrames)) {
273
+ throw new Error("audio buffer frame count exceeds safe integer range");
274
+ }
275
+ return {
276
+ startupFrames: deliveryFrames,
277
+ capacityFrames,
278
+ deliveryFrames
279
+ };
280
+ }
281
+
282
+ // src/audio/audio-render-pipeline.ts
283
+ import { MmtpDecodePipeline } from "@blockcast/mmt-container/mmtp-decode-pipeline";
284
+
285
+ // src/pacing/frame-pacer.ts
286
+ var _frameCount, _anchorWallMs, _anchored;
287
+ var FrameCountPacer = class {
288
+ constructor(opts) {
289
+ __privateAdd(this, _frameCount, 0);
290
+ __privateAdd(this, _anchorWallMs, 0);
291
+ __privateAdd(this, _anchored, false);
292
+ if (!(opts.frameDurationMs > 0)) {
293
+ throw new Error("frameDurationMs must be > 0");
294
+ }
295
+ this.frameDurationMs = opts.frameDurationMs;
296
+ this.thresholdMs = opts.mapper.pacingThresholdMs;
297
+ this.warmupFrames = Math.max(0, opts.warmupFrames ?? 0);
298
+ }
299
+ /** Call on every emitted decoded frame (AU or picture). Anchors on first call. */
300
+ notifyFrame() {
301
+ if (!__privateGet(this, _anchored)) {
302
+ __privateSet(this, _anchorWallMs, now());
303
+ __privateSet(this, _anchored, true);
304
+ }
305
+ __privateWrapper(this, _frameCount)._++;
306
+ }
307
+ /**
308
+ * Compute sleep ms before reading the next MoQ object.
309
+ * Returns 0 when:
310
+ * - pacing is disabled (NullBlockMapper → threshold=0)
311
+ * - the anchor is not yet set
312
+ * - still in warmup
313
+ * - the caller reports a standing backlog (see `observedDelayMs`)
314
+ * - decoder is not ahead of wall clock by more than threshold
315
+ * Otherwise returns aheadMs - thresholdMs/2 (leaves half the threshold as headroom).
316
+ *
317
+ * `observedDelayMs` is how far this frame is behind the producer's own clock,
318
+ * measured by the caller against a producer-supplied sending instant (for
319
+ * MMTP, the header send-wall timestamp). It is optional because the anchored
320
+ * rate below is blind to it: `#anchorWallMs` is the wall time of the FIRST
321
+ * frame read, so `aheadMs` measures consumption against the join instant and
322
+ * not against the producer. Once `aheadMs` reaches the threshold the loop
323
+ * consumes at exactly the source rate, and recovering latency present at join
324
+ * requires consuming FASTER than the source rate. So without this argument a
325
+ * consumer that joined a live stream mid-block keeps that join latency for the
326
+ * life of the subscription.
327
+ *
328
+ * A caller that can measure the real distance from the producer passes it and
329
+ * gets a drain: while the backlog exceeds the threshold there is nothing to
330
+ * pace against, so return 0 and let the transport set the rate. At the live
331
+ * edge the anchored-rate behavior below applies unchanged.
332
+ *
333
+ * Callers with no producer clock omit it and keep the pure ATSC3-style
334
+ * anchored pacing (see the class doc), where a first-frame anchor is correct
335
+ * because a broadcast push has no live edge to catch up to.
336
+ */
337
+ computeSleepMs(observedDelayMs) {
338
+ if (this.thresholdMs <= 0) return 0;
339
+ if (!__privateGet(this, _anchored)) return 0;
340
+ if (__privateGet(this, _frameCount) <= this.warmupFrames) return 0;
341
+ if (observedDelayMs !== void 0 && Number.isFinite(observedDelayMs) && observedDelayMs > this.thresholdMs) {
342
+ return 0;
343
+ }
344
+ const mediaMs = __privateGet(this, _frameCount) * this.frameDurationMs;
345
+ const wallMs = now() - __privateGet(this, _anchorWallMs);
346
+ const aheadMs = mediaMs - wallMs;
347
+ if (aheadMs <= this.thresholdMs) return 0;
348
+ return aheadMs - this.thresholdMs / 2;
349
+ }
350
+ /** Reset anchor + counter. Call on source switch (MoQ ↔ multicast). */
351
+ reset() {
352
+ __privateSet(this, _frameCount, 0);
353
+ __privateSet(this, _anchorWallMs, 0);
354
+ __privateSet(this, _anchored, false);
355
+ }
356
+ get snapshot() {
357
+ const mediaMs = __privateGet(this, _frameCount) * this.frameDurationMs;
358
+ const wallMs = __privateGet(this, _anchored) ? now() - __privateGet(this, _anchorWallMs) : 0;
359
+ return {
360
+ frameCount: __privateGet(this, _frameCount),
361
+ mediaMs,
362
+ wallMs,
363
+ aheadMs: mediaMs - wallMs,
364
+ thresholdMs: this.thresholdMs,
365
+ anchored: __privateGet(this, _anchored)
366
+ };
367
+ }
368
+ };
369
+ _frameCount = new WeakMap();
370
+ _anchorWallMs = new WeakMap();
371
+ _anchored = new WeakMap();
372
+ function now() {
373
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
374
+ return performance.now();
375
+ }
376
+ return Date.now();
377
+ }
378
+
379
+ // src/pacing/au-duration.ts
380
+ function auDurationMsFromCodec(codec, sampleRate) {
381
+ if (!(sampleRate > 0)) throw new Error("sampleRate must be > 0");
382
+ if (codec.startsWith("opus") || codec.startsWith("Opus")) {
383
+ return 960 / sampleRate * 1e3;
384
+ }
385
+ if (codec.startsWith("mp4a") || codec.startsWith("AAC") || codec.startsWith("aac")) {
386
+ return 1024 / sampleRate * 1e3;
387
+ }
388
+ if (codec.startsWith("flac") || codec.startsWith("fLaC")) {
389
+ return 4096 / sampleRate * 1e3;
390
+ }
391
+ throw new Error(`unknown audio codec for AU duration derivation: ${codec}`);
392
+ }
393
+
394
+ // src/audio/worklet-url.ts
395
+ function workletModuleUrl() {
396
+ const base = new URL("../worklet/render-worklet.js", import.meta.url);
397
+ return base.href;
398
+ }
399
+ var WORKLET_PROCESSOR_NAME = "mmt-render";
400
+
401
+ // src/audio/audio-render-pipeline.ts
402
+ var _context, _pacer, _mapper, _codec, _packetId, _sampleRate, _channels, _description, _latencyMs, _startupFrames2, _startupThresholdFrames, _capacityFrames, _diag, _warmupFrames, _onState, _onDiag, _onError, _reassemblyPolicy, _decoder, _pipeline, _worklet, _fecClient, _closed, _readyPromise, _workletGeneration, _startupReleased, _AudioRenderPipeline_instances, initialize_fn, onDecoded_fn;
403
+ var AudioRenderPipeline = class {
404
+ constructor(opts) {
405
+ __privateAdd(this, _AudioRenderPipeline_instances);
406
+ __privateAdd(this, _context);
407
+ __privateAdd(this, _pacer);
408
+ __privateAdd(this, _mapper);
409
+ __privateAdd(this, _codec);
410
+ __privateAdd(this, _packetId);
411
+ __privateAdd(this, _sampleRate);
412
+ __privateAdd(this, _channels);
413
+ __privateAdd(this, _description);
414
+ __privateAdd(this, _latencyMs);
415
+ __privateAdd(this, _startupFrames2);
416
+ __privateAdd(this, _startupThresholdFrames);
417
+ __privateAdd(this, _capacityFrames);
418
+ __privateAdd(this, _diag);
419
+ __privateAdd(this, _warmupFrames);
420
+ __privateAdd(this, _onState);
421
+ __privateAdd(this, _onDiag);
422
+ __privateAdd(this, _onError);
423
+ __privateAdd(this, _reassemblyPolicy);
424
+ __privateAdd(this, _decoder, null);
425
+ __privateAdd(this, _pipeline, null);
426
+ __privateAdd(this, _worklet, null);
427
+ __privateAdd(this, _fecClient);
428
+ __privateAdd(this, _closed, false);
429
+ __privateAdd(this, _readyPromise, null);
430
+ __privateAdd(this, _workletGeneration, 0);
431
+ __privateAdd(this, _startupReleased, false);
432
+ __privateSet(this, _context, opts.context);
433
+ __privateSet(this, _mapper, opts.mapper);
434
+ __privateSet(this, _codec, opts.codec);
435
+ __privateSet(this, _packetId, opts.packetId);
436
+ __privateSet(this, _sampleRate, opts.sampleRate);
437
+ __privateSet(this, _channels, opts.channels);
438
+ __privateSet(this, _description, opts.description);
439
+ __privateSet(this, _latencyMs, opts.latencyMs);
440
+ __privateSet(this, _startupFrames2, opts.startupFrames);
441
+ __privateSet(this, _startupThresholdFrames, opts.startupFrames ?? Math.ceil(opts.sampleRate * (opts.latencyMs / 1e3)));
442
+ __privateSet(this, _capacityFrames, opts.capacityFrames);
443
+ __privateSet(this, _diag, opts.diag ?? false);
444
+ __privateSet(this, _warmupFrames, opts.warmupFrames ?? 0);
445
+ __privateSet(this, _onState, opts.onState);
446
+ __privateSet(this, _onDiag, opts.onDiag);
447
+ __privateSet(this, _onError, opts.onError);
448
+ __privateSet(this, _fecClient, opts.fecClient);
449
+ __privateSet(this, _reassemblyPolicy, opts.reassemblyPolicy);
450
+ const auDurationMs = auDurationMsFromCodec(opts.codec, opts.sampleRate);
451
+ __privateSet(this, _pacer, new FrameCountPacer({
452
+ frameDurationMs: auDurationMs,
453
+ mapper: opts.mapper,
454
+ warmupFrames: __privateGet(this, _warmupFrames)
455
+ }));
456
+ }
457
+ /** Load worklet module + create decoder + pipeline. Call once. */
458
+ async ready() {
459
+ if (__privateGet(this, _readyPromise)) return __privateGet(this, _readyPromise);
460
+ __privateSet(this, _readyPromise, __privateMethod(this, _AudioRenderPipeline_instances, initialize_fn).call(this));
461
+ return __privateGet(this, _readyPromise);
462
+ }
463
+ /** Feed one MoQ object (raw MMTP packet). */
464
+ feedMoqObject(packet) {
465
+ __privateGet(this, _pipeline)?.feedMoqObject(packet);
466
+ }
467
+ /** ms to sleep before the next object read. 0 when not anchored / not ahead. */
468
+ paceSleepMs() {
469
+ return __privateGet(this, _pacer).computeSleepMs();
470
+ }
471
+ /** Pacer snapshot (for diagnostics / UI). */
472
+ get pacerSnapshot() {
473
+ return __privateGet(this, _pacer).snapshot;
474
+ }
475
+ /** Reset pacer on source switch (MoQ ↔ multicast). */
476
+ resetPacer() {
477
+ __privateGet(this, _pacer).reset();
478
+ }
479
+ /** Drop queued PCM and its timestamp epoch at an explicit source boundary. */
480
+ resetPlayout(startUnstalled = false) {
481
+ __privateGet(this, _pacer).reset();
482
+ __privateSet(this, _startupReleased, true);
483
+ const message = {
484
+ type: "reset",
485
+ generation: ++__privateWrapper(this, _workletGeneration)._,
486
+ startUnstalled
487
+ };
488
+ __privateGet(this, _worklet)?.port.postMessage(message);
489
+ }
490
+ /** Node to connect to destination / gain. */
491
+ get rootNode() {
492
+ if (!__privateGet(this, _worklet)) throw new Error("AudioRenderPipeline.ready() must resolve first");
493
+ return __privateGet(this, _worklet);
494
+ }
495
+ close() {
496
+ if (__privateGet(this, _closed)) return;
497
+ __privateSet(this, _closed, true);
498
+ try {
499
+ __privateGet(this, _decoder)?.close();
500
+ } catch {
501
+ }
502
+ try {
503
+ __privateGet(this, _pipeline)?.dispose();
504
+ } catch {
505
+ }
506
+ try {
507
+ __privateGet(this, _worklet)?.disconnect();
508
+ } catch {
509
+ }
510
+ __privateSet(this, _decoder, null);
511
+ __privateSet(this, _pipeline, null);
512
+ __privateSet(this, _worklet, null);
513
+ }
514
+ };
515
+ _context = new WeakMap();
516
+ _pacer = new WeakMap();
517
+ _mapper = new WeakMap();
518
+ _codec = new WeakMap();
519
+ _packetId = new WeakMap();
520
+ _sampleRate = new WeakMap();
521
+ _channels = new WeakMap();
522
+ _description = new WeakMap();
523
+ _latencyMs = new WeakMap();
524
+ _startupFrames2 = new WeakMap();
525
+ _startupThresholdFrames = new WeakMap();
526
+ _capacityFrames = new WeakMap();
527
+ _diag = new WeakMap();
528
+ _warmupFrames = new WeakMap();
529
+ _onState = new WeakMap();
530
+ _onDiag = new WeakMap();
531
+ _onError = new WeakMap();
532
+ _reassemblyPolicy = new WeakMap();
533
+ _decoder = new WeakMap();
534
+ _pipeline = new WeakMap();
535
+ _worklet = new WeakMap();
536
+ _fecClient = new WeakMap();
537
+ _closed = new WeakMap();
538
+ _readyPromise = new WeakMap();
539
+ _workletGeneration = new WeakMap();
540
+ _startupReleased = new WeakMap();
541
+ _AudioRenderPipeline_instances = new WeakSet();
542
+ initialize_fn = async function() {
543
+ await __privateGet(this, _context).audioWorklet.addModule(workletModuleUrl());
544
+ const worklet = new AudioWorkletNode(__privateGet(this, _context), WORKLET_PROCESSOR_NAME, {
545
+ numberOfInputs: 0,
546
+ numberOfOutputs: 1,
547
+ outputChannelCount: [__privateGet(this, _channels)]
548
+ });
549
+ const initMsg = {
550
+ type: "init",
551
+ generation: ++__privateWrapper(this, _workletGeneration)._,
552
+ channels: __privateGet(this, _channels),
553
+ rate: __privateGet(this, _sampleRate),
554
+ latencyMs: __privateGet(this, _latencyMs),
555
+ startupFrames: __privateGet(this, _startupFrames2),
556
+ capacityFrames: __privateGet(this, _capacityFrames),
557
+ holdUntilStart: true,
558
+ diag: __privateGet(this, _diag)
559
+ };
560
+ worklet.port.postMessage(initMsg);
561
+ worklet.port.onmessage = (ev) => {
562
+ var _a, _b;
563
+ const m = ev.data;
564
+ if (m.type === "state") {
565
+ if (m.generation !== __privateGet(this, _workletGeneration)) return;
566
+ (_a = __privateGet(this, _onState)) == null ? void 0 : _a.call(this, {
567
+ timestampUs: m.timestamp,
568
+ stalled: m.stalled,
569
+ bufferedFrames: m.bufferedFrames,
570
+ writtenFrames: m.writtenFrames
571
+ });
572
+ } else if (m.type === "ringBufDiag") {
573
+ if (m.generation !== __privateGet(this, _workletGeneration)) return;
574
+ (_b = __privateGet(this, _onDiag)) == null ? void 0 : _b.call(this, {
575
+ reads: m.reads,
576
+ avgFill: m.avgFill,
577
+ capacity: m.capacity,
578
+ skipsPerSec: m.skipsPerSec,
579
+ dupsPerSec: m.dupsPerSec,
580
+ overflowSamplesPerSec: m.overflowSamplesPerSec,
581
+ underflowSamplesPerSec: m.underflowSamplesPerSec
582
+ });
583
+ } else if (m.type === "writeAck") {
584
+ if (m.generation !== __privateGet(this, _workletGeneration) || __privateGet(this, _startupReleased) || m.bufferedFrames < __privateGet(this, _startupThresholdFrames)) return;
585
+ __privateSet(this, _startupReleased, true);
586
+ const start = {
587
+ type: "start",
588
+ generation: __privateGet(this, _workletGeneration)
589
+ };
590
+ worklet.port.postMessage(start);
591
+ }
592
+ };
593
+ __privateSet(this, _worklet, worklet);
594
+ const decoder = new AudioDecoder({
595
+ output: (data) => __privateMethod(this, _AudioRenderPipeline_instances, onDecoded_fn).call(this, data),
596
+ error: (err) => {
597
+ var _a;
598
+ return (_a = __privateGet(this, _onError)) == null ? void 0 : _a.call(this, err);
599
+ }
600
+ });
601
+ const config = {
602
+ codec: __privateGet(this, _codec),
603
+ sampleRate: __privateGet(this, _sampleRate),
604
+ numberOfChannels: __privateGet(this, _channels),
605
+ ...__privateGet(this, _description) ? { description: __privateGet(this, _description) } : {}
606
+ };
607
+ decoder.configure(config);
608
+ __privateSet(this, _decoder, decoder);
609
+ const pipeline = new MmtpDecodePipeline();
610
+ pipeline.configure({
611
+ codec: __privateGet(this, _codec),
612
+ packetId: __privateGet(this, _packetId),
613
+ description: __privateGet(this, _description),
614
+ reorderWindow: 0,
615
+ // audio doesn't need reorder — AAC/Opus frames are self-contained
616
+ reassemblyPolicy: __privateGet(this, _reassemblyPolicy)
617
+ });
618
+ if (__privateGet(this, _fecClient)) pipeline.setFecClient(__privateGet(this, _fecClient));
619
+ pipeline.onFrame((codecData, meta) => {
620
+ var _a;
621
+ if (!__privateGet(this, _decoder) || __privateGet(this, _decoder).state !== "configured") return;
622
+ if (codecData.byteLength === 0) return;
623
+ __privateGet(this, _pacer).notifyFrame();
624
+ try {
625
+ __privateGet(this, _decoder).decode(new EncodedAudioChunk({
626
+ type: "key",
627
+ data: codecData,
628
+ timestamp: meta.timestamp
629
+ }));
630
+ } catch (err) {
631
+ (_a = __privateGet(this, _onError)) == null ? void 0 : _a.call(this, err);
632
+ }
633
+ });
634
+ __privateSet(this, _pipeline, pipeline);
635
+ };
636
+ // ─── Private ─────────────────────────────────────────────────────
637
+ onDecoded_fn = function(sample) {
638
+ if (__privateGet(this, _closed) || !__privateGet(this, _worklet)) {
639
+ sample.close();
640
+ return;
641
+ }
642
+ const timestamp = sample.timestamp;
643
+ const channelData = [];
644
+ for (let ch = 0; ch < sample.numberOfChannels; ch++) {
645
+ const data = new Float32Array(sample.numberOfFrames);
646
+ sample.copyTo(data, { format: "f32-planar", planeIndex: ch });
647
+ channelData.push(data);
648
+ }
649
+ sample.close();
650
+ const msg = {
651
+ type: "data",
652
+ data: channelData,
653
+ timestamp
654
+ };
655
+ __privateGet(this, _worklet).port.postMessage(msg, channelData.map((d) => d.buffer));
656
+ };
657
+ export {
658
+ AudioRenderPipeline,
659
+ AudioRingBuffer,
660
+ WORKLET_PROCESSOR_NAME,
661
+ deriveAudioBurstBufferPlan,
662
+ workletModuleUrl
663
+ };
664
+ //# sourceMappingURL=index.js.map