@blockcast/mmt-render 0.1.0-main.02dfe3276f87

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