@camstack/addon-pipeline 1.2.136 → 1.2.138

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 (41) hide show
  1. package/dist/audio-analyzer/index.js +7 -7
  2. package/dist/audio-analyzer/index.mjs +4 -4
  3. package/dist/detection-pipeline/index.js +61 -23
  4. package/dist/detection-pipeline/index.mjs +53 -15
  5. package/dist/{dist-BzLiQ8Ue.js → dist-BuIP0499.js} +315 -25
  6. package/dist/{dist-C1dXLLQq.mjs → dist-CmEYRK7G.mjs} +304 -26
  7. package/dist/{event-loop-stall-monitor-DjV4Bow7.js → event-loop-stall-monitor-Bef2jXMX.js} +1 -1
  8. package/dist/{event-loop-stall-monitor-CU-xxX5c.mjs → event-loop-stall-monitor-JGTFb0Uv.mjs} +1 -1
  9. package/dist/{lazy-sharp-DxWmhTqk.js → lazy-sharp-DH2eVehm.js} +3 -3
  10. package/dist/motion-wasm/index.js +3 -3
  11. package/dist/motion-wasm/index.mjs +3 -3
  12. package/dist/node-ChdX9lv7.js +721 -0
  13. package/dist/node-J07GBWT3.mjs +690 -0
  14. package/dist/pipeline-runner/index.js +87 -18
  15. package/dist/pipeline-runner/index.mjs +87 -18
  16. package/dist/{process-memory-CZK3D3kM.js → process-memory-CJoZemF4.js} +2 -2
  17. package/dist/{process-memory-CaEwi5Cd.mjs → process-memory-DAKxUb9d.mjs} +2 -2
  18. package/dist/recorder/index.js +39 -7
  19. package/dist/recorder/index.mjs +36 -4
  20. package/dist/{segment-demux-js-BbpqygHL.js → segment-demux-js-BgXbXZnp.js} +1 -1
  21. package/dist/{segment-demux-js-njRO85gd.mjs → segment-demux-js-Ck9ly4bX.mjs} +1 -1
  22. package/dist/session-decode/decode-worker-child.js +115 -5
  23. package/dist/session-decode/decode-worker-child.mjs +115 -5
  24. package/dist/stream-broker/_stub.js +2 -2
  25. package/dist/stream-broker/{_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-CLtMmF1E.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-Cad8960O.mjs} +3 -3
  26. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-xdmO8wYp.mjs +26 -0
  27. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-BrTM_tsb.mjs +26 -0
  28. package/dist/stream-broker/demux-worker-child.js +1 -1
  29. package/dist/stream-broker/demux-worker-child.mjs +1 -1
  30. package/dist/stream-broker/{hostInit-CP7Xhd8J.mjs → hostInit-Gd3OcDIa.mjs} +3 -3
  31. package/dist/stream-broker/index.js +245 -535
  32. package/dist/stream-broker/index.mjs +242 -530
  33. package/dist/stream-broker/remoteEntry.js +1 -1
  34. package/dist/{worker-protocol-DvTZBvh2.js → worker-protocol-Bpz62eyB.js} +2 -1
  35. package/dist/{worker-protocol-DxsVx0G7.mjs → worker-protocol-wMS29PG9.mjs} +2 -1
  36. package/package.json +17 -3
  37. package/dist/addon-utils-CKf8kbwh.js +0 -625
  38. package/dist/addon-utils-CgBCF-mE.mjs +0 -583
  39. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-DqplWP1i.mjs +0 -26
  40. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-DKMXG57X.mjs +0 -26
  41. package/dist/{lazy-sharp-BtT5x-qP.mjs → lazy-sharp-DXsqwpph.mjs} +1 -1
@@ -0,0 +1,690 @@
1
+ import { Ct as errMsg, Et as buildFfmpegArgs, Ot as isSoftwareDecode, Tt as Fmp4BoxSplitter } from "./dist-CmEYRK7G.mjs";
2
+ import { randomUUID } from "node:crypto";
3
+ import "node:fs";
4
+ import "node:path";
5
+ import "node:child_process";
6
+ import { readFile } from "node:fs/promises";
7
+ /**
8
+ * The registry an addon claims its OWN child processes in — the spawn-site
9
+ * half of `load-contribution.cap.ts`.
10
+ *
11
+ * ## Where a claim is made, and where it is released
12
+ *
13
+ * At the spawn site, and nowhere else. It is the only place that knows both
14
+ * halves: the recorder's controller knows it is starting ffmpeg for camera 615
15
+ * profile `high`; the decode coordinator knows the session it is forking a
16
+ * worker for. Nothing has to deduce it afterwards, and no entity needs a
17
+ * global list of which pid belongs to which camera.
18
+ *
19
+ * {@link ChildCostRegistry.claim} returns a HANDLE, and the handle is the only
20
+ * way to release. That is not decoration: the alternative — `release(pid)` —
21
+ * lets a late release from a dead generation delete the live claim of a
22
+ * process that inherited the same pid, which is precisely how a per-camera
23
+ * chart charges one camera for another camera's work. A handle can only ever
24
+ * remove the entry it created.
25
+ *
26
+ * ## What the registry does NOT do
27
+ *
28
+ * It keeps no history, no counters and no timers. It holds live claims and
29
+ * answers questions about them; when the process holding it dies, every claim
30
+ * in it dies with it, which is correct — those children were its children.
31
+ *
32
+ * ## The numbers
33
+ *
34
+ * {@link ChildCostRegistry.contributions} reads each claimed child's
35
+ * CUMULATIVE CPU seconds and resident bytes out of `/proc/<pid>` at the moment
36
+ * it is asked. On demand, never on a timer: a new periodic per-node sampler is
37
+ * the defect half of `docs/architecture/load-ledger.md` documents. A counter
38
+ * can be differenced by whoever already keeps a history; a rate cannot be
39
+ * un-averaged.
40
+ *
41
+ * Where `/proc` does not exist (macOS, Windows) or the read fails, the numbers
42
+ * are ABSENT — never zero. Zero would say the camera cost nothing.
43
+ */
44
+ /**
45
+ * Kernel jiffies per second (`USER_HZ`). Same constant, same reasoning, as
46
+ * `packages/system/src/builtins/native-metrics/thread-cpu-sampler.ts`:
47
+ * `sysconf(_SC_CLK_TCK)` is not exposed to Node and this has been 100 on every
48
+ * kernel configuration we ship to. A wrong value would scale every CPU number
49
+ * by a constant — visible immediately, not a silent skew.
50
+ */
51
+ var CLOCK_TICKS_PER_SEC = 100;
52
+ /** Bytes per page, for `/proc/<pid>/statm`'s page counts. */
53
+ var PAGE_BYTES = 4096;
54
+ /**
55
+ * The handle a spawn site gets when nobody is collecting — a test harness, or
56
+ * a runner built before its addon registered a registry. Reporting nothing is
57
+ * the correct behaviour: the process still appears in the node's process
58
+ * snapshot, unclaimed, which is exactly what "nobody reported this" should
59
+ * look like.
60
+ */
61
+ var NO_COST_CLAIM = { release: () => void 0 };
62
+ var nodeProcStatReader = {
63
+ readStat: (pid) => readFile(`/proc/${pid}/stat`, "utf8"),
64
+ readStatm: (pid) => readFile(`/proc/${pid}/statm`, "utf8")
65
+ };
66
+ /**
67
+ * Cumulative CPU seconds from a `/proc/<pid>/stat` line.
68
+ *
69
+ * The `comm` field is field 2, wrapped in parentheses, and can itself contain
70
+ * spaces and parentheses — so the only correct parse cuts at the LAST `)` and
71
+ * indexes from there. After the cut, field 3 (`state`) is index 0, so `utime`
72
+ * (field 14) is index 11 and `stime` (field 15) is index 12.
73
+ *
74
+ * `null` for a line that does not parse: a process that exited between the
75
+ * claim and the read leaves a truncated or empty file, and that is normal.
76
+ */
77
+ function parseProcCpuSeconds(line) {
78
+ const close = line.lastIndexOf(")");
79
+ if (close < 0) return null;
80
+ const rest = line.slice(close + 1).trim().split(/\s+/);
81
+ const utime = Number(rest[11]);
82
+ const stime = Number(rest[12]);
83
+ if (!Number.isFinite(utime) || !Number.isFinite(stime)) return null;
84
+ return (utime + stime) / CLOCK_TICKS_PER_SEC;
85
+ }
86
+ /**
87
+ * Resident bytes from a `/proc/<pid>/statm` line — field 2 is the resident set
88
+ * in pages. `null` when the line does not parse.
89
+ */
90
+ function parseProcRssBytes(line) {
91
+ const fields = line.trim().split(/\s+/);
92
+ const residentPages = Number(fields[1]);
93
+ if (!Number.isFinite(residentPages)) return null;
94
+ return residentPages * PAGE_BYTES;
95
+ }
96
+ /**
97
+ * What the OS will say about one process right now: cumulative CPU seconds and
98
+ * resident bytes, each ABSENT when it cannot be read.
99
+ *
100
+ * Exported because not every cost has a spawn site inside a registry. The
101
+ * shared inference pool is the case that forced it: its process is created
102
+ * deep inside the engine factory and belongs to no camera, so it is reported
103
+ * as an `unattributable` contribution built from the live pool's pids rather
104
+ * than from a claim — but its numbers must be read the same way, by the same
105
+ * parsers, or two "CPU seconds" in one payload would mean two things.
106
+ */
107
+ async function readProcessCost(pid, reader = nodeProcStatReader) {
108
+ let cpuSeconds = null;
109
+ let rssBytes = null;
110
+ try {
111
+ cpuSeconds = parseProcCpuSeconds(await reader.readStat(pid));
112
+ } catch {
113
+ cpuSeconds = null;
114
+ }
115
+ try {
116
+ rssBytes = parseProcRssBytes(await reader.readStatm(pid));
117
+ } catch {
118
+ rssBytes = null;
119
+ }
120
+ return {
121
+ ...cpuSeconds === null ? {} : { cpuSeconds },
122
+ ...rssBytes === null ? {} : { rssBytes }
123
+ };
124
+ }
125
+ var ChildCostRegistry = class {
126
+ reader;
127
+ now;
128
+ claims = /* @__PURE__ */ new Map();
129
+ constructor(reader = nodeProcStatReader, now = Date.now) {
130
+ this.reader = reader;
131
+ this.now = now;
132
+ }
133
+ /**
134
+ * Record one child. The returned handle is the only way to remove it.
135
+ *
136
+ * A claim with no pid is dropped rather than stored: it could carry no
137
+ * measurement, and an entry with a camera and no numbers reads on a chart as
138
+ * a camera that cost nothing.
139
+ */
140
+ claim(input) {
141
+ const pid = input.pid;
142
+ if (pid === void 0 || !Number.isInteger(pid) || pid <= 0) return NO_COST_CLAIM;
143
+ const key = Symbol("child-cost-claim");
144
+ this.claims.set(key, {
145
+ role: input.role,
146
+ deviceId: input.deviceId,
147
+ unit: input.unit,
148
+ attribution: input.attribution ?? "measured",
149
+ pid,
150
+ startedAtMs: this.now()
151
+ });
152
+ return { release: () => {
153
+ this.claims.delete(key);
154
+ } };
155
+ }
156
+ /** Live claims, in claim order. Diagnostics and tests; not a contribution. */
157
+ list() {
158
+ return [...this.claims.values()].map((c) => ({
159
+ role: c.role,
160
+ deviceId: c.deviceId,
161
+ unit: c.unit,
162
+ attribution: c.attribution,
163
+ pid: c.pid
164
+ }));
165
+ }
166
+ /**
167
+ * This addon's contribution: one entry per live claim, with whatever the OS
168
+ * will tell us about that child right now.
169
+ *
170
+ * A child that has exited between the claim and this read contributes an
171
+ * entry with no numbers rather than no entry — the unit exists, the addon
172
+ * believes it is running, and hiding it would make a dying writer look like
173
+ * a writer that was never started.
174
+ */
175
+ async contributions() {
176
+ const out = [];
177
+ for (const claim of this.claims.values()) out.push({
178
+ role: claim.role,
179
+ deviceId: claim.deviceId,
180
+ attribution: claim.attribution,
181
+ unit: claim.unit,
182
+ pid: claim.pid,
183
+ startedAtMs: claim.startedAtMs,
184
+ ...await readProcessCost(claim.pid, this.reader)
185
+ });
186
+ return out;
187
+ }
188
+ };
189
+ /**
190
+ * Fmp4FragmentPlane — a SUBSCRIBABLE fragmented-MP4 plane, fed by one
191
+ * {@link import('./fmp4-box-splitter.js').Fmp4BoxSplitter}.
192
+ *
193
+ * ## Why a plane and not a callback
194
+ *
195
+ * The operator's requirement for HKSV was explicit: the live fMP4 source built
196
+ * for it must be **dual-use**, so a HomeKit-triggered recording also lands in
197
+ * CamStack as an additional videoclip source alongside the recorder and the NC
198
+ * clip ring — *one fragmenter, two consumers; do not build an HKSV-only pipe*
199
+ * (`docs/roadmap.md` item 4b). A single-callback pipe makes the second consumer
200
+ * a second ffmpeg child of the same camera. So this is the same shape the
201
+ * broker's other multi-consumer surfaces already have
202
+ * (`AudioChunkPlane`, the push packet plane): N independent subscriptions over
203
+ * one producer.
204
+ *
205
+ * **Nothing consumes it yet.** Phase 4 brings the HKSV delegate and phase 4b the
206
+ * clip source; both are named here so the seam is not re-invented, and neither
207
+ * is built.
208
+ *
209
+ * ## The init segment is RETAINED
210
+ *
211
+ * A subscriber that attaches mid-stream — the clip consumer joining an already
212
+ * running HKSV session, which is the whole dual-use case — receives the
213
+ * retained `ftyp`+`moov` as its first packet and then live fragments. Without
214
+ * retention its fragments are undecodable and the failure looks like a codec
215
+ * problem.
216
+ *
217
+ * ## A slow subscriber is CLOSED, never silently gapped
218
+ *
219
+ * `AudioChunkPlane` drops its oldest chunk on overflow, which for audio costs a
220
+ * click. An fMP4 stream with a hole is not a shorter clip, it is a corrupt one:
221
+ * `moof` sequence numbers jump, the consumer's demuxer desynchronises, and HKSV
222
+ * shows a clip that fails to play with nothing anywhere saying why. So a
223
+ * subscription whose queue overflows is ENDED with a reason, loudly, and the
224
+ * other subscriptions are untouched.
225
+ *
226
+ * ## The PREBUFFER (phase 3)
227
+ *
228
+ * HKSV asks for context BEFORE the trigger — `CameraRecordingOptions.prebufferLength`
229
+ * is a HAP-mandated minimum of 4000 ms — and a subscriber that attaches at the
230
+ * motion edge has none. So the plane optionally retains the last few fragments
231
+ * and replays them to a subscriber that asks for them.
232
+ *
233
+ * Three things this ring gets right, each of which is a measured fact rather
234
+ * than a preference (see [D84](../../../../docs/decisions/adr-0084.md)):
235
+ *
236
+ * - **It is bounded by TIME *and* BYTES.** On the live fleet a 720p copy
237
+ * fragment is ~255 KB and a 4K one is ~6.35 MB — a 25× spread over the same
238
+ * window. A time-only bound is a per-camera RAM figure nobody can predict.
239
+ * - **The window is measured on ARRIVAL, not parsed from `tfdt`.** The
240
+ * splitter deliberately never computes a fragment's duration (a second
241
+ * opinion about a fact the muxer owns), and a prebuffer cares about how long
242
+ * ago the bytes turned up, which is exactly what arrival time answers.
243
+ * - **A replay is not backlog.** A subscriber taking N retained fragments gets
244
+ * its queue capacity raised by N for them, because closing a subscriber as a
245
+ * slow consumer for the prebuffer it explicitly asked for would be the
246
+ * stupidest possible failure — and, with `DEFAULT_QUEUE_CAPACITY` of 4 and a
247
+ * ring of 4, the guaranteed one.
248
+ *
249
+ * ## `isLast`
250
+ *
251
+ * hap-nodejs requires the delegate to mark exactly one `RecordingPacket` with
252
+ * `isLast` — a generator that finishes without it produces the twelve-second
253
+ * timeout loop [D50](../../../../../docs/decisions/adr-0050.md) deleted. The
254
+ * plane therefore computes it at DELIVERY time: a packet is last when the plane
255
+ * has ended and nothing remains queued behind it. A subscription that ends
256
+ * having delivered NOTHING says so through {@link Fmp4Subscription.delivered};
257
+ * the future delegate must not open an HDS stream it cannot feed.
258
+ */
259
+ var DEFAULT_QUEUE_CAPACITY = 4;
260
+ var Fmp4FragmentPlane = class {
261
+ logger;
262
+ prebuffer;
263
+ now;
264
+ subscriptions = /* @__PURE__ */ new Map();
265
+ /** The last init unit seen, handed to every later subscriber. */
266
+ retainedInit = null;
267
+ ended = false;
268
+ /** Oldest first. Empty unless {@link Fmp4PrebufferOptions} was supplied. */
269
+ ring = [];
270
+ ringBytes = 0;
271
+ constructor(logger, prebuffer, now = Date.now) {
272
+ this.logger = logger;
273
+ this.prebuffer = prebuffer;
274
+ this.now = now;
275
+ }
276
+ get subscriberCount() {
277
+ return this.subscriptions.size;
278
+ }
279
+ /** True once {@link end} has been called — no further units are accepted. */
280
+ get isEnded() {
281
+ return this.ended;
282
+ }
283
+ /** What the prebuffer ring holds right now. All zeroes when disabled. */
284
+ prebufferStats() {
285
+ const oldest = this.ring[0];
286
+ return {
287
+ fragments: this.ring.length,
288
+ bytes: this.ringBytes,
289
+ spanMs: oldest === void 0 ? 0 : this.now() - oldest.arrivedAt
290
+ };
291
+ }
292
+ subscribe(input) {
293
+ const replay = input.withPrebuffer === true ? this.trimmedRing() : [];
294
+ const requested = Math.max(1, input.queueCapacity ?? DEFAULT_QUEUE_CAPACITY);
295
+ const sub = {
296
+ id: `fmp4-${randomUUID()}`,
297
+ tag: input.tag,
298
+ subscribedAt: this.now(),
299
+ capacity: requested + replay.length,
300
+ queue: [],
301
+ delivered: 0,
302
+ closedReason: null,
303
+ wake: null,
304
+ iterating: false
305
+ };
306
+ this.subscriptions.set(sub.id, sub);
307
+ if (this.retainedInit !== null) this.enqueue(sub, this.retainedInit);
308
+ for (const retained of replay) this.enqueue(sub, retained.unit);
309
+ if (this.ended) this.closeSubscription(sub, "ended");
310
+ this.logger?.info("fmp4 plane: subscribed", { meta: {
311
+ subscriptionId: sub.id,
312
+ tag: sub.tag,
313
+ hasRetainedInit: this.retainedInit !== null,
314
+ prebufferFragments: replay.length,
315
+ prebufferBytes: replay.reduce((n, r) => n + r.unit.data.length, 0)
316
+ } });
317
+ return this.facade(sub);
318
+ }
319
+ /**
320
+ * Fan one splitter unit out. An `init` REPLACES the retained one — ffmpeg
321
+ * emits exactly one per child, and a second means the child was respawned, in
322
+ * which case the old one describes a stream that no longer exists.
323
+ */
324
+ publish(unit) {
325
+ if (this.ended) return;
326
+ if (unit.kind === "init") {
327
+ this.retainedInit = unit;
328
+ this.ring.length = 0;
329
+ this.ringBytes = 0;
330
+ } else this.retain(unit);
331
+ for (const sub of this.subscriptions.values()) {
332
+ if (sub.closedReason !== null) continue;
333
+ this.enqueue(sub, unit);
334
+ }
335
+ }
336
+ /**
337
+ * The producer stopped. Every subscriber drains what it holds; its final
338
+ * packet carries `isLast`, and its generator then completes.
339
+ */
340
+ end(reason = "producer ended") {
341
+ if (this.ended) return;
342
+ this.ended = true;
343
+ this.logger?.info("fmp4 plane: ended", { meta: {
344
+ reason,
345
+ subscribers: this.subscriptions.size
346
+ } });
347
+ for (const sub of this.subscriptions.values()) if (sub.closedReason === null) this.closeSubscription(sub, "ended");
348
+ }
349
+ listSubscribers() {
350
+ return [...this.subscriptions.values()].map((s) => ({
351
+ tag: s.tag,
352
+ subscribedAt: s.subscribedAt,
353
+ delivered: s.delivered,
354
+ closedReason: s.closedReason
355
+ }));
356
+ }
357
+ /** End and forget everything. Idempotent. */
358
+ dispose() {
359
+ this.end("disposed");
360
+ this.subscriptions.clear();
361
+ this.retainedInit = null;
362
+ this.ring.length = 0;
363
+ this.ringBytes = 0;
364
+ }
365
+ /**
366
+ * Add one fragment to the ring and evict from the front until BOTH bounds
367
+ * hold. Eviction is oldest-first, which is the one place in this file where
368
+ * dropping is correct: the ring is context, not stream — nobody is mid-decode
369
+ * on it, and a subscriber only ever receives a contiguous tail of it.
370
+ */
371
+ retain(unit) {
372
+ const prebuffer = this.prebuffer;
373
+ if (prebuffer === void 0) return;
374
+ const arrivedAt = this.now();
375
+ this.ring.push({
376
+ unit,
377
+ arrivedAt
378
+ });
379
+ this.ringBytes += unit.data.length;
380
+ const cutoff = arrivedAt - prebuffer.windowMs;
381
+ while (this.ring.length > 0) {
382
+ const oldest = this.ring[0];
383
+ if (oldest === void 0) break;
384
+ const tooOld = oldest.arrivedAt < cutoff;
385
+ const tooBig = this.ringBytes > prebuffer.maxBytes;
386
+ if (!tooOld && !tooBig || this.ring.length === 1) break;
387
+ this.ring.shift();
388
+ this.ringBytes -= oldest.unit.data.length;
389
+ }
390
+ }
391
+ /**
392
+ * The ring as a subscriber should receive it — window applied AT SUBSCRIBE
393
+ * time, not only at publish time. A camera that went quiet keeps its last
394
+ * fragment in the ring indefinitely (see the never-evict-the-newest rule),
395
+ * and replaying a 40-second-old fragment as "prebuffer" would put stale video
396
+ * at the head of a clip iOS presents as the moment of the event.
397
+ */
398
+ trimmedRing() {
399
+ const prebuffer = this.prebuffer;
400
+ if (prebuffer === void 0) return [];
401
+ const cutoff = this.now() - prebuffer.windowMs;
402
+ return this.ring.filter((r) => r.arrivedAt >= cutoff);
403
+ }
404
+ enqueue(sub, unit) {
405
+ if (sub.queue.length >= sub.capacity) {
406
+ this.logger?.warn("fmp4 plane: subscriber fell behind — CLOSING it rather than gapping it", { meta: {
407
+ subscriptionId: sub.id,
408
+ tag: sub.tag,
409
+ capacity: sub.capacity,
410
+ delivered: sub.delivered
411
+ } });
412
+ this.closeSubscription(sub, "slow-consumer");
413
+ return;
414
+ }
415
+ sub.queue.push({
416
+ kind: unit.kind,
417
+ data: unit.data,
418
+ sequence: unit.sequence,
419
+ isLast: false
420
+ });
421
+ this.wake(sub);
422
+ }
423
+ closeSubscription(sub, reason) {
424
+ if (sub.closedReason !== null) return;
425
+ sub.closedReason = reason;
426
+ if (reason === "slow-consumer") sub.queue.length = 0;
427
+ this.wake(sub);
428
+ }
429
+ wake(sub) {
430
+ const resume = sub.wake;
431
+ sub.wake = null;
432
+ resume?.();
433
+ }
434
+ facade(sub) {
435
+ const plane = this;
436
+ return {
437
+ id: sub.id,
438
+ tag: sub.tag,
439
+ get delivered() {
440
+ return sub.delivered;
441
+ },
442
+ get closedReason() {
443
+ return sub.closedReason;
444
+ },
445
+ packets: () => plane.iterate(sub),
446
+ release: () => {
447
+ plane.closeSubscription(sub, "released");
448
+ plane.subscriptions.delete(sub.id);
449
+ }
450
+ };
451
+ }
452
+ async *iterate(sub) {
453
+ if (sub.iterating) throw new Error(`fmp4 plane: subscription ${sub.tag} is already being consumed — take a second subscription`);
454
+ sub.iterating = true;
455
+ for (;;) {
456
+ const next = sub.queue.shift();
457
+ if (next === void 0) {
458
+ if (sub.closedReason !== null) return;
459
+ await new Promise((resolve) => {
460
+ sub.wake = resolve;
461
+ });
462
+ continue;
463
+ }
464
+ const isLast = sub.closedReason === "ended" && sub.queue.length === 0;
465
+ sub.delivered += 1;
466
+ yield {
467
+ ...next,
468
+ isLast
469
+ };
470
+ if (isLast) return;
471
+ }
472
+ }
473
+ };
474
+ var DEFAULT_FIRST_UNIT_TIMEOUT_MS = 12e3;
475
+ /** Heartbeat cadence — ~2 minutes of 4 s fragments. */
476
+ var FRAGMENT_LOG_EVERY = 30;
477
+ var Fmp4FragmentChild = class {
478
+ deps;
479
+ args;
480
+ child = null;
481
+ splitter = new Fmp4BoxSplitter();
482
+ stopped = false;
483
+ unitsOut = 0;
484
+ activeHwAccel = null;
485
+ constructor(deps, args) {
486
+ this.deps = deps;
487
+ this.args = args;
488
+ }
489
+ /** Spawn, and resolve once the INIT segment has been cut out of stdout. */
490
+ async start() {
491
+ const requested = this.args.invocation.decodeHwAccel;
492
+ this.activeHwAccel = requested;
493
+ try {
494
+ await this.spawnAttempt(requested);
495
+ return;
496
+ } catch (err) {
497
+ if (this.stopped) throw err;
498
+ if (requested === null || isSoftwareDecode(requested)) throw err;
499
+ this.deps.logger.warn("fmp4 fragment child: hardware decode produced NO fragment — retrying in SOFTWARE", {
500
+ tags: { deviceId: this.args.deviceId },
501
+ meta: {
502
+ sourceId: this.args.sourceId,
503
+ decodeHwAccel: requested,
504
+ error: errMsg(err)
505
+ }
506
+ });
507
+ this.killChild();
508
+ this.splitter = new Fmp4BoxSplitter();
509
+ this.activeHwAccel = null;
510
+ await this.spawnAttempt(null);
511
+ }
512
+ }
513
+ /** The backend the child ACTUALLY ran with — `null` for software. */
514
+ activeDecodeHwAccel() {
515
+ const value = this.activeHwAccel;
516
+ return value === null || value === "none" || value === "copy" ? null : value;
517
+ }
518
+ /** Kill ffmpeg and end the plane. Idempotent. */
519
+ async stop() {
520
+ if (this.stopped) return;
521
+ this.stopped = true;
522
+ this.killChild();
523
+ this.args.plane.end("the fragment child stopped");
524
+ }
525
+ spawnAttempt(decodeHwAccel) {
526
+ const args = buildFfmpegArgs({
527
+ ...this.args.invocation,
528
+ decodeHwAccel,
529
+ sink: {
530
+ kind: "stdout",
531
+ container: "mp4",
532
+ fragmentMs: this.args.fragmentMs
533
+ }
534
+ });
535
+ this.deps.logger.info("fmp4 fragment child: spawning ffmpeg", {
536
+ tags: { deviceId: this.args.deviceId },
537
+ meta: {
538
+ sourceId: this.args.sourceId,
539
+ fragmentMs: this.args.fragmentMs,
540
+ decodeHwAccel: decodeHwAccel ?? "software",
541
+ argv: args.join(" ")
542
+ }
543
+ });
544
+ return new Promise((resolve, reject) => {
545
+ const child = this.deps.spawnFn(this.deps.ffmpegBinaryPath, args, { stdio: [
546
+ "ignore",
547
+ "pipe",
548
+ "pipe"
549
+ ] });
550
+ this.child = child;
551
+ let settled = false;
552
+ /**
553
+ * This attempt FAILED. Set before the kill, because SIGTERM makes the
554
+ * child exit and that exit must not be reported as a death: the retry —
555
+ * or the caller's rejection — already owns what happens next. Without it
556
+ * the timeout path ends the plane the software retry is about to fill,
557
+ * and the consumer sees a stream that stopped for no reason. A "which
558
+ * spawn is current" counter does NOT cover this: the retry has not been
559
+ * spawned when the kill's exit arrives.
560
+ */
561
+ let failed = false;
562
+ /**
563
+ * This attempt is still the live producer: it has not failed (a failure
564
+ * hands ownership to the retry, or to the caller's rejection) and nothing
565
+ * has stopped the child. Those two cover every way an attempt stops being
566
+ * current — `start` only respawns after a rejection.
567
+ */
568
+ const isCurrent = () => !this.stopped && !failed;
569
+ const timeoutMs = this.deps.firstUnitTimeoutMs ?? DEFAULT_FIRST_UNIT_TIMEOUT_MS;
570
+ const settle = (fail) => {
571
+ if (settled) return;
572
+ settled = true;
573
+ clearTimeout(timer);
574
+ if (fail) {
575
+ failed = true;
576
+ reject(fail);
577
+ } else resolve();
578
+ };
579
+ const timer = setTimeout(() => {
580
+ settle(/* @__PURE__ */ new Error(`fmp4 fragment child: no fragment within ${timeoutMs}ms`));
581
+ this.killChild();
582
+ }, timeoutMs);
583
+ timer.unref?.();
584
+ child.stdout?.on("data", (chunk) => {
585
+ for (const unit of this.splitter.push(chunk)) {
586
+ this.unitsOut += 1;
587
+ this.args.plane.publish(unit);
588
+ if (unit.kind === "init") {
589
+ this.deps.logger.info("fmp4 fragment child: INIT segment cut", {
590
+ tags: { deviceId: this.args.deviceId },
591
+ meta: {
592
+ sourceId: this.args.sourceId,
593
+ bytes: unit.data.length
594
+ }
595
+ });
596
+ settle();
597
+ } else if (this.unitsOut % FRAGMENT_LOG_EVERY === 0) this.deps.logger.info("fmp4 fragment child: fragments still flowing", {
598
+ tags: { deviceId: this.args.deviceId },
599
+ meta: {
600
+ sourceId: this.args.sourceId,
601
+ unitsOut: this.unitsOut,
602
+ bytes: unit.data.length,
603
+ subscribers: this.args.plane.subscriberCount
604
+ }
605
+ });
606
+ }
607
+ const fault = this.splitter.fault;
608
+ if (fault !== null) this.onFault(fault, settled, isCurrent(), settle);
609
+ });
610
+ child.stderr?.setEncoding("utf8");
611
+ child.stderr?.on("data", (line) => {
612
+ this.deps.logger.debug("fmp4 fragment child ffmpeg", {
613
+ tags: { deviceId: this.args.deviceId },
614
+ meta: {
615
+ sourceId: this.args.sourceId,
616
+ line: line.trim()
617
+ }
618
+ });
619
+ });
620
+ child.once("error", (err) => {
621
+ if (!settled) {
622
+ settle(err);
623
+ return;
624
+ }
625
+ if (!isCurrent()) return;
626
+ this.args.plane.end("the fragment child errored");
627
+ this.deps.onChildExit?.(err);
628
+ });
629
+ child.once("exit", (code, signal) => {
630
+ if (!settled) {
631
+ settle(/* @__PURE__ */ new Error(`fmp4 fragment child: ffmpeg exited before any fragment (code=${code} signal=${signal})`));
632
+ return;
633
+ }
634
+ if (!isCurrent()) return;
635
+ const error = /* @__PURE__ */ new Error(`fmp4 fragment child: ffmpeg exited while live (code=${code} signal=${signal})`);
636
+ this.deps.logger.warn("fmp4 fragment child: ffmpeg exited while live", {
637
+ tags: { deviceId: this.args.deviceId },
638
+ meta: {
639
+ sourceId: this.args.sourceId,
640
+ code,
641
+ signal,
642
+ unitsOut: this.unitsOut
643
+ }
644
+ });
645
+ this.args.plane.end("the fragment child exited");
646
+ this.deps.onChildExit?.(error);
647
+ });
648
+ });
649
+ }
650
+ /**
651
+ * The byte stream stopped being splittable. Not recoverable — the splitter
652
+ * cannot resynchronise mid-box — so the child is a corpse and every consumer
653
+ * has to be told, loudly, with the reason.
654
+ */
655
+ onFault(reason, wasLive, current, settle) {
656
+ const error = /* @__PURE__ */ new Error(`fmp4 fragment child: ${reason}`);
657
+ this.deps.logger.error("fmp4 fragment child: the ffmpeg output stopped parsing as fMP4", {
658
+ tags: { deviceId: this.args.deviceId },
659
+ meta: {
660
+ sourceId: this.args.sourceId,
661
+ unitsOut: this.unitsOut,
662
+ interstitial: this.splitter.discardedInterstitialTypes,
663
+ reason
664
+ }
665
+ });
666
+ this.killChild();
667
+ settle(error);
668
+ if (wasLive && current) {
669
+ this.args.plane.end("the fragment child produced unsplittable output");
670
+ this.deps.onChildExit?.(error);
671
+ }
672
+ }
673
+ killChild() {
674
+ const child = this.child;
675
+ this.child = null;
676
+ if (child && !child.killed) try {
677
+ child.kill("SIGTERM");
678
+ } catch (err) {
679
+ this.deps.logger.warn("fmp4 fragment child: kill error", {
680
+ tags: { deviceId: this.args.deviceId },
681
+ meta: {
682
+ sourceId: this.args.sourceId,
683
+ error: errMsg(err)
684
+ }
685
+ });
686
+ }
687
+ }
688
+ };
689
+ //#endregion
690
+ export { readProcessCost as a, NO_COST_CLAIM as i, Fmp4FragmentChild as n, Fmp4FragmentPlane as r, ChildCostRegistry as t };