@blockcast/mmt-render 0.1.0-main.5dd8358ae902

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 +372 -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 +640 -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 +71 -0
  36. package/dist/pacing/frame-pacer.d.ts.map +1 -0
  37. package/dist/pacing/frame-pacer.js +89 -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 +166 -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 +247 -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 +247 -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 +129 -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,372 @@
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-render-pipeline.ts
19
+ import { MmtpDecodePipeline } from "@blockcast/mmt-container/mmtp-decode-pipeline";
20
+
21
+ // src/pacing/frame-pacer.ts
22
+ var _frameCount, _anchorWallMs, _anchored;
23
+ var FrameCountPacer = class {
24
+ constructor(opts) {
25
+ __privateAdd(this, _frameCount, 0);
26
+ __privateAdd(this, _anchorWallMs, 0);
27
+ __privateAdd(this, _anchored, false);
28
+ if (!(opts.frameDurationMs > 0)) {
29
+ throw new Error("frameDurationMs must be > 0");
30
+ }
31
+ this.frameDurationMs = opts.frameDurationMs;
32
+ this.thresholdMs = opts.mapper.pacingThresholdMs;
33
+ this.warmupFrames = Math.max(0, opts.warmupFrames ?? 0);
34
+ }
35
+ /** Call on every emitted decoded frame (AU or picture). Anchors on first call. */
36
+ notifyFrame() {
37
+ if (!__privateGet(this, _anchored)) {
38
+ __privateSet(this, _anchorWallMs, now());
39
+ __privateSet(this, _anchored, true);
40
+ }
41
+ __privateWrapper(this, _frameCount)._++;
42
+ }
43
+ /**
44
+ * Compute sleep ms before reading the next MoQ object.
45
+ * Returns 0 when:
46
+ * - pacing is disabled (NullBlockMapper → threshold=0)
47
+ * - the anchor is not yet set
48
+ * - still in warmup
49
+ * - decoder is not ahead of wall clock by more than threshold
50
+ * Otherwise returns aheadMs - thresholdMs/2 (leaves half the threshold as headroom).
51
+ */
52
+ computeSleepMs() {
53
+ if (this.thresholdMs <= 0) return 0;
54
+ if (!__privateGet(this, _anchored)) return 0;
55
+ if (__privateGet(this, _frameCount) <= this.warmupFrames) return 0;
56
+ const mediaMs = __privateGet(this, _frameCount) * this.frameDurationMs;
57
+ const wallMs = now() - __privateGet(this, _anchorWallMs);
58
+ const aheadMs = mediaMs - wallMs;
59
+ if (aheadMs <= this.thresholdMs) return 0;
60
+ return aheadMs - this.thresholdMs / 2;
61
+ }
62
+ /** Reset anchor + counter. Call on source switch (MoQ ↔ multicast). */
63
+ reset() {
64
+ __privateSet(this, _frameCount, 0);
65
+ __privateSet(this, _anchorWallMs, 0);
66
+ __privateSet(this, _anchored, false);
67
+ }
68
+ get snapshot() {
69
+ const mediaMs = __privateGet(this, _frameCount) * this.frameDurationMs;
70
+ const wallMs = __privateGet(this, _anchored) ? now() - __privateGet(this, _anchorWallMs) : 0;
71
+ return {
72
+ frameCount: __privateGet(this, _frameCount),
73
+ mediaMs,
74
+ wallMs,
75
+ aheadMs: mediaMs - wallMs,
76
+ thresholdMs: this.thresholdMs,
77
+ anchored: __privateGet(this, _anchored)
78
+ };
79
+ }
80
+ };
81
+ _frameCount = new WeakMap();
82
+ _anchorWallMs = new WeakMap();
83
+ _anchored = new WeakMap();
84
+ function now() {
85
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
86
+ return performance.now();
87
+ }
88
+ return Date.now();
89
+ }
90
+
91
+ // src/pacing/au-duration.ts
92
+ function auDurationMsFromCodec(codec, sampleRate) {
93
+ if (!(sampleRate > 0)) throw new Error("sampleRate must be > 0");
94
+ if (codec.startsWith("opus") || codec.startsWith("Opus")) {
95
+ return 960 / sampleRate * 1e3;
96
+ }
97
+ if (codec.startsWith("mp4a") || codec.startsWith("AAC") || codec.startsWith("aac")) {
98
+ return 1024 / sampleRate * 1e3;
99
+ }
100
+ if (codec.startsWith("flac") || codec.startsWith("fLaC")) {
101
+ return 4096 / sampleRate * 1e3;
102
+ }
103
+ throw new Error(`unknown audio codec for AU duration derivation: ${codec}`);
104
+ }
105
+
106
+ // src/audio/worklet-url.ts
107
+ function workletModuleUrl() {
108
+ const base = new URL("../worklet/render-worklet.js", import.meta.url);
109
+ return base.href;
110
+ }
111
+ var WORKLET_PROCESSOR_NAME = "mmt-render";
112
+
113
+ // src/audio/audio-render-pipeline.ts
114
+ var _context, _pacer, _mapper, _codec, _packetId, _sampleRate, _channels, _description, _latencyMs, _startupFrames, _startupThresholdFrames, _capacityFrames, _diag, _warmupFrames, _onState, _onDiag, _onError, _reassemblyPolicy, _decoder, _pipeline, _worklet, _fecClient, _closed, _readyPromise, _workletGeneration, _startupReleased, _AudioRenderPipeline_instances, initialize_fn, onDecoded_fn;
115
+ var AudioRenderPipeline = class {
116
+ constructor(opts) {
117
+ __privateAdd(this, _AudioRenderPipeline_instances);
118
+ __privateAdd(this, _context);
119
+ __privateAdd(this, _pacer);
120
+ __privateAdd(this, _mapper);
121
+ __privateAdd(this, _codec);
122
+ __privateAdd(this, _packetId);
123
+ __privateAdd(this, _sampleRate);
124
+ __privateAdd(this, _channels);
125
+ __privateAdd(this, _description);
126
+ __privateAdd(this, _latencyMs);
127
+ __privateAdd(this, _startupFrames);
128
+ __privateAdd(this, _startupThresholdFrames);
129
+ __privateAdd(this, _capacityFrames);
130
+ __privateAdd(this, _diag);
131
+ __privateAdd(this, _warmupFrames);
132
+ __privateAdd(this, _onState);
133
+ __privateAdd(this, _onDiag);
134
+ __privateAdd(this, _onError);
135
+ __privateAdd(this, _reassemblyPolicy);
136
+ __privateAdd(this, _decoder, null);
137
+ __privateAdd(this, _pipeline, null);
138
+ __privateAdd(this, _worklet, null);
139
+ __privateAdd(this, _fecClient);
140
+ __privateAdd(this, _closed, false);
141
+ __privateAdd(this, _readyPromise, null);
142
+ __privateAdd(this, _workletGeneration, 0);
143
+ __privateAdd(this, _startupReleased, false);
144
+ __privateSet(this, _context, opts.context);
145
+ __privateSet(this, _mapper, opts.mapper);
146
+ __privateSet(this, _codec, opts.codec);
147
+ __privateSet(this, _packetId, opts.packetId);
148
+ __privateSet(this, _sampleRate, opts.sampleRate);
149
+ __privateSet(this, _channels, opts.channels);
150
+ __privateSet(this, _description, opts.description);
151
+ __privateSet(this, _latencyMs, opts.latencyMs);
152
+ __privateSet(this, _startupFrames, opts.startupFrames);
153
+ __privateSet(this, _startupThresholdFrames, opts.startupFrames ?? Math.ceil(opts.sampleRate * (opts.latencyMs / 1e3)));
154
+ __privateSet(this, _capacityFrames, opts.capacityFrames);
155
+ __privateSet(this, _diag, opts.diag ?? false);
156
+ __privateSet(this, _warmupFrames, opts.warmupFrames ?? 0);
157
+ __privateSet(this, _onState, opts.onState);
158
+ __privateSet(this, _onDiag, opts.onDiag);
159
+ __privateSet(this, _onError, opts.onError);
160
+ __privateSet(this, _fecClient, opts.fecClient);
161
+ __privateSet(this, _reassemblyPolicy, opts.reassemblyPolicy);
162
+ const auDurationMs = auDurationMsFromCodec(opts.codec, opts.sampleRate);
163
+ __privateSet(this, _pacer, new FrameCountPacer({
164
+ frameDurationMs: auDurationMs,
165
+ mapper: opts.mapper,
166
+ warmupFrames: __privateGet(this, _warmupFrames)
167
+ }));
168
+ }
169
+ /** Load worklet module + create decoder + pipeline. Call once. */
170
+ async ready() {
171
+ if (__privateGet(this, _readyPromise)) return __privateGet(this, _readyPromise);
172
+ __privateSet(this, _readyPromise, __privateMethod(this, _AudioRenderPipeline_instances, initialize_fn).call(this));
173
+ return __privateGet(this, _readyPromise);
174
+ }
175
+ /** Feed one MoQ object (raw MMTP packet). */
176
+ feedMoqObject(packet) {
177
+ __privateGet(this, _pipeline)?.feedMoqObject(packet);
178
+ }
179
+ /** ms to sleep before the next object read. 0 when not anchored / not ahead. */
180
+ paceSleepMs() {
181
+ return __privateGet(this, _pacer).computeSleepMs();
182
+ }
183
+ /** Pacer snapshot (for diagnostics / UI). */
184
+ get pacerSnapshot() {
185
+ return __privateGet(this, _pacer).snapshot;
186
+ }
187
+ /** Reset pacer on source switch (MoQ ↔ multicast). */
188
+ resetPacer() {
189
+ __privateGet(this, _pacer).reset();
190
+ }
191
+ /** Drop queued PCM and its timestamp epoch at an explicit source boundary. */
192
+ resetPlayout(startUnstalled = false) {
193
+ __privateGet(this, _pacer).reset();
194
+ __privateSet(this, _startupReleased, true);
195
+ const message = {
196
+ type: "reset",
197
+ generation: ++__privateWrapper(this, _workletGeneration)._,
198
+ startUnstalled
199
+ };
200
+ __privateGet(this, _worklet)?.port.postMessage(message);
201
+ }
202
+ /** Node to connect to destination / gain. */
203
+ get rootNode() {
204
+ if (!__privateGet(this, _worklet)) throw new Error("AudioRenderPipeline.ready() must resolve first");
205
+ return __privateGet(this, _worklet);
206
+ }
207
+ close() {
208
+ if (__privateGet(this, _closed)) return;
209
+ __privateSet(this, _closed, true);
210
+ try {
211
+ __privateGet(this, _decoder)?.close();
212
+ } catch {
213
+ }
214
+ try {
215
+ __privateGet(this, _pipeline)?.dispose();
216
+ } catch {
217
+ }
218
+ try {
219
+ __privateGet(this, _worklet)?.disconnect();
220
+ } catch {
221
+ }
222
+ __privateSet(this, _decoder, null);
223
+ __privateSet(this, _pipeline, null);
224
+ __privateSet(this, _worklet, null);
225
+ }
226
+ };
227
+ _context = new WeakMap();
228
+ _pacer = new WeakMap();
229
+ _mapper = new WeakMap();
230
+ _codec = new WeakMap();
231
+ _packetId = new WeakMap();
232
+ _sampleRate = new WeakMap();
233
+ _channels = new WeakMap();
234
+ _description = new WeakMap();
235
+ _latencyMs = new WeakMap();
236
+ _startupFrames = new WeakMap();
237
+ _startupThresholdFrames = new WeakMap();
238
+ _capacityFrames = new WeakMap();
239
+ _diag = new WeakMap();
240
+ _warmupFrames = new WeakMap();
241
+ _onState = new WeakMap();
242
+ _onDiag = new WeakMap();
243
+ _onError = new WeakMap();
244
+ _reassemblyPolicy = new WeakMap();
245
+ _decoder = new WeakMap();
246
+ _pipeline = new WeakMap();
247
+ _worklet = new WeakMap();
248
+ _fecClient = new WeakMap();
249
+ _closed = new WeakMap();
250
+ _readyPromise = new WeakMap();
251
+ _workletGeneration = new WeakMap();
252
+ _startupReleased = new WeakMap();
253
+ _AudioRenderPipeline_instances = new WeakSet();
254
+ initialize_fn = async function() {
255
+ await __privateGet(this, _context).audioWorklet.addModule(workletModuleUrl());
256
+ const worklet = new AudioWorkletNode(__privateGet(this, _context), WORKLET_PROCESSOR_NAME, {
257
+ numberOfInputs: 0,
258
+ numberOfOutputs: 1,
259
+ outputChannelCount: [__privateGet(this, _channels)]
260
+ });
261
+ const initMsg = {
262
+ type: "init",
263
+ generation: ++__privateWrapper(this, _workletGeneration)._,
264
+ channels: __privateGet(this, _channels),
265
+ rate: __privateGet(this, _sampleRate),
266
+ latencyMs: __privateGet(this, _latencyMs),
267
+ startupFrames: __privateGet(this, _startupFrames),
268
+ capacityFrames: __privateGet(this, _capacityFrames),
269
+ holdUntilStart: true,
270
+ diag: __privateGet(this, _diag)
271
+ };
272
+ worklet.port.postMessage(initMsg);
273
+ worklet.port.onmessage = (ev) => {
274
+ var _a, _b;
275
+ const m = ev.data;
276
+ if (m.type === "state") {
277
+ if (m.generation !== __privateGet(this, _workletGeneration)) return;
278
+ (_a = __privateGet(this, _onState)) == null ? void 0 : _a.call(this, {
279
+ timestampUs: m.timestamp,
280
+ stalled: m.stalled,
281
+ bufferedFrames: m.bufferedFrames,
282
+ writtenFrames: m.writtenFrames
283
+ });
284
+ } else if (m.type === "ringBufDiag") {
285
+ if (m.generation !== __privateGet(this, _workletGeneration)) return;
286
+ (_b = __privateGet(this, _onDiag)) == null ? void 0 : _b.call(this, {
287
+ reads: m.reads,
288
+ avgFill: m.avgFill,
289
+ capacity: m.capacity,
290
+ skipsPerSec: m.skipsPerSec,
291
+ dupsPerSec: m.dupsPerSec,
292
+ overflowSamplesPerSec: m.overflowSamplesPerSec,
293
+ underflowSamplesPerSec: m.underflowSamplesPerSec
294
+ });
295
+ } else if (m.type === "writeAck") {
296
+ if (m.generation !== __privateGet(this, _workletGeneration) || __privateGet(this, _startupReleased) || m.bufferedFrames < __privateGet(this, _startupThresholdFrames)) return;
297
+ __privateSet(this, _startupReleased, true);
298
+ const start = {
299
+ type: "start",
300
+ generation: __privateGet(this, _workletGeneration)
301
+ };
302
+ worklet.port.postMessage(start);
303
+ }
304
+ };
305
+ __privateSet(this, _worklet, worklet);
306
+ const decoder = new AudioDecoder({
307
+ output: (data) => __privateMethod(this, _AudioRenderPipeline_instances, onDecoded_fn).call(this, data),
308
+ error: (err) => {
309
+ var _a;
310
+ return (_a = __privateGet(this, _onError)) == null ? void 0 : _a.call(this, err);
311
+ }
312
+ });
313
+ const config = {
314
+ codec: __privateGet(this, _codec),
315
+ sampleRate: __privateGet(this, _sampleRate),
316
+ numberOfChannels: __privateGet(this, _channels),
317
+ ...__privateGet(this, _description) ? { description: __privateGet(this, _description) } : {}
318
+ };
319
+ decoder.configure(config);
320
+ __privateSet(this, _decoder, decoder);
321
+ const pipeline = new MmtpDecodePipeline();
322
+ pipeline.configure({
323
+ codec: __privateGet(this, _codec),
324
+ packetId: __privateGet(this, _packetId),
325
+ description: __privateGet(this, _description),
326
+ reorderWindow: 0,
327
+ // audio doesn't need reorder — AAC/Opus frames are self-contained
328
+ reassemblyPolicy: __privateGet(this, _reassemblyPolicy)
329
+ });
330
+ if (__privateGet(this, _fecClient)) pipeline.setFecClient(__privateGet(this, _fecClient));
331
+ pipeline.onFrame((codecData, meta) => {
332
+ var _a;
333
+ if (!__privateGet(this, _decoder) || __privateGet(this, _decoder).state !== "configured") return;
334
+ if (codecData.byteLength === 0) return;
335
+ __privateGet(this, _pacer).notifyFrame();
336
+ try {
337
+ __privateGet(this, _decoder).decode(new EncodedAudioChunk({
338
+ type: "key",
339
+ data: codecData,
340
+ timestamp: meta.timestamp
341
+ }));
342
+ } catch (err) {
343
+ (_a = __privateGet(this, _onError)) == null ? void 0 : _a.call(this, err);
344
+ }
345
+ });
346
+ __privateSet(this, _pipeline, pipeline);
347
+ };
348
+ // ─── Private ─────────────────────────────────────────────────────
349
+ onDecoded_fn = function(sample) {
350
+ if (__privateGet(this, _closed) || !__privateGet(this, _worklet)) {
351
+ sample.close();
352
+ return;
353
+ }
354
+ const timestamp = sample.timestamp;
355
+ const channelData = [];
356
+ for (let ch = 0; ch < sample.numberOfChannels; ch++) {
357
+ const data = new Float32Array(sample.numberOfFrames);
358
+ sample.copyTo(data, { format: "f32-planar", planeIndex: ch });
359
+ channelData.push(data);
360
+ }
361
+ sample.close();
362
+ const msg = {
363
+ type: "data",
364
+ data: channelData,
365
+ timestamp
366
+ };
367
+ __privateGet(this, _worklet).port.postMessage(msg, channelData.map((d) => d.buffer));
368
+ };
369
+ export {
370
+ AudioRenderPipeline
371
+ };
372
+ //# sourceMappingURL=audio-render-pipeline.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/audio/audio-render-pipeline.ts", "../../src/pacing/frame-pacer.ts", "../../src/pacing/au-duration.ts", "../../src/audio/worklet-url.ts"],
4
+ "sourcesContent": ["/**\n * AudioRenderPipeline \u2014 end-to-end audio render for MoQ/MMT players.\n *\n * Pipeline: MoQ object \u2192 MmtpDecodePipeline \u2192 WebCodecs AudioDecoder\n * \u2192 AudioWorkletNode (exact-timestamp FIFO)\n *\n * The consumer:\n * 1. constructs with codec/sampleRate/channels/mapper from catalog\n * 2. awaits ready()\n * 3. calls feedMoqObject(packet) for each arriving MoQ object\n * 4. between objects, awaits paceSleepMs() to throttle burst delivery\n * 5. connects rootNode to an AudioContext destination (or a GainNode)\n * 6. close() on teardown\n *\n * Pacing uses FrameCountPacer (anchor on first decoded AU, frame count \u00D7 AU\n * duration) with threshold = mapper.pacingThresholdMs \u2014 NOT MPU timestamps\n * (ambiguous under FEC interleave).\n */\n\nimport { MmtpDecodePipeline, type PipelineFecClient } from '@blockcast/mmt-container/mmtp-decode-pipeline'\nimport type { MfuReassemblyPolicy } from '@blockcast/mmt-container/mfu-reassembly-policy'\nimport type { FecBlockMapper } from '@blockcast/mmt-fec'\nimport { FrameCountPacer } from '../pacing/frame-pacer.js'\nimport { auDurationMsFromCodec } from '../pacing/au-duration.js'\nimport type {\n ToMain,\n DataMessage,\n InitMessage,\n ResetMessage,\n StartMessage,\n} from './render-messages.js'\nimport { WORKLET_PROCESSOR_NAME, workletModuleUrl } from './worklet-url.js'\n\nexport interface AudioRenderPipelineOpts {\n context: AudioContext\n codec: string\n /** MMTP packet_id for this audio track \u2014 from catalog. */\n packetId?: number\n sampleRate: number\n channels: number\n description?: Uint8Array\n mapper: FecBlockMapper\n fecClient?: PipelineFecClient\n /** Reliable MoQ is clock-free; datagram deadlines come from catalog/in-band timing. */\n reassemblyPolicy: MfuReassemblyPolicy\n /** Catalog-derived PCM startup buffer in milliseconds. */\n latencyMs: number\n /** Exact PCM startup threshold when catalog grouping is codec-aligned. */\n startupFrames?: number\n /** Exact PCM storage ceiling, including one successor delivery burst. */\n capacityFrames?: number\n /** Enable ring-buffer telemetry messages. Default false. */\n diag?: boolean\n /** Called when worklet reports state (playback timestamp + exact buffer accounting). Optional. */\n onState?: (state: {\n timestampUs: number | undefined\n stalled: boolean\n bufferedFrames: number\n writtenFrames: number\n }) => void\n /** Called when worklet reports ring-buffer diag (telemetry). Optional. */\n onDiag?: (diag: {\n reads: number; avgFill: number; capacity: number\n skipsPerSec: number; dupsPerSec: number; overflowSamplesPerSec: number\n underflowSamplesPerSec: number\n }) => void\n /** Warmup frames before pacing engages. Default 0 (audio tolerates instant pacing). */\n warmupFrames?: number\n /** Audio underflow / config event logger. Optional. */\n onError?: (err: unknown) => void\n}\n\nexport class AudioRenderPipeline {\n readonly #context: AudioContext\n readonly #pacer: FrameCountPacer\n readonly #mapper: FecBlockMapper\n readonly #codec: string\n readonly #packetId: number | undefined\n readonly #sampleRate: number\n readonly #channels: number\n readonly #description?: Uint8Array\n readonly #latencyMs: number\n readonly #startupFrames?: number\n readonly #startupThresholdFrames: number\n readonly #capacityFrames?: number\n readonly #diag: boolean\n readonly #warmupFrames: number\n readonly #onState?: AudioRenderPipelineOpts['onState']\n readonly #onDiag?: AudioRenderPipelineOpts['onDiag']\n readonly #onError?: AudioRenderPipelineOpts['onError']\n readonly #reassemblyPolicy: MfuReassemblyPolicy\n\n #decoder: AudioDecoder | null = null\n #pipeline: MmtpDecodePipeline | null = null\n #worklet: AudioWorkletNode | null = null\n #fecClient?: PipelineFecClient\n #closed = false\n #readyPromise: Promise<void> | null = null\n #workletGeneration = 0\n #startupReleased = false\n\n constructor(opts: AudioRenderPipelineOpts) {\n this.#context = opts.context\n this.#mapper = opts.mapper\n this.#codec = opts.codec\n this.#packetId = opts.packetId\n this.#sampleRate = opts.sampleRate\n this.#channels = opts.channels\n this.#description = opts.description\n this.#latencyMs = opts.latencyMs\n this.#startupFrames = opts.startupFrames\n this.#startupThresholdFrames = opts.startupFrames\n ?? Math.ceil(opts.sampleRate * (opts.latencyMs / 1000))\n this.#capacityFrames = opts.capacityFrames\n this.#diag = opts.diag ?? false\n this.#warmupFrames = opts.warmupFrames ?? 0\n this.#onState = opts.onState\n this.#onDiag = opts.onDiag\n this.#onError = opts.onError\n this.#fecClient = opts.fecClient\n this.#reassemblyPolicy = opts.reassemblyPolicy\n\n // AU duration from codec + sampleRate. Keep inside the lib so consumers\n // don't re-derive it.\n const auDurationMs = auDurationMsFromCodec(opts.codec, opts.sampleRate)\n this.#pacer = new FrameCountPacer({\n frameDurationMs: auDurationMs,\n mapper: opts.mapper,\n warmupFrames: this.#warmupFrames,\n })\n }\n\n /** Load worklet module + create decoder + pipeline. Call once. */\n async ready(): Promise<void> {\n if (this.#readyPromise) return this.#readyPromise\n this.#readyPromise = this.#initialize()\n return this.#readyPromise\n }\n\n async #initialize(): Promise<void> {\n // 1. Load shared worklet module.\n await this.#context.audioWorklet.addModule(workletModuleUrl())\n\n // 2. Create worklet node.\n const worklet = new AudioWorkletNode(this.#context, WORKLET_PROCESSOR_NAME, {\n numberOfInputs: 0,\n numberOfOutputs: 1,\n outputChannelCount: [this.#channels],\n })\n const initMsg: InitMessage = {\n type: 'init',\n generation: ++this.#workletGeneration,\n channels: this.#channels,\n rate: this.#sampleRate,\n latencyMs: this.#latencyMs,\n startupFrames: this.#startupFrames,\n capacityFrames: this.#capacityFrames,\n holdUntilStart: true,\n diag: this.#diag,\n }\n worklet.port.postMessage(initMsg)\n worklet.port.onmessage = (ev: MessageEvent<ToMain>) => {\n const m = ev.data\n if (m.type === 'state') {\n if (m.generation !== this.#workletGeneration) return\n this.#onState?.({\n timestampUs: m.timestamp,\n stalled: m.stalled,\n bufferedFrames: m.bufferedFrames,\n writtenFrames: m.writtenFrames,\n })\n } else if (m.type === 'ringBufDiag') {\n if (m.generation !== this.#workletGeneration) return\n this.#onDiag?.({\n reads: m.reads, avgFill: m.avgFill, capacity: m.capacity,\n skipsPerSec: m.skipsPerSec, dupsPerSec: m.dupsPerSec,\n overflowSamplesPerSec: m.overflowSamplesPerSec,\n underflowSamplesPerSec: m.underflowSamplesPerSec,\n })\n } else if (m.type === 'writeAck') {\n if (\n m.generation !== this.#workletGeneration ||\n this.#startupReleased ||\n m.bufferedFrames < this.#startupThresholdFrames\n ) return\n this.#startupReleased = true\n const start: StartMessage = {\n type: 'start',\n generation: this.#workletGeneration,\n }\n worklet.port.postMessage(start)\n }\n }\n this.#worklet = worklet\n\n // 3. Create decoder.\n const decoder = new AudioDecoder({\n output: (data) => this.#onDecoded(data),\n error: (err) => this.#onError?.(err),\n })\n const config: AudioDecoderConfig = {\n codec: this.#codec,\n sampleRate: this.#sampleRate,\n numberOfChannels: this.#channels,\n ...(this.#description ? { description: this.#description } : {}),\n }\n decoder.configure(config)\n this.#decoder = decoder\n\n // 4. Create decode pipeline.\n const pipeline = new MmtpDecodePipeline()\n pipeline.configure({\n codec: this.#codec,\n packetId: this.#packetId,\n description: this.#description,\n reorderWindow: 0, // audio doesn't need reorder \u2014 AAC/Opus frames are self-contained\n reassemblyPolicy: this.#reassemblyPolicy,\n })\n if (this.#fecClient) pipeline.setFecClient(this.#fecClient)\n pipeline.onFrame((codecData, meta) => {\n if (!this.#decoder || this.#decoder.state !== 'configured') return\n if (codecData.byteLength === 0) return\n this.#pacer.notifyFrame()\n try {\n this.#decoder.decode(new EncodedAudioChunk({\n type: 'key',\n data: codecData,\n timestamp: meta.timestamp,\n }))\n } catch (err) {\n this.#onError?.(err)\n }\n })\n this.#pipeline = pipeline\n }\n\n /** Feed one MoQ object (raw MMTP packet). */\n feedMoqObject(packet: Uint8Array): void {\n this.#pipeline?.feedMoqObject(packet)\n }\n\n /** ms to sleep before the next object read. 0 when not anchored / not ahead. */\n paceSleepMs(): number {\n return this.#pacer.computeSleepMs()\n }\n\n /** Pacer snapshot (for diagnostics / UI). */\n get pacerSnapshot() {\n return this.#pacer.snapshot\n }\n\n /** Reset pacer on source switch (MoQ \u2194 multicast). */\n resetPacer(): void {\n this.#pacer.reset()\n }\n\n /** Drop queued PCM and its timestamp epoch at an explicit source boundary. */\n resetPlayout(startUnstalled = false): void {\n this.#pacer.reset()\n // The explicit gate owns only the initial prefill. Source-boundary resets\n // use the worklet's one-frame resume threshold.\n this.#startupReleased = true\n const message: ResetMessage = {\n type: 'reset',\n generation: ++this.#workletGeneration,\n startUnstalled,\n }\n this.#worklet?.port.postMessage(message)\n }\n\n /** Node to connect to destination / gain. */\n get rootNode(): AudioNode {\n if (!this.#worklet) throw new Error('AudioRenderPipeline.ready() must resolve first')\n return this.#worklet\n }\n\n close(): void {\n if (this.#closed) return\n this.#closed = true\n try { this.#decoder?.close() } catch { /* already closed */ }\n try { this.#pipeline?.dispose() } catch { /* noop */ }\n try { this.#worklet?.disconnect() } catch { /* noop */ }\n this.#decoder = null\n this.#pipeline = null\n this.#worklet = null\n }\n\n // \u2500\u2500\u2500 Private \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n #onDecoded(sample: AudioData): void {\n if (this.#closed || !this.#worklet) { sample.close(); return }\n\n const timestamp = sample.timestamp\n const channelData: Float32Array[] = []\n for (let ch = 0; ch < sample.numberOfChannels; ch++) {\n const data = new Float32Array(sample.numberOfFrames)\n sample.copyTo(data, { format: 'f32-planar', planeIndex: ch })\n channelData.push(data)\n }\n sample.close()\n\n const msg: DataMessage = {\n type: 'data',\n data: channelData,\n timestamp,\n }\n this.#worklet.port.postMessage(msg, channelData.map((d) => d.buffer))\n }\n}\n\n// auDurationMsFromCodec lives in ../pacing/au-duration.ts (canonical, no\n// mmt-container dep). Import it from '@blockcast/mmt-render/pacing' directly\n// or via the top-level '@blockcast/mmt-render' export.\n", "/**\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 * - 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 computeSleepMs(): number {\n if (this.thresholdMs <= 0) return 0\n if (!this.#anchored) return 0\n if (this.#frameCount <= this.warmupFrames) return 0\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 * 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", "/**\n * Helper for loading the prebuilt AudioWorklet bundle.\n *\n * Two equivalent loading patterns supported:\n *\n * 1. Vite-style static URL (recommended for bundled apps):\n * import workletUrl from '@blockcast/mmt-render/audio/worklet.js?url'\n * await ctx.audioWorklet.addModule(workletUrl)\n * Vite resolves the `?url` suffix + the package's \"./audio/worklet.js\"\n * export to the prebuilt IIFE file.\n *\n * 2. Runtime import.meta.url resolution (no bundler):\n * import { workletModuleUrl } from '@blockcast/mmt-render/audio/worklet-url'\n * await ctx.audioWorklet.addModule(workletModuleUrl())\n *\n * Both resolve to dist/worklet/render-worklet.js.\n */\n\n/**\n * Returns a URL (or URL string) pointing to the prebuilt worklet bundle.\n * Resolves relative to this module's location via import.meta.url.\n */\nexport function workletModuleUrl(): string {\n // dist layout: dist/audio/worklet-url.js \u2192 dist/worklet/render-worklet.js\n const base = new URL('../worklet/render-worklet.js', import.meta.url)\n return base.href\n}\n\n/** Processor name registered in the worklet bundle. */\nexport const WORKLET_PROCESSOR_NAME = 'mmt-render'\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAmBA,SAAS,0BAAkD;;;ACnB3D;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,y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MAAM;AAAA,QACN,WAAW,KAAK;AAAA,MAClB,CAAC,CAAC;AAAA,IACJ,SAAS,KAAK;AACZ,+BAAK,cAAL,8BAAgB;AAAA,IAClB;AAAA,EACF,CAAC;AACD,qBAAK,WAAY;AACnB;AAAA;AAuDA,eAAU,SAAC,QAAyB;AAClC,MAAI,mBAAK,YAAW,CAAC,mBAAK,WAAU;AAAE,WAAO,MAAM;AAAG;AAAA,EAAO;AAE7D,QAAM,YAAY,OAAO;AACzB,QAAM,cAA8B,CAAC;AACrC,WAAS,KAAK,GAAG,KAAK,OAAO,kBAAkB,MAAM;AACnD,UAAM,OAAO,IAAI,aAAa,OAAO,cAAc;AACnD,WAAO,OAAO,MAAM,EAAE,QAAQ,cAAc,YAAY,GAAG,CAAC;AAC5D,gBAAY,KAAK,IAAI;AAAA,EACvB;AACA,SAAO,MAAM;AAEb,QAAM,MAAmB;AAAA,IACvB,MAAM;AAAA,IACN,MAAM;AAAA,IACN;AAAA,EACF;AACA,qBAAK,UAAS,KAAK,YAAY,KAAK,YAAY,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC;AACtE;",
6
+ "names": []
7
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Timestamp-anchored FIFO shared by MMT AudioWorklet consumers.
3
+ *
4
+ * PCM remains in decoder emission order. Media timestamps are exact anchors
5
+ * for playout reporting only; they never reposition samples or trigger a
6
+ * guessed discontinuity. The FIFO starts after its full catalog-derived
7
+ * latency is buffered and performs no sample skip/dup clock recovery.
8
+ */
9
+ export interface AudioRingBufferConfig {
10
+ channels: number;
11
+ rate: number;
12
+ latencyMs: number;
13
+ /** Exact PCM startup threshold. Overrides latencyMs when provided. */
14
+ startupFrames?: number;
15
+ /** PCM refill threshold after the first underrun. Defaults to startupFrames. */
16
+ resumeFrames?: number;
17
+ /** Exact PCM storage ceiling. Must cover the startup and resume thresholds. */
18
+ capacityFrames?: number;
19
+ startUnstalled?: boolean;
20
+ /** Deprecated compatibility input. Clock recovery is not performed. */
21
+ warmupReads?: number;
22
+ diag?: boolean;
23
+ }
24
+ export interface AudioRingBufferDiag {
25
+ reads: number;
26
+ avgFill: number;
27
+ capacity: number;
28
+ skips: number;
29
+ dups: number;
30
+ overflowSamples: number;
31
+ }
32
+ export declare class AudioRingBuffer {
33
+ #private;
34
+ readonly channels: number;
35
+ readonly rate: number;
36
+ constructor(config: AudioRingBufferConfig);
37
+ get stalled(): boolean;
38
+ get startupFrames(): number;
39
+ get capacity(): number;
40
+ get length(): number;
41
+ /** Timestamp of the next media sample after the PCM already emitted. */
42
+ get timestampUs(): number | undefined;
43
+ write(timestampUs: number, data: Float32Array[]): void;
44
+ read(output: Float32Array[]): number;
45
+ /** Clear queued PCM; optionally treat the next fill as post-start recovery. */
46
+ reset(startUnstalled?: boolean, resumeAfterReset?: boolean): void;
47
+ /**
48
+ * Change the startup latency while preserving the configured storage
49
+ * headroom above its buffering thresholds. Active playout keeps draining
50
+ * retained PCM; a stalled buffer waits for its startup or resume threshold.
51
+ */
52
+ resize(latencyMs: number): void;
53
+ getDiagAndReset(): AudioRingBufferDiag | null;
54
+ }
55
+ //# sourceMappingURL=audio-ring-buffer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audio-ring-buffer.d.ts","sourceRoot":"","sources":["../../src/audio/audio-ring-buffer.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,EAAE,MAAM,CAAA;IACZ,SAAS,EAAE,MAAM,CAAA;IACjB,sEAAsE;IACtE,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,gFAAgF;IAChF,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,+EAA+E;IAC/E,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,uEAAuE;IACvE,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,IAAI,CAAC,EAAE,O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