@camstack/addon-decoder-ffmpeg 1.1.4 → 1.1.6

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 (3) hide show
  1. package/dist/index.js +1579 -45
  2. package/dist/index.mjs +1580 -46
  3. package/package.json +6 -2
package/dist/index.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { FrameRingReaderCache, FrameRingWriter, MIN_RING_SLOTS, computeSegmentSize, computeSlotByteLength, createSegment, deriveSlotCount } from "@camstack/shm-ring";
2
+ import { FrameRingReaderCache, FrameRingWriter, MIN_RING_SLOTS, computeSegmentSize, computeSlotByteLength, createSegment, deriveSlotCount, unlinkSegment } from "@camstack/shm-ring";
3
3
  import { spawn } from "node:child_process";
4
+ import { readdirSync } from "node:fs";
4
5
  //#region ../../node_modules/zod/v4/core/core.js
5
6
  var _a$1;
6
7
  function $constructor(name, initializer, params) {
@@ -4630,7 +4631,7 @@ function _instanceof(cls, params = {}) {
4630
4631
  return inst;
4631
4632
  }
4632
4633
  //#endregion
4633
- //#region ../types/dist/sleep-BiDFW0E7.mjs
4634
+ //#region ../types/dist/sleep-CZDdRBua.mjs
4634
4635
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
4635
4636
  EventCategory["SystemBoot"] = "system.boot";
4636
4637
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -7237,7 +7238,16 @@ var DecoderStatsSchema = object({
7237
7238
  inputFps: number(),
7238
7239
  outputFps: number(),
7239
7240
  avgDecodeTimeMs: number(),
7240
- droppedFrames: number()
7241
+ droppedFrames: number(),
7242
+ /**
7243
+ * Pull-mode adaptive-fps telemetry (optional — only pull sessions run the
7244
+ * lag-driven controller; push sessions omit these). `lagMs` is the EWMA of
7245
+ * the decoder's real-time drift (rising = falling behind live); `adaptiveFps`
7246
+ * is the current lag-throttled emit rate (≤ `effectiveFps` ceiling).
7247
+ */
7248
+ lagMs: number().optional(),
7249
+ effectiveFps: number().optional(),
7250
+ adaptiveFps: number().optional()
7241
7251
  });
7242
7252
  var DecoderSessionConfigSchema = object({
7243
7253
  codec: string(),
@@ -7278,7 +7288,15 @@ var DecoderSessionConfigSchema = object({
7278
7288
  * other — `pullFrames` returns nothing for an `'shm'` session and
7279
7289
  * `pullHandles` returns nothing for a `'callback'` session.
7280
7290
  */
7281
- frameSink: _enum(["callback", "shm"]).default("callback")
7291
+ frameSink: _enum(["callback", "shm"]).default("callback"),
7292
+ /**
7293
+ * Per-camera decoder DEBUG facility. When `true`, a pull-mode session emits
7294
+ * a throttled (~1Hz) structured `decoder debug` line (effective/adaptive fps,
7295
+ * real-time lag, dropped-frame delta, avg decode time, hwaccel). Mirrors the
7296
+ * stream-broker's `streamingDebug` gate — off by default so production logs
7297
+ * stay quiet and the emit path pays zero per-frame cost when disabled.
7298
+ */
7299
+ debug: boolean().optional()
7282
7300
  });
7283
7301
  var EncodeProfileSchema = object({
7284
7302
  video: object({
@@ -9436,6 +9454,75 @@ DeviceType.Cover, method(object({ deviceId: number().int().nonnegative() }), _vo
9436
9454
  auth: "admin"
9437
9455
  });
9438
9456
  /**
9457
+ * Vendor-neutral day/night (IR-cut) control — the per-camera config cap
9458
+ * shared by reolink / hikvision / amcrest. Models the common firmware
9459
+ * surface: the IR-cut switching MODE plus the two knobs that gate it
9460
+ * (photocell `sensitivity` + `switchDelaySec`). Each vendor maps these
9461
+ * onto its own ISAPI / Baichuan / Dahua-CGI fields; the cap standardises
9462
+ * the shape so ONE derived-form renders every camera.
9463
+ *
9464
+ * Follows the D14 `deviceConfig` archetype (see `stream-params.cap.ts`):
9465
+ * `getOptions` advertises per-camera availability, `getStatus` (auto-
9466
+ * injected from `status`) reports the live values, and a single
9467
+ * `setSettings` mutation applies a partial change. No hand-written
9468
+ * settings-contribution methods — the framework derives the UI + save
9469
+ * routing from this surface.
9470
+ */
9471
+ /** IR-cut switching mode. `schedule` = time-of-day table configured on the camera. */
9472
+ var DayNightModeSchema = _enum([
9473
+ "auto",
9474
+ "day",
9475
+ "night",
9476
+ "schedule"
9477
+ ]);
9478
+ /** Normalized numeric range descriptor — `{ min, max, step }` per the
9479
+ * getOptions availability convention. Normalized values are 0–100. */
9480
+ var NormalizedRangeSchema$1 = object({
9481
+ min: number(),
9482
+ max: number(),
9483
+ step: number()
9484
+ });
9485
+ object({
9486
+ mode: DayNightModeSchema,
9487
+ /** IR-cut trigger sensitivity, NORMALIZED 0–100 (higher = switches to night sooner). */
9488
+ sensitivity: number().optional(),
9489
+ /** Delay before the IR-cut filter flips, in seconds. */
9490
+ switchDelaySec: number().optional(),
9491
+ lastFetchedAt: number()
9492
+ });
9493
+ /**
9494
+ * Per-camera availability descriptor — drives which controls the admin UI
9495
+ * renders. Booleans as `supportsX`; numeric ranges as `{ min, max, step }`
9496
+ * (normalized 0–100); the mode choice-set as an array. A provider returns
9497
+ * honest, camera-probed values — never hardcoded.
9498
+ */
9499
+ var DayNightOptionsSchema = object({
9500
+ /** Modes this camera accepts. Empty → the camera has no configurable day/night mode. */
9501
+ modes: array(DayNightModeSchema),
9502
+ supportsSensitivity: boolean(),
9503
+ /** Present when `supportsSensitivity` — the normalized 0–100 range. */
9504
+ sensitivity: NormalizedRangeSchema$1.optional(),
9505
+ supportsSwitchDelay: boolean(),
9506
+ /** Present when `supportsSwitchDelay` — the allowed delay range in seconds. */
9507
+ switchDelaySec: NormalizedRangeSchema$1.optional()
9508
+ });
9509
+ /**
9510
+ * Partial change to the day/night config — every field optional. A
9511
+ * provider ignores fields it does not support.
9512
+ */
9513
+ var DayNightSettingsPatchSchema = object({
9514
+ mode: DayNightModeSchema.optional(),
9515
+ sensitivity: number().optional(),
9516
+ switchDelaySec: number().optional()
9517
+ });
9518
+ DeviceType.Camera, method(object({ deviceId: number() }), DayNightOptionsSchema), method(object({
9519
+ deviceId: number(),
9520
+ settings: DayNightSettingsPatchSchema
9521
+ }), _void(), {
9522
+ kind: "mutation",
9523
+ auth: "admin"
9524
+ });
9525
+ /**
9439
9526
  * Identity envelope for a device's upstream-system metadata.
9440
9527
  *
9441
9528
  * Two jobs:
@@ -9791,6 +9878,130 @@ object({
9791
9878
  });
9792
9879
  DeviceType.Image;
9793
9880
  /**
9881
+ * Vendor-neutral image / picture-adjustment cap — the per-camera config
9882
+ * cap shared by reolink / hikvision / amcrest. Models the common ISP
9883
+ * surface: the four picture sliders (brightness / contrast / saturation /
9884
+ * sharpness), orientation (mirror / flip / rotate), white-balance,
9885
+ * exposure and backlight-compensation modes.
9886
+ *
9887
+ * NORMALIZATION: every slider is a normalized int 0–100. Vendors expose
9888
+ * these natively as 0–100 or 0–255 (or other ranges); each provider maps
9889
+ * its native range to/from this normalized 0–100 space so the cap surface
9890
+ * (and the derived form) is identical across cameras. `warmth` (manual
9891
+ * white-balance) is likewise normalized 0–100.
9892
+ *
9893
+ * Follows the D14 `deviceConfig` archetype (see `stream-params.cap.ts`):
9894
+ * `getOptions` advertises per-camera availability, `getStatus` (auto-
9895
+ * injected from `status`) reports the live values, and a single
9896
+ * `setSettings` mutation applies a partial change. No hand-written
9897
+ * settings-contribution methods — the framework derives the UI + save
9898
+ * routing from this surface.
9899
+ */
9900
+ /** Sensor/image rotation, degrees clockwise. */
9901
+ var ImageRotateSchema = _enum([
9902
+ "0",
9903
+ "90",
9904
+ "180",
9905
+ "270"
9906
+ ]);
9907
+ /** White-balance mode. `manual` unlocks the normalized `warmth` knob. */
9908
+ var WhiteBalanceModeSchema = _enum(["auto", "manual"]);
9909
+ /** Exposure mode. */
9910
+ var ExposureModeSchema = _enum(["auto", "manual"]);
9911
+ /**
9912
+ * Backlight-compensation mode:
9913
+ * - `off` — disabled
9914
+ * - `blc` — backlight compensation
9915
+ * - `wdr` — wide dynamic range
9916
+ * - `hlc` — highlight compensation
9917
+ */
9918
+ var BacklightModeSchema = _enum([
9919
+ "off",
9920
+ "blc",
9921
+ "wdr",
9922
+ "hlc"
9923
+ ]);
9924
+ /** Normalized numeric range descriptor — `{ min, max, step }` per the
9925
+ * getOptions availability convention. Slider values are normalized 0–100. */
9926
+ var NormalizedRangeSchema = object({
9927
+ min: number(),
9928
+ max: number(),
9929
+ step: number()
9930
+ });
9931
+ object({
9932
+ /** Normalized 0–100. */
9933
+ brightness: number().optional(),
9934
+ /** Normalized 0–100. */
9935
+ contrast: number().optional(),
9936
+ /** Normalized 0–100. */
9937
+ saturation: number().optional(),
9938
+ /** Normalized 0–100. */
9939
+ sharpness: number().optional(),
9940
+ mirror: boolean().optional(),
9941
+ flip: boolean().optional(),
9942
+ rotate: ImageRotateSchema.optional(),
9943
+ whiteBalance: WhiteBalanceModeSchema.optional(),
9944
+ /** Manual white-balance warmth, NORMALIZED 0–100. Meaningful only when `whiteBalance === 'manual'`. */
9945
+ warmth: number().optional(),
9946
+ exposureMode: ExposureModeSchema.optional(),
9947
+ backlightMode: BacklightModeSchema.optional(),
9948
+ lastFetchedAt: number()
9949
+ });
9950
+ /**
9951
+ * Per-camera availability descriptor — drives which controls the admin UI
9952
+ * renders. Booleans as `supportsX`; numeric ranges as `{ min, max, step }`
9953
+ * (the normalized 0–100 range); enums as arrays of supported values (empty
9954
+ * array → control hidden). A provider returns honest, camera-probed values
9955
+ * — never hardcoded.
9956
+ */
9957
+ var ImageSettingsOptionsSchema = object({
9958
+ supportsBrightness: boolean(),
9959
+ brightness: NormalizedRangeSchema.optional(),
9960
+ supportsContrast: boolean(),
9961
+ contrast: NormalizedRangeSchema.optional(),
9962
+ supportsSaturation: boolean(),
9963
+ saturation: NormalizedRangeSchema.optional(),
9964
+ supportsSharpness: boolean(),
9965
+ sharpness: NormalizedRangeSchema.optional(),
9966
+ supportsMirror: boolean(),
9967
+ supportsFlip: boolean(),
9968
+ /** Supported rotation values. Empty → rotation not configurable. */
9969
+ rotateOptions: array(ImageRotateSchema),
9970
+ /** Supported white-balance modes. Empty → white-balance not configurable. */
9971
+ whiteBalanceModes: array(WhiteBalanceModeSchema),
9972
+ supportsWarmth: boolean(),
9973
+ /** Present when `supportsWarmth` — the normalized 0–100 range. */
9974
+ warmth: NormalizedRangeSchema.optional(),
9975
+ /** Supported exposure modes. Empty → exposure not configurable. */
9976
+ exposureModes: array(ExposureModeSchema),
9977
+ /** Supported backlight modes. Empty → backlight-compensation not configurable. */
9978
+ backlightModes: array(BacklightModeSchema)
9979
+ });
9980
+ /**
9981
+ * Partial change to the image config — every field optional. Slider values
9982
+ * are normalized 0–100. A provider ignores fields it does not support.
9983
+ */
9984
+ var ImageSettingsPatchSchema = object({
9985
+ brightness: number().optional(),
9986
+ contrast: number().optional(),
9987
+ saturation: number().optional(),
9988
+ sharpness: number().optional(),
9989
+ mirror: boolean().optional(),
9990
+ flip: boolean().optional(),
9991
+ rotate: ImageRotateSchema.optional(),
9992
+ whiteBalance: WhiteBalanceModeSchema.optional(),
9993
+ warmth: number().optional(),
9994
+ exposureMode: ExposureModeSchema.optional(),
9995
+ backlightMode: BacklightModeSchema.optional()
9996
+ });
9997
+ DeviceType.Camera, method(object({ deviceId: number() }), ImageSettingsOptionsSchema), method(object({
9998
+ deviceId: number(),
9999
+ settings: ImageSettingsPatchSchema
10000
+ }), _void(), {
10001
+ kind: "mutation",
10002
+ auth: "admin"
10003
+ });
10004
+ /**
9794
10005
  * Robotic lawn-mower cap. Models HA `lawn_mower.*` entities — anything
9795
10006
  * with a mowing lifecycle plus a dock action.
9796
10007
  *
@@ -10685,6 +10896,16 @@ var RunnerCameraConfigSchema = object({
10685
10896
  * this gate is bypassed.
10686
10897
  */
10687
10898
  onboardMotionDrivesAnalyzer: boolean().default(true),
10899
+ /**
10900
+ * Master toggle for the occupancy re-check. When `false` (DEFAULT) the runner
10901
+ * never arms the periodic recheck timer, regardless of `occupancyRecheckSec` —
10902
+ * this is off by default because the recheck re-subscribes a detection session
10903
+ * every N seconds while `watching`, a major source of pull-decoder re-dial
10904
+ * churn (each cycle creates+tears a session → RTSP re-dial → latency). The
10905
+ * `occupancyRecheckSec` / `occupancyRecheckFrames` sliders only take effect
10906
+ * (and only render) when this is enabled.
10907
+ */
10908
+ occupancyRecheckEnabled: boolean().default(false),
10688
10909
  occupancyRecheckSec: number().min(occupancyRecheckSecField.min).max(occupancyRecheckSecField.max).default(occupancyRecheckSecField.default),
10689
10910
  occupancyRecheckFrames: number().min(occupancyRecheckFramesField.min).max(occupancyRecheckFramesField.max).default(occupancyRecheckFramesField.default),
10690
10911
  /**
@@ -12530,42 +12751,79 @@ var SessionInventoryEntrySchema = object({
12530
12751
  framesIn: number(),
12531
12752
  framesOut: number()
12532
12753
  });
12533
- method(_void(), array(AudioCodecInfoSchema).readonly()), method(object({
12534
- codec: string(),
12535
- kind: _enum(["decode", "encode"])
12536
- }), boolean()), method(AudioDecodeSessionConfigSchema, object({
12537
- sessionId: string(),
12538
- nodeId: string()
12539
- }), { kind: "mutation" }), method(AudioEncodeSessionConfigSchema, object({
12540
- sessionId: string(),
12541
- nodeId: string()
12542
- }), { kind: "mutation" }), method(object({
12543
- sessionId: string(),
12544
- nodeId: string().optional()
12545
- }), _void(), { kind: "mutation" }), method(object({
12546
- sessionId: string(),
12547
- nodeId: string().optional(),
12548
- data: _instanceof(Uint8Array),
12549
- /** Source PTS in milliseconds. Synthesised when omitted. */
12550
- pts: number().optional()
12551
- }), _void(), { kind: "mutation" }), method(object({
12552
- sessionId: string(),
12553
- nodeId: string().optional(),
12554
- maxCount: number().int().positive().default(8)
12555
- }), array(AudioPcmChunkSchema)), method(object({
12556
- sessionId: string(),
12557
- nodeId: string().optional(),
12558
- data: _instanceof(Uint8Array),
12559
- /** Source PTS in milliseconds. */
12560
- pts: number().optional()
12561
- }), _void(), { kind: "mutation" }), method(object({
12562
- sessionId: string(),
12563
- nodeId: string().optional(),
12564
- maxCount: number().int().positive().default(8)
12565
- }), array(AudioEncodedChunkSchema)), method(object({
12566
- sessionId: string(),
12567
- nodeId: string().optional()
12568
- }), array(AudioEncodedChunkSchema), { kind: "mutation" }), method(_void(), array(SessionInventoryEntrySchema).readonly());
12754
+ /**
12755
+ * audio-codec — bidirectional PCM ↔ encoded audio I/O box.
12756
+ *
12757
+ * Independent per-consumer sessions. The provider runs decode + resample
12758
+ * (or resample + encode) inside the session so a 16kHz mono ASA
12759
+ * subscriber and a 48kHz stereo WebRTC subscriber on the same source
12760
+ * stream don't share resamplers.
12761
+ *
12762
+ * Singleton on each node. Decoder and encoder live in the same provider
12763
+ * because they share the underlying libav contexts (node-av today,
12764
+ * pluggable later) — operators always install one or the other together.
12765
+ */
12766
+ var audioCodecCapability = {
12767
+ name: "audio-codec",
12768
+ scope: "system",
12769
+ mode: "singleton",
12770
+ preferredProvider: "decoder-nodeav",
12771
+ methods: {
12772
+ /** Probe the local runtime and return the supported codec matrix. */
12773
+ listSupportedCodecs: method(_void(), array(AudioCodecInfoSchema).readonly()),
12774
+ /** Cheap predicate — does the runtime support `(codec, kind)`? */
12775
+ canHandle: method(object({
12776
+ codec: string(),
12777
+ kind: _enum(["decode", "encode"])
12778
+ }), boolean()),
12779
+ createDecodeSession: method(AudioDecodeSessionConfigSchema, object({
12780
+ sessionId: string(),
12781
+ nodeId: string()
12782
+ }), { kind: "mutation" }),
12783
+ createEncodeSession: method(AudioEncodeSessionConfigSchema, object({
12784
+ sessionId: string(),
12785
+ nodeId: string()
12786
+ }), { kind: "mutation" }),
12787
+ closeSession: method(object({
12788
+ sessionId: string(),
12789
+ nodeId: string().optional()
12790
+ }), _void(), { kind: "mutation" }),
12791
+ /** Push one encoded audio frame into a decode session. */
12792
+ pushEncodedFrame: method(object({
12793
+ sessionId: string(),
12794
+ nodeId: string().optional(),
12795
+ data: _instanceof(Uint8Array),
12796
+ /** Source PTS in milliseconds. Synthesised when omitted. */
12797
+ pts: number().optional()
12798
+ }), _void(), { kind: "mutation" }),
12799
+ /** Pull up to `maxCount` PCM chunks from a decode session. */
12800
+ pullPcm: method(object({
12801
+ sessionId: string(),
12802
+ nodeId: string().optional(),
12803
+ maxCount: number().int().positive().default(8)
12804
+ }), array(AudioPcmChunkSchema)),
12805
+ /** Push one PCM chunk into an encode session. */
12806
+ pushPcm: method(object({
12807
+ sessionId: string(),
12808
+ nodeId: string().optional(),
12809
+ data: _instanceof(Uint8Array),
12810
+ /** Source PTS in milliseconds. */
12811
+ pts: number().optional()
12812
+ }), _void(), { kind: "mutation" }),
12813
+ /** Pull up to `maxCount` encoded chunks from an encode session. */
12814
+ pullEncoded: method(object({
12815
+ sessionId: string(),
12816
+ nodeId: string().optional(),
12817
+ maxCount: number().int().positive().default(8)
12818
+ }), array(AudioEncodedChunkSchema)),
12819
+ /** Flush any pending encoded output (call before close on graceful tear). */
12820
+ flushEncode: method(object({
12821
+ sessionId: string(),
12822
+ nodeId: string().optional()
12823
+ }), array(AudioEncodedChunkSchema), { kind: "mutation" }),
12824
+ listActiveSessions: method(_void(), array(SessionInventoryEntrySchema).readonly())
12825
+ }
12826
+ };
12569
12827
  var AuthResultSchema = object({
12570
12828
  userId: string(),
12571
12829
  username: string(),
@@ -19068,6 +19326,18 @@ Object.freeze({
19068
19326
  addonId: null,
19069
19327
  access: "view"
19070
19328
  },
19329
+ "dayNight.getOptions": {
19330
+ capName: "day-night",
19331
+ capScope: "device",
19332
+ addonId: null,
19333
+ access: "view"
19334
+ },
19335
+ "dayNight.setSettings": {
19336
+ capName: "day-night",
19337
+ capScope: "device",
19338
+ addonId: null,
19339
+ access: "create"
19340
+ },
19071
19341
  "decoder.createSession": {
19072
19342
  capName: "decoder",
19073
19343
  capScope: "system",
@@ -19998,6 +20268,18 @@ Object.freeze({
19998
20268
  addonId: null,
19999
20269
  access: "create"
20000
20270
  },
20271
+ "imageSettings.getOptions": {
20272
+ capName: "image-settings",
20273
+ capScope: "device",
20274
+ addonId: null,
20275
+ access: "view"
20276
+ },
20277
+ "imageSettings.setSettings": {
20278
+ capName: "image-settings",
20279
+ capScope: "device",
20280
+ addonId: null,
20281
+ access: "create"
20282
+ },
20001
20283
  "integrations.create": {
20002
20284
  capName: "integrations",
20003
20285
  capScope: "system",
@@ -23288,10 +23570,16 @@ var RING_BUDGET_BYTES = RING_BUDGET_MB * 1024 * 1024;
23288
23570
  * segment (resolution change) a distinct name so a stale consumer mapping is
23289
23571
  * never silently reused.
23290
23572
  */
23573
+ /**
23574
+ * Shared prefix for every decoder shm segment name. Startup orphan reclamation
23575
+ * (`purgeOrphanSegments`) keys off this to find segments left behind by a
23576
+ * crashed prior instance.
23577
+ */
23578
+ var SEGMENT_NAME_PREFIX = "csf.";
23291
23579
  function makeSegmentName(seed, generation) {
23292
23580
  let hash = 5381;
23293
23581
  for (let i = 0; i < seed.length; i += 1) hash = (hash << 5) + hash + seed.charCodeAt(i) | 0;
23294
- return `csf.${(hash >>> 0).toString(36)}.${generation}`;
23582
+ return `${SEGMENT_NAME_PREFIX}${(hash >>> 0).toString(36)}.${generation}`;
23295
23583
  }
23296
23584
  /**
23297
23585
  * The decoder-side owner of one stream's shared-memory frame ring.
@@ -24134,6 +24422,1225 @@ function probeGpuScaleFilters(ffmpegPath, logger) {
24134
24422
  });
24135
24423
  }
24136
24424
  //#endregion
24425
+ //#region src/shm-orphan-purge.ts
24426
+ /**
24427
+ * Startup reclamation of orphaned shared-memory segments.
24428
+ *
24429
+ * A decoder writes frames into named `/dev/shm` segments and unlinks each one
24430
+ * on graceful session teardown (`DecoderFrameRingSink.destroy`). When the
24431
+ * decoder process dies *ungracefully* — SIGBUS, OOM-kill, or a SIGKILL during
24432
+ * redeploy — that teardown never runs and the segment is orphaned: it stays in
24433
+ * the tmpfs forever, since nothing else knows its name. Across many
24434
+ * crashes/redeploys these accumulate until `/dev/shm` fills, at which point the
24435
+ * next `mmap` write faults with an uncatchable SIGBUS and the decoder
24436
+ * crash-loops into its circuit breaker (which is exactly the incident this
24437
+ * guards against).
24438
+ *
24439
+ * The reclamation is safe *at process startup*: a freshly-booting decoder owns
24440
+ * no live sessions, so every pre-existing segment with its prefix is by
24441
+ * definition an orphan from a dead instance. `shm_unlink` only removes the
24442
+ * name — any consumer still holding a mapping keeps reading valid memory until
24443
+ * it closes (POSIX deferred reclaim + the ring seqlock), so unlinking is safe
24444
+ * even if a stale reader is momentarily still attached.
24445
+ *
24446
+ * POSIX-only: segments surface as files under `/dev/shm` on Linux. On platforms
24447
+ * without that directory (Windows, macOS) the scan finds nothing — no-op.
24448
+ *
24449
+ * NOTE: this lives inside the decoder addon (not `@camstack/shm-ring`) so it
24450
+ * ships in the self-contained addon bundle via `camstack deploy`, reusing the
24451
+ * already-deployed `unlinkSegment`; no host base-image rebuild required.
24452
+ */
24453
+ /** Default tmpfs directory where POSIX shared-memory segments appear on Linux. */
24454
+ var DEFAULT_SHM_DIR = "/dev/shm";
24455
+ /**
24456
+ * Unlink every shared-memory segment whose name starts with `prefix`.
24457
+ *
24458
+ * Intended to run ONCE at decoder startup, before any session is created, to
24459
+ * reclaim segments orphaned by a previously-crashed instance. A per-file unlink
24460
+ * failure is swallowed so one stuck segment cannot block reclaiming the rest.
24461
+ */
24462
+ function purgeOrphanSegments(prefix, options = {}) {
24463
+ const dir = options.dir ?? DEFAULT_SHM_DIR;
24464
+ const unlink = options.unlink ?? unlinkSegment;
24465
+ let entries;
24466
+ try {
24467
+ entries = readdirSync(dir);
24468
+ } catch {
24469
+ return {
24470
+ scanned: 0,
24471
+ removed: 0,
24472
+ names: []
24473
+ };
24474
+ }
24475
+ const names = [];
24476
+ for (const name of entries) {
24477
+ if (!name.startsWith(prefix)) continue;
24478
+ try {
24479
+ unlink(name);
24480
+ names.push(name);
24481
+ } catch {}
24482
+ }
24483
+ return {
24484
+ scanned: entries.length,
24485
+ removed: names.length,
24486
+ names
24487
+ };
24488
+ }
24489
+ //#endregion
24490
+ //#region src/audio-codec/ffmpeg-audio-process.ts
24491
+ /**
24492
+ * Minimal ffmpeg subprocess wrapper shared by the audio decode + encode
24493
+ * sessions of `audio-codec-ffmpeg`.
24494
+ *
24495
+ * Owns exactly the process concerns both directions need: spawn, stdin write
24496
+ * with tolerated backpressure, stdout chunk delivery, and the kill sequence.
24497
+ *
24498
+ * The kill logic copies the CORRECTED pattern from `decoder-ffmpeg`'s
24499
+ * `killFfmpeg`: SIGTERM, then SIGKILL after a grace — gated on
24500
+ * `exitCode === null && signalCode === null`, NOT on `child.killed` (which Node
24501
+ * sets true after ANY `kill()`, so `!child.killed` never fires and the SIGKILL
24502
+ * would leak the process).
24503
+ */
24504
+ /** Grace period between SIGTERM and the escalated SIGKILL. */
24505
+ var KILL_GRACE_MS = 500;
24506
+ var FfmpegAudioProcess = class {
24507
+ child = null;
24508
+ logger;
24509
+ opts;
24510
+ killed = false;
24511
+ constructor(opts) {
24512
+ this.opts = opts;
24513
+ this.logger = opts.logger;
24514
+ this.spawn();
24515
+ }
24516
+ spawn() {
24517
+ let child;
24518
+ try {
24519
+ child = spawn(this.opts.ffmpegPath, [...this.opts.args]);
24520
+ } catch (err) {
24521
+ this.logger.error("audio-codec-ffmpeg: spawn threw", { meta: { error: errMsg(err) } });
24522
+ return;
24523
+ }
24524
+ this.child = child;
24525
+ child.stdin?.on("error", () => {});
24526
+ child.stdout?.on("data", (chunk) => this.opts.onStdout(chunk));
24527
+ child.stderr?.on("data", (data) => {
24528
+ const line = data.toString().trim();
24529
+ if (line) this.logger.debug("audio-codec-ffmpeg stderr", { meta: { line } });
24530
+ });
24531
+ child.on("error", (err) => {
24532
+ this.logger.error("audio-codec-ffmpeg: process error", { meta: { error: err.message } });
24533
+ });
24534
+ child.on("exit", (code, signal) => {
24535
+ if (this.killed) return;
24536
+ this.opts.onExit(code, signal);
24537
+ });
24538
+ }
24539
+ /** Write encoded frames / PCM into ffmpeg stdin. Backpressure is tolerated. */
24540
+ write(data) {
24541
+ const stdin = this.child?.stdin;
24542
+ if (!stdin) return;
24543
+ try {
24544
+ stdin.write(Buffer.from(data.buffer, data.byteOffset, data.byteLength));
24545
+ } catch {}
24546
+ }
24547
+ /** Close stdin so ffmpeg flushes and drains its remaining output. */
24548
+ endStdin() {
24549
+ try {
24550
+ this.child?.stdin?.end();
24551
+ } catch {}
24552
+ }
24553
+ /** SIGTERM then escalated SIGKILL — see class doc for the gating rationale. */
24554
+ kill() {
24555
+ const child = this.child;
24556
+ if (!child) return;
24557
+ this.killed = true;
24558
+ this.child = null;
24559
+ try {
24560
+ child.stdin?.end();
24561
+ } catch {}
24562
+ try {
24563
+ child.kill("SIGTERM");
24564
+ } catch {}
24565
+ const { pid } = child;
24566
+ setTimeout(() => {
24567
+ if (pid !== void 0 && child.exitCode === null && child.signalCode === null) try {
24568
+ child.kill("SIGKILL");
24569
+ } catch {}
24570
+ }, KILL_GRACE_MS).unref?.();
24571
+ }
24572
+ };
24573
+ //#endregion
24574
+ //#region src/audio-codec/audio-codec-args.ts
24575
+ /**
24576
+ * Low-latency flag set shared by both the decode and encode invocations.
24577
+ *
24578
+ * - `-hide_banner -nostats -loglevel error`: quiet stderr (no periodic counter).
24579
+ * - `-fflags +nobuffer+flush_packets`: don't buffer input; flush output packets
24580
+ * the moment they are ready (critical for the intercom encode path).
24581
+ * - `-flags low_delay`: request the lowest-latency codec behaviour.
24582
+ * - `-probesize 32 -analyzeduration 0`: skip stream probing — the input format
24583
+ * is fully specified by `-f`/`-ar`/`-ac`, so probing only adds startup delay.
24584
+ * - `-threads 1`: single-threaded — audio frames are tiny, and extra worker
24585
+ * threads only add scheduling jitter to a real-time path.
24586
+ */
24587
+ var AUDIO_LOW_LATENCY_ARGS = [
24588
+ "-hide_banner",
24589
+ "-nostats",
24590
+ "-loglevel",
24591
+ "error",
24592
+ "-fflags",
24593
+ "+nobuffer+flush_packets",
24594
+ "-flags",
24595
+ "low_delay",
24596
+ "-probesize",
24597
+ "32",
24598
+ "-analyzeduration",
24599
+ "0",
24600
+ "-threads",
24601
+ "1"
24602
+ ];
24603
+ /**
24604
+ * Normalise an SDP-reported codec name to the libav/ffmpeg name. Mirrors the
24605
+ * `resolveCodecAlias` in `audio-codec-nodeav` so callers can pass the
24606
+ * SDP-reported value verbatim.
24607
+ */
24608
+ function resolveAudioCodecAlias(codec) {
24609
+ const c = codec.toLowerCase();
24610
+ if (c === "mpeg4-generic") return "aac";
24611
+ if (c === "l16") return "pcm_s16be";
24612
+ return c;
24613
+ }
24614
+ /**
24615
+ * codec → ffmpeg DECODE input format.
24616
+ *
24617
+ * | codec | -f | raw? | note |
24618
+ * | ----------------------------- | ------ | ---- | ----------------------------- |
24619
+ * | pcm_mulaw | mulaw | yes | G.711 µ-law |
24620
+ * | pcm_alaw | alaw | yes | G.711 A-law |
24621
+ * | pcm_s16be (l16) | s16be | yes | RTP L16 |
24622
+ * | pcm_s16le | s16le | yes | |
24623
+ * | g722 | g722 | yes | 16 kHz wideband |
24624
+ * | aac / aac_latm / mpeg4-generic| aac | no | ADTS demuxer |
24625
+ * | opus | ogg | no | ⚠ needs Ogg framing (see NOTE)|
24626
+ *
24627
+ * NOTE (opus decode): ffmpeg has no raw-packet Opus demuxer. `audio-codec-nodeav`
24628
+ * feeds raw RTP Opus packets straight to the `AV_CODEC_ID_OPUS` decoder with no
24629
+ * demuxer; a subprocess cannot do that from a pipe. We map to `ogg`, which is
24630
+ * correct only if the pushed bytes are Ogg-Opus. Raw RTP Opus decode via the
24631
+ * subprocess is a KNOWN limitation — see the addon report.
24632
+ */
24633
+ var DECODE_FORMAT_BY_CODEC = {
24634
+ pcm_mulaw: {
24635
+ inputFormat: "mulaw",
24636
+ rawInput: true
24637
+ },
24638
+ pcm_alaw: {
24639
+ inputFormat: "alaw",
24640
+ rawInput: true
24641
+ },
24642
+ pcm_s16be: {
24643
+ inputFormat: "s16be",
24644
+ rawInput: true
24645
+ },
24646
+ pcm_s16le: {
24647
+ inputFormat: "s16le",
24648
+ rawInput: true
24649
+ },
24650
+ g722: {
24651
+ inputFormat: "g722",
24652
+ rawInput: true
24653
+ },
24654
+ aac: {
24655
+ inputFormat: "aac",
24656
+ rawInput: false
24657
+ },
24658
+ aac_latm: {
24659
+ inputFormat: "aac",
24660
+ rawInput: false
24661
+ },
24662
+ opus: {
24663
+ inputFormat: "ogg",
24664
+ rawInput: false
24665
+ }
24666
+ };
24667
+ /**
24668
+ * codec → ffmpeg ENCODE codec + container.
24669
+ *
24670
+ * | codec | -c:a | -f | bitrate? |
24671
+ * | --------- | ---------- | ----- | -------- |
24672
+ * | pcm_mulaw | pcm_mulaw | mulaw | no |
24673
+ * | pcm_alaw | pcm_alaw | alaw | no |
24674
+ * | g722 | g722 | g722 | no |
24675
+ * | aac | aac | adts | yes |
24676
+ * | opus | libopus | ogg | yes |
24677
+ */
24678
+ var ENCODE_FORMAT_BY_CODEC = {
24679
+ pcm_mulaw: {
24680
+ encoder: "pcm_mulaw",
24681
+ outputFormat: "mulaw",
24682
+ acceptsBitrate: false
24683
+ },
24684
+ pcm_alaw: {
24685
+ encoder: "pcm_alaw",
24686
+ outputFormat: "alaw",
24687
+ acceptsBitrate: false
24688
+ },
24689
+ g722: {
24690
+ encoder: "g722",
24691
+ outputFormat: "g722",
24692
+ acceptsBitrate: false
24693
+ },
24694
+ aac: {
24695
+ encoder: "aac",
24696
+ outputFormat: "adts",
24697
+ acceptsBitrate: true
24698
+ },
24699
+ opus: {
24700
+ encoder: "libopus",
24701
+ outputFormat: "ogg",
24702
+ acceptsBitrate: true
24703
+ }
24704
+ };
24705
+ /** Resolve the DECODE input-format descriptor for a codec, or `null` if unknown. */
24706
+ function decodeFormatForCodec(codec) {
24707
+ return DECODE_FORMAT_BY_CODEC[resolveAudioCodecAlias(codec)] ?? null;
24708
+ }
24709
+ /** Resolve the ENCODE codec+container descriptor for a codec, or `null` if unknown. */
24710
+ function encodeFormatForCodec(codec) {
24711
+ return ENCODE_FORMAT_BY_CODEC[resolveAudioCodecAlias(codec)] ?? null;
24712
+ }
24713
+ /** Packed bytes-per-sample for a PCM format (s16le = 2, f32le = 4). */
24714
+ function audioBytesPerSample(format) {
24715
+ return format === "f32le" ? 4 : 2;
24716
+ }
24717
+ /**
24718
+ * Build the ffmpeg argv for a DECODE session — encoded frames on `pipe:0`, raw
24719
+ * PCM on `pipe:1`. PURE: no spawn, no env access.
24720
+ *
24721
+ * ffmpeg <low-latency> -f <inputFmt> [-ar <src> -ac <srcCh>] -i pipe:0 \
24722
+ * -ar <target> -ac <targetCh> -f <s16le|f32le> pipe:1
24723
+ *
24724
+ * @throws if the codec has no known decode mapping.
24725
+ */
24726
+ function buildAudioDecodeArgs(config) {
24727
+ const entry = decodeFormatForCodec(config.codec);
24728
+ if (!entry) throw new Error(`audio-codec-ffmpeg: no decode format for codec '${config.codec}'`);
24729
+ const outFormat = config.targetFormat ?? "s16le";
24730
+ const inputRateChannel = entry.rawInput ? [
24731
+ "-ar",
24732
+ String(config.sourceSampleRate),
24733
+ "-ac",
24734
+ String(config.sourceChannels)
24735
+ ] : [];
24736
+ return [
24737
+ ...AUDIO_LOW_LATENCY_ARGS,
24738
+ "-f",
24739
+ entry.inputFormat,
24740
+ ...inputRateChannel,
24741
+ "-i",
24742
+ "pipe:0",
24743
+ "-ar",
24744
+ String(config.targetSampleRate),
24745
+ "-ac",
24746
+ String(config.targetChannels),
24747
+ "-f",
24748
+ outFormat,
24749
+ "pipe:1"
24750
+ ];
24751
+ }
24752
+ /**
24753
+ * Build the ffmpeg argv for an ENCODE session — raw PCM on `pipe:0`, encoded
24754
+ * bytes on `pipe:1`. PURE: no spawn, no env access.
24755
+ *
24756
+ * ffmpeg <low-latency> -f <s16le|f32le> -ar <src> -ac <srcCh> -i pipe:0 \
24757
+ * -c:a <encoder> -ar <target> -ac <targetCh> [-b:a <k>k] \
24758
+ * [-application lowdelay] -f <containerFmt> pipe:1
24759
+ *
24760
+ * For `libopus` the intercom-oriented `-application lowdelay` mode is added,
24761
+ * trading a little quality for the lowest algorithmic latency.
24762
+ *
24763
+ * @throws if the codec has no known encode mapping.
24764
+ */
24765
+ function buildAudioEncodeArgs(config) {
24766
+ const entry = encodeFormatForCodec(config.codec);
24767
+ if (!entry) throw new Error(`audio-codec-ffmpeg: no encode format for codec '${config.codec}'`);
24768
+ const inFormat = config.sourceFormat ?? "s16le";
24769
+ const bitrateArgs = entry.acceptsBitrate && config.bitrateKbps !== void 0 ? ["-b:a", `${config.bitrateKbps}k`] : [];
24770
+ const opusLowDelay = entry.encoder === "libopus" ? ["-application", "lowdelay"] : [];
24771
+ return [
24772
+ ...AUDIO_LOW_LATENCY_ARGS,
24773
+ "-f",
24774
+ inFormat,
24775
+ "-ar",
24776
+ String(config.sourceSampleRate),
24777
+ "-ac",
24778
+ String(config.sourceChannels),
24779
+ "-i",
24780
+ "pipe:0",
24781
+ "-c:a",
24782
+ entry.encoder,
24783
+ "-ar",
24784
+ String(config.targetSampleRate),
24785
+ "-ac",
24786
+ String(config.targetChannels),
24787
+ ...bitrateArgs,
24788
+ ...opusLowDelay,
24789
+ "-f",
24790
+ entry.outputFormat,
24791
+ "pipe:1"
24792
+ ];
24793
+ }
24794
+ //#endregion
24795
+ //#region src/audio-codec/ogg-opus-framer.ts
24796
+ /**
24797
+ * Ogg-Opus encapsulator for the `audio-codec-ffmpeg` decode path.
24798
+ *
24799
+ * Cameras / RTP deliver RAW Opus packets — one self-delimited Opus packet per
24800
+ * `pushEncodedFrame`. ffmpeg has NO raw-Opus demuxer, so the subprocess cannot
24801
+ * decode a bare packet stream from a pipe (unlike `audio-codec-nodeav`, which
24802
+ * feeds raw packets straight to `AV_CODEC_ID_OPUS` in-process). To decode Opus
24803
+ * out-of-process we must wrap the raw packets in a valid **Ogg-Opus** container
24804
+ * so `ffmpeg -f ogg -i pipe:0` can demux + decode them.
24805
+ *
24806
+ * This framer turns a stream of raw Opus packets into a byte stream shaped per
24807
+ * RFC 7845 (Ogg Encapsulation for Opus) + RFC 3533 (the Ogg container):
24808
+ *
24809
+ * Page 0 (BOS) : one "OpusHead" identification packet
24810
+ * Page 1 : one "OpusTags" comment packet
24811
+ * Page 2..n : one Opus audio packet each (one-packet-per-page = lowest
24812
+ * latency, simplest lacing), granule = running 48 kHz sample
24813
+ * total.
24814
+ * flush() : optional final EOS page.
24815
+ *
24816
+ * The Ogg page CRC is NOT the common zlib CRC-32: it uses polynomial
24817
+ * 0x04C11DB7 with init 0, NO input/output bit reflection, and NO final XOR,
24818
+ * computed over the whole page with the CRC field zeroed (see `oggCrc32`).
24819
+ */
24820
+ /** Ogg capture pattern, "OggS". */
24821
+ var OGG_CAPTURE_PATTERN = Buffer.from("OggS", "ascii");
24822
+ /** Opus identification header magic, "OpusHead". */
24823
+ var OPUS_HEAD_MAGIC = Buffer.from("OpusHead", "ascii");
24824
+ /** Opus comment header magic, "OpusTags". */
24825
+ var OPUS_TAGS_MAGIC = Buffer.from("OpusTags", "ascii");
24826
+ /** Ogg page header byte offsets (before the segment table). */
24827
+ var OGG_HEADER_FIXED_BYTES = 27;
24828
+ /** Byte offset of the 4-byte CRC field within the fixed header. */
24829
+ var OGG_CRC_OFFSET = 22;
24830
+ var HEADER_TYPE_BOS = 2;
24831
+ var HEADER_TYPE_EOS = 4;
24832
+ /** OpusHead `input sample rate` — informational per RFC 7845 (§5.1). */
24833
+ var OPUS_INPUT_SAMPLE_RATE = 48e3;
24834
+ /** Opus granule positions are ALWAYS counted at 48 kHz (RFC 7845 §4). */
24835
+ var OPUS_GRANULE_SAMPLE_RATE = 48e3;
24836
+ /**
24837
+ * Opus frame size, in 48 kHz samples, indexed by the 5-bit TOC `config`
24838
+ * (0..31). Derived from the frame-duration table in RFC 6716 §3.1:
24839
+ *
24840
+ * config 0-11 SILK NB/MB/WB → 10 / 20 / 40 / 60 ms
24841
+ * config 12-15 Hybrid SWB/FB → 10 / 20 ms
24842
+ * config 16-31 CELT NB/…/FB → 2.5 / 5 / 10 / 20 ms
24843
+ *
24844
+ * samples@48k = ms * 48 (2.5→120, 5→240, 10→480, 20→960, 40→1920, 60→2880).
24845
+ */
24846
+ var OPUS_FRAME_SAMPLES_48K = [
24847
+ 480,
24848
+ 960,
24849
+ 1920,
24850
+ 2880,
24851
+ 480,
24852
+ 960,
24853
+ 1920,
24854
+ 2880,
24855
+ 480,
24856
+ 960,
24857
+ 1920,
24858
+ 2880,
24859
+ 480,
24860
+ 960,
24861
+ 480,
24862
+ 960,
24863
+ 120,
24864
+ 240,
24865
+ 480,
24866
+ 960,
24867
+ 120,
24868
+ 240,
24869
+ 480,
24870
+ 960,
24871
+ 120,
24872
+ 240,
24873
+ 480,
24874
+ 960,
24875
+ 120,
24876
+ 240,
24877
+ 480,
24878
+ 960
24879
+ ];
24880
+ /**
24881
+ * Precomputed Ogg CRC-32 lookup table (MSB-first, polynomial 0x04C11DB7).
24882
+ *
24883
+ * Each entry is the CRC of the single byte `i` placed in the top position of a
24884
+ * 32-bit register, shifted out MSB-first with no reflection. This is the table
24885
+ * form of the bit-serial algorithm used by `oggCrc32`.
24886
+ */
24887
+ var OGG_CRC_TABLE = (() => {
24888
+ const table = new Uint32Array(256);
24889
+ for (let i = 0; i < 256; i++) {
24890
+ let r = i << 24 >>> 0;
24891
+ for (let bit = 0; bit < 8; bit++) r = (r & 2147483648) !== 0 ? (r << 1 ^ 79764919) >>> 0 : r << 1 >>> 0;
24892
+ table[i] = r >>> 0;
24893
+ }
24894
+ return table;
24895
+ })();
24896
+ /**
24897
+ * Ogg page CRC-32 (RFC 3533 §4). Polynomial 0x04C11DB7, init 0, NO input or
24898
+ * output reflection, NO final XOR — deliberately different from the reflected
24899
+ * zlib/IEEE CRC-32. Computed over the ENTIRE page bytes with the 4-byte CRC
24900
+ * field already zeroed.
24901
+ */
24902
+ function oggCrc32(data) {
24903
+ let crc = 0;
24904
+ for (let i = 0; i < data.length; i++) {
24905
+ const idx = (crc >>> 24 ^ (data[i] ?? 0)) & 255;
24906
+ crc = (crc << 8 >>> 0 ^ (OGG_CRC_TABLE[idx] ?? 0)) >>> 0;
24907
+ }
24908
+ return crc >>> 0;
24909
+ }
24910
+ /**
24911
+ * Decode an Opus packet's total duration in samples from its TOC byte
24912
+ * (RFC 6716 §3). Returns samples at `sampleRate` (default 48 kHz — the rate Ogg
24913
+ * granule positions are counted in).
24914
+ *
24915
+ * TOC byte layout: `config` (bits 3-7), `s` stereo (bit 2), `c` frame-count
24916
+ * code (bits 0-1):
24917
+ * - code 0 → 1 frame
24918
+ * - code 1 / 2 → 2 frames
24919
+ * - code 3 → arbitrary; frame count = low 6 bits of the byte after the TOC.
24920
+ *
24921
+ * Returns 0 for an empty or malformed (code-3 with no count byte) packet.
24922
+ */
24923
+ function opusPacketSampleCount(packet, sampleRate = 48e3) {
24924
+ if (packet.length < 1) return 0;
24925
+ const toc = packet[0] ?? 0;
24926
+ const config = toc >> 3;
24927
+ const code = toc & 3;
24928
+ const samplesPerFrame48k = OPUS_FRAME_SAMPLES_48K[config] ?? 0;
24929
+ if (samplesPerFrame48k === 0) return 0;
24930
+ let frameCount;
24931
+ if (code === 0) frameCount = 1;
24932
+ else if (code === 1 || code === 2) frameCount = 2;
24933
+ else {
24934
+ if (packet.length < 2) return 0;
24935
+ frameCount = (packet[1] ?? 0) & 63;
24936
+ }
24937
+ const samples48k = samplesPerFrame48k * frameCount;
24938
+ if (sampleRate === OPUS_GRANULE_SAMPLE_RATE) return samples48k;
24939
+ return Math.round(samples48k * sampleRate / OPUS_GRANULE_SAMPLE_RATE);
24940
+ }
24941
+ /**
24942
+ * Encode an Ogg lacing segment table for a single packet of length `len`
24943
+ * (RFC 3533 §6): `floor(len/255)` bytes of 0xFF then one final byte `len%255`.
24944
+ * A length that is an exact multiple of 255 therefore ends in a `0x00` lacing
24945
+ * value — required so the demuxer knows the packet terminates on this page.
24946
+ */
24947
+ function buildLacing(len) {
24948
+ const full = Math.floor(len / 255);
24949
+ const table = Buffer.alloc(full + 1);
24950
+ table.fill(255, 0, full);
24951
+ table[full] = len % 255;
24952
+ return table;
24953
+ }
24954
+ /**
24955
+ * Turn a hash-derivable seed into a stable 32-bit Ogg bitstream serial. FNV-1a
24956
+ * over the seed string keeps distinct sessions on distinct serials without
24957
+ * requiring the caller to allocate one.
24958
+ */
24959
+ function serialFromSeed(seed) {
24960
+ let hash = 2166136261;
24961
+ for (let i = 0; i < seed.length; i++) {
24962
+ hash ^= seed.charCodeAt(i) & 255;
24963
+ hash = Math.imul(hash, 16777619);
24964
+ }
24965
+ return hash >>> 0;
24966
+ }
24967
+ /**
24968
+ * Streaming Ogg-Opus encapsulator. Stateful: tracks page sequence numbers and
24969
+ * the running 48 kHz granule position across calls. One instance per decode
24970
+ * session; call {@link reset} to reuse it for a fresh stream.
24971
+ */
24972
+ var OggOpusFramer = class {
24973
+ channelCount;
24974
+ serial;
24975
+ preSkip;
24976
+ vendor;
24977
+ pageSeq = 0;
24978
+ granule = 0;
24979
+ headersEmitted = false;
24980
+ audioEmitted = false;
24981
+ constructor(config) {
24982
+ this.channelCount = config.channelCount;
24983
+ this.serial = config.serial >>> 0;
24984
+ this.preSkip = config.preSkip ?? 3840;
24985
+ this.vendor = config.vendor ?? "camstack";
24986
+ }
24987
+ /**
24988
+ * Build the two header pages (OpusHead BOS + OpusTags). Advances the page
24989
+ * sequence to 2 so audio pages follow. Returns an empty buffer if the headers
24990
+ * were already emitted (idempotent within a stream).
24991
+ */
24992
+ headerPages() {
24993
+ if (this.headersEmitted) return Buffer.alloc(0);
24994
+ this.headersEmitted = true;
24995
+ const head = this.buildOpusHead();
24996
+ const tags = this.buildOpusTags();
24997
+ const headPage = this.buildPage(head, HEADER_TYPE_BOS, 0);
24998
+ const tagsPage = this.buildPage(tags, 0, 0);
24999
+ return Buffer.concat([headPage, tagsPage]);
25000
+ }
25001
+ /**
25002
+ * Encapsulate one raw Opus packet as a single audio page, advancing the
25003
+ * granule by the packet's decoded sample count. Header pages are emitted
25004
+ * (and prepended) automatically on the first call, so the caller can simply
25005
+ * write the returned bytes to ffmpeg stdin.
25006
+ */
25007
+ framePacket(packet) {
25008
+ const prefix = this.headersEmitted ? Buffer.alloc(0) : this.headerPages();
25009
+ this.granule += opusPacketSampleCount(packet, OPUS_GRANULE_SAMPLE_RATE);
25010
+ this.audioEmitted = true;
25011
+ const page = this.buildPage(packet, 0, this.granule);
25012
+ return prefix.length > 0 ? Buffer.concat([prefix, page]) : page;
25013
+ }
25014
+ /**
25015
+ * Emit a final EOS page terminating the logical bitstream. Returns `null`
25016
+ * when no audio was written (nothing to terminate). The EOS page carries no
25017
+ * packet data (0 segments) and the final granule position.
25018
+ */
25019
+ flush() {
25020
+ if (!this.audioEmitted) return null;
25021
+ return this.buildPage(null, HEADER_TYPE_EOS, this.granule);
25022
+ }
25023
+ /** Reset all page/granule state so the instance can frame a fresh stream. */
25024
+ reset() {
25025
+ this.pageSeq = 0;
25026
+ this.granule = 0;
25027
+ this.headersEmitted = false;
25028
+ this.audioEmitted = false;
25029
+ }
25030
+ /** OpusHead identification packet (RFC 7845 §5.1) — 19 bytes for family 0. */
25031
+ buildOpusHead() {
25032
+ const buf = Buffer.alloc(19);
25033
+ OPUS_HEAD_MAGIC.copy(buf, 0);
25034
+ buf.writeUInt8(1, 8);
25035
+ buf.writeUInt8(this.channelCount, 9);
25036
+ buf.writeUInt16LE(this.preSkip & 65535, 10);
25037
+ buf.writeUInt32LE(OPUS_INPUT_SAMPLE_RATE, 12);
25038
+ buf.writeInt16LE(0, 16);
25039
+ buf.writeUInt8(0, 18);
25040
+ return buf;
25041
+ }
25042
+ /** OpusTags comment packet (RFC 7845 §5.2) — magic, vendor, 0 comments. */
25043
+ buildOpusTags() {
25044
+ const vendor = Buffer.from(this.vendor, "utf8");
25045
+ const buf = Buffer.alloc(12 + vendor.length + 4);
25046
+ OPUS_TAGS_MAGIC.copy(buf, 0);
25047
+ buf.writeUInt32LE(vendor.length, 8);
25048
+ vendor.copy(buf, 12);
25049
+ buf.writeUInt32LE(0, 12 + vendor.length);
25050
+ return buf;
25051
+ }
25052
+ /**
25053
+ * Assemble one Ogg page around a single packet (or none, for an EOS
25054
+ * terminator), compute its CRC, and return the framed bytes. Keeps to a
25055
+ * single packet per page so the segment count never approaches the 255 limit
25056
+ * (an Opus packet is ≤ ~1275 bytes → ≤ 6 lacing segments).
25057
+ */
25058
+ buildPage(packet, headerType, granule) {
25059
+ const lacing = packet !== null ? buildLacing(packet.length) : Buffer.alloc(0);
25060
+ const segmentCount = lacing.length;
25061
+ const bodyLen = packet !== null ? packet.length : 0;
25062
+ const page = Buffer.alloc(OGG_HEADER_FIXED_BYTES + segmentCount + bodyLen);
25063
+ OGG_CAPTURE_PATTERN.copy(page, 0);
25064
+ page.writeUInt8(0, 4);
25065
+ page.writeUInt8(headerType & 7, 5);
25066
+ this.writeGranule(page, granule, 6);
25067
+ page.writeUInt32LE(this.serial, 14);
25068
+ page.writeUInt32LE(this.pageSeq >>> 0, 18);
25069
+ page.writeUInt32LE(0, OGG_CRC_OFFSET);
25070
+ page.writeUInt8(segmentCount, 26);
25071
+ lacing.copy(page, OGG_HEADER_FIXED_BYTES);
25072
+ if (packet !== null) packet.copy(page, OGG_HEADER_FIXED_BYTES + segmentCount);
25073
+ const crc = oggCrc32(page);
25074
+ page.writeUInt32LE(crc, OGG_CRC_OFFSET);
25075
+ this.pageSeq = this.pageSeq + 1 >>> 0;
25076
+ return page;
25077
+ }
25078
+ /**
25079
+ * Write a 64-bit little-endian granule position. Values fit comfortably in a
25080
+ * JS safe integer for any realistic stream duration (2^53 samples @48k ≈ 5940
25081
+ * years), so a split 32-bit lo/hi write is exact and avoids BigInt on the
25082
+ * hot path.
25083
+ */
25084
+ writeGranule(page, granule, offset) {
25085
+ const lo = granule >>> 0;
25086
+ const hi = Math.floor(granule / 4294967296) >>> 0;
25087
+ page.writeUInt32LE(lo, offset);
25088
+ page.writeUInt32LE(hi, offset + 4);
25089
+ }
25090
+ };
25091
+ //#endregion
25092
+ //#region src/audio-codec/adts.ts
25093
+ /**
25094
+ * ADTS framing for raw AAC access units.
25095
+ *
25096
+ * The audio decode path runs `ffmpeg -f aac -i pipe:0` — the **ADTS** demuxer,
25097
+ * which requires each frame to begin with a 7-byte ADTS header (0xFFF sync).
25098
+ * But every AAC source that reaches the decoder delivers **raw** AAC access
25099
+ * units with no ADTS header: push sources (Reolink Baichuan) emit one bare
25100
+ * codec frame per packet, and rfc3640 (RTP AAC) depacketization yields bare
25101
+ * AUs too. Piping those straight into `-f aac` fails with
25102
+ * `Invalid data found when processing input` → no PCM → a silent WebRTC audio
25103
+ * track. Wrapping each raw AU in an ADTS header (built from the source
25104
+ * sample-rate / channel-count / AAC object type) makes the demuxer accept it.
25105
+ *
25106
+ * Opus is handled separately (Ogg encapsulation); this module is AAC-only.
25107
+ */
25108
+ /** MPEG-4 AAC sampling-frequency index table (ISO/IEC 14496-3). */
25109
+ var AAC_SAMPLE_RATES = [
25110
+ 96e3,
25111
+ 88200,
25112
+ 64e3,
25113
+ 48e3,
25114
+ 44100,
25115
+ 32e3,
25116
+ 24e3,
25117
+ 22050,
25118
+ 16e3,
25119
+ 12e3,
25120
+ 11025,
25121
+ 8e3,
25122
+ 7350
25123
+ ];
25124
+ /** AAC-LC is object type 2; the ADTS `profile` field is objectType - 1. */
25125
+ var DEFAULT_AAC_OBJECT_TYPE = 2;
25126
+ /** Resolve the ADTS sampling-frequency index for a sample rate (default 16 kHz → 8). */
25127
+ function aacSampleRateIndex(sampleRate) {
25128
+ const idx = AAC_SAMPLE_RATES.indexOf(sampleRate);
25129
+ return idx >= 0 ? idx : AAC_SAMPLE_RATES.indexOf(16e3);
25130
+ }
25131
+ /**
25132
+ * True when `buf` already begins with an ADTS syncword (0xFFF) + MPEG layer 0.
25133
+ * Raw AAC AUs never do; ADTS-framed frames always do. Lets the wrapper pass
25134
+ * already-framed input through untouched.
25135
+ */
25136
+ function hasAdtsSync(buf) {
25137
+ return buf.length >= 2 && buf[0] === 255 && (buf[1] & 246) === 240;
25138
+ }
25139
+ /**
25140
+ * Build the 7-byte ADTS header (no CRC) for a payload of `payloadLength` bytes.
25141
+ */
25142
+ function buildAdtsHeader(config, payloadLength) {
25143
+ const objectType = config.aacObjectType ?? DEFAULT_AAC_OBJECT_TYPE;
25144
+ const profile = Math.max(0, objectType - 1) & 3;
25145
+ const freqIdx = aacSampleRateIndex(config.sampleRate) & 15;
25146
+ const chanCfg = Math.max(1, config.channels) & 7;
25147
+ const frameLength = payloadLength + 7;
25148
+ const h = Buffer.alloc(7);
25149
+ h[0] = 255;
25150
+ h[1] = 241;
25151
+ h[2] = profile << 6 | freqIdx << 2 | chanCfg >> 2 & 1;
25152
+ h[3] = (chanCfg & 3) << 6 | frameLength >> 11 & 3;
25153
+ h[4] = frameLength >> 3 & 255;
25154
+ h[5] = (frameLength & 7) << 5 | 31;
25155
+ h[6] = 252;
25156
+ return h;
25157
+ }
25158
+ /**
25159
+ * Return `frame` framed as ADTS: unchanged when it already carries an ADTS
25160
+ * sync, otherwise the 7-byte header prepended. Pure; the input is never mutated.
25161
+ */
25162
+ function wrapAacAsAdts(frame, config) {
25163
+ if (hasAdtsSync(frame)) return Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength);
25164
+ const payload = Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength);
25165
+ return Buffer.concat([buildAdtsHeader(config, payload.length), payload]);
25166
+ }
25167
+ //#endregion
25168
+ //#region src/audio-codec/ffmpeg-audio-decode-session.ts
25169
+ var FfmpegAudioDecodeSession = class {
25170
+ logger;
25171
+ process;
25172
+ outFormat;
25173
+ bytesPerFrame;
25174
+ targetSampleRate;
25175
+ targetChannels;
25176
+ onChunk;
25177
+ /**
25178
+ * Ogg-Opus encapsulator, present ONLY when the codec is Opus. Raw Opus
25179
+ * packets have no ffmpeg demuxer, so each pushed packet is wrapped in an
25180
+ * Ogg page (with OpusHead/OpusTags emitted before the first) so
25181
+ * `ffmpeg -f ogg -i pipe:0` can demux + decode. `null` for all other codecs,
25182
+ * which pipe their encoded frames straight through.
25183
+ */
25184
+ oggFramer;
25185
+ /**
25186
+ * ADTS framing config, present ONLY when the codec is AAC. `ffmpeg -f aac`
25187
+ * is the ADTS demuxer, but every AAC source delivers raw AAC access units
25188
+ * (push sources emit bare frames; rfc3640 depacketization yields bare AUs) —
25189
+ * piping those in raw fails `Invalid data found when processing input` → no
25190
+ * PCM → silent WebRTC audio. Each frame is ADTS-wrapped before ffmpeg.
25191
+ */
25192
+ adtsConfig;
25193
+ residual = Buffer.alloc(0);
25194
+ nextPts = 0;
25195
+ destroyed = false;
25196
+ constructor(params, logger, onChunk) {
25197
+ this.logger = logger;
25198
+ this.onChunk = onChunk;
25199
+ this.outFormat = params.targetFormat ?? "s16le";
25200
+ this.targetSampleRate = params.targetSampleRate;
25201
+ this.targetChannels = params.targetChannels;
25202
+ this.bytesPerFrame = Math.max(1, params.targetChannels * audioBytesPerSample(this.outFormat));
25203
+ this.oggFramer = resolveAudioCodecAlias(params.codec) === "opus" ? new OggOpusFramer({
25204
+ channelCount: Math.max(1, params.sourceChannels),
25205
+ serial: serialFromSeed(params.oggSerialSeed ?? "audio-codec-ffmpeg-opus")
25206
+ }) : null;
25207
+ this.adtsConfig = resolveAudioCodecAlias(params.codec) === "aac" ? {
25208
+ sampleRate: params.sourceSampleRate,
25209
+ channels: Math.max(1, params.sourceChannels)
25210
+ } : null;
25211
+ const args = buildAudioDecodeArgs(params);
25212
+ this.process = new FfmpegAudioProcess({
25213
+ ffmpegPath: params.ffmpegPath,
25214
+ args,
25215
+ logger,
25216
+ onStdout: (chunk) => this.handleStdout(chunk),
25217
+ onExit: (code, signal) => {
25218
+ if (this.destroyed) return;
25219
+ this.logger.warn("audio-codec-ffmpeg: decode child exited", { meta: {
25220
+ code,
25221
+ signal
25222
+ } });
25223
+ }
25224
+ });
25225
+ }
25226
+ /** Push one encoded audio frame into ffmpeg stdin. */
25227
+ pushEncoded(data) {
25228
+ if (this.destroyed) return;
25229
+ if (this.oggFramer) {
25230
+ const packet = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
25231
+ this.process.write(this.oggFramer.framePacket(packet));
25232
+ return;
25233
+ }
25234
+ if (this.adtsConfig) {
25235
+ this.process.write(wrapAacAsAdts(data, this.adtsConfig));
25236
+ return;
25237
+ }
25238
+ this.process.write(data);
25239
+ }
25240
+ handleStdout(chunk) {
25241
+ if (this.destroyed) return;
25242
+ const buf = this.residual.length === 0 ? chunk : Buffer.concat([this.residual, chunk]);
25243
+ const frameBytes = this.bytesPerFrame;
25244
+ const usable = buf.length - buf.length % frameBytes;
25245
+ if (usable <= 0) {
25246
+ this.residual = buf;
25247
+ return;
25248
+ }
25249
+ const emit = buf.subarray(0, usable);
25250
+ this.residual = usable < buf.length ? Buffer.from(buf.subarray(usable)) : Buffer.alloc(0);
25251
+ const out = new Uint8Array(new ArrayBuffer(usable));
25252
+ out.set(emit);
25253
+ const samples = usable / frameBytes;
25254
+ const pts = this.nextPts;
25255
+ this.nextPts = pts + Math.round(samples * 1e3 / this.targetSampleRate);
25256
+ this.onChunk({
25257
+ data: out,
25258
+ sampleRate: this.targetSampleRate,
25259
+ channels: this.targetChannels,
25260
+ format: this.outFormat,
25261
+ pts
25262
+ });
25263
+ }
25264
+ destroy() {
25265
+ if (this.destroyed) return;
25266
+ this.destroyed = true;
25267
+ if (this.oggFramer) {
25268
+ const eos = this.oggFramer.flush();
25269
+ if (eos) this.process.write(eos);
25270
+ }
25271
+ this.process.kill();
25272
+ this.residual = Buffer.alloc(0);
25273
+ }
25274
+ };
25275
+ //#endregion
25276
+ //#region src/audio-codec/ffmpeg-audio-encode-session.ts
25277
+ var FfmpegAudioEncodeSession = class {
25278
+ logger;
25279
+ process;
25280
+ codec;
25281
+ onChunk;
25282
+ nextPts = 0;
25283
+ destroyed = false;
25284
+ constructor(params, logger, onChunk) {
25285
+ this.logger = logger;
25286
+ this.onChunk = onChunk;
25287
+ this.codec = resolveAudioCodecAlias(params.codec);
25288
+ const args = buildAudioEncodeArgs(params);
25289
+ this.process = new FfmpegAudioProcess({
25290
+ ffmpegPath: params.ffmpegPath,
25291
+ args,
25292
+ logger,
25293
+ onStdout: (chunk) => this.handleStdout(chunk),
25294
+ onExit: (code, signal) => {
25295
+ if (this.destroyed) return;
25296
+ this.logger.warn("audio-codec-ffmpeg: encode child exited", { meta: {
25297
+ code,
25298
+ signal
25299
+ } });
25300
+ }
25301
+ });
25302
+ }
25303
+ /** Push one PCM chunk into ffmpeg stdin. */
25304
+ pushPcm(data) {
25305
+ if (this.destroyed) return;
25306
+ this.process.write(data);
25307
+ }
25308
+ /** Close stdin so ffmpeg flushes and drains the remaining encoded output. */
25309
+ flush() {
25310
+ if (this.destroyed) return;
25311
+ this.process.endStdin();
25312
+ }
25313
+ handleStdout(chunk) {
25314
+ if (this.destroyed || chunk.length === 0) return;
25315
+ const out = new Uint8Array(new ArrayBuffer(chunk.length));
25316
+ out.set(chunk);
25317
+ const pts = this.nextPts;
25318
+ this.nextPts = pts + 1;
25319
+ this.onChunk({
25320
+ data: out,
25321
+ codec: this.codec,
25322
+ pts,
25323
+ frameComplete: true
25324
+ });
25325
+ }
25326
+ destroy() {
25327
+ if (this.destroyed) return;
25328
+ this.destroyed = true;
25329
+ this.process.kill();
25330
+ }
25331
+ };
25332
+ //#endregion
25333
+ //#region src/audio-codec/provider.ts
25334
+ var CODEC_CATALOG = [
25335
+ {
25336
+ codec: "pcm_mulaw",
25337
+ canDecode: true,
25338
+ canEncode: true,
25339
+ label: "PCM µ-law (G.711)"
25340
+ },
25341
+ {
25342
+ codec: "pcm_alaw",
25343
+ canDecode: true,
25344
+ canEncode: true,
25345
+ label: "PCM A-law (G.711)"
25346
+ },
25347
+ {
25348
+ codec: "g722",
25349
+ canDecode: true,
25350
+ canEncode: true,
25351
+ label: "G.722"
25352
+ },
25353
+ {
25354
+ codec: "aac",
25355
+ canDecode: true,
25356
+ canEncode: true,
25357
+ label: "AAC"
25358
+ },
25359
+ {
25360
+ codec: "aac_latm",
25361
+ canDecode: true,
25362
+ canEncode: false,
25363
+ label: "AAC LATM"
25364
+ },
25365
+ {
25366
+ codec: "mpeg4-generic",
25367
+ canDecode: true,
25368
+ canEncode: false,
25369
+ label: "AAC (MPEG4-GENERIC)"
25370
+ },
25371
+ {
25372
+ codec: "opus",
25373
+ canDecode: true,
25374
+ canEncode: true,
25375
+ label: "Opus"
25376
+ }
25377
+ ];
25378
+ var DEFAULT_IDLE_MS = 3e4;
25379
+ var MAX_PCM_QUEUE_CHUNKS = 500;
25380
+ var REAPER_INTERVAL_MS = 5e3;
25381
+ /**
25382
+ * Grace wait in `flushEncode` for ffmpeg to drain its encoder after stdin is
25383
+ * closed. This is a graceful-teardown path (not the real-time push path), so a
25384
+ * short wait is acceptable to capture the encoder's tail output.
25385
+ */
25386
+ var FLUSH_DRAIN_MS = 60;
25387
+ /**
25388
+ * Audio codec I/O box backed by an **ffmpeg subprocess** (Phase B replacement
25389
+ * for `audio-codec-nodeav`, which runs libavcodec + libswresample in-process).
25390
+ *
25391
+ * Each `createDecodeSession` / `createEncodeSession` spawns its own ffmpeg
25392
+ * child, so consumers never share a resampler and a codec crash is isolated to
25393
+ * the child — the addon runner survives. Cap surface + session bookkeeping
25394
+ * mirror the node-av addon exactly; only the codec backend changed.
25395
+ *
25396
+ * This is a PLAIN provider class merged into the `decoder-ffmpeg` addon (which
25397
+ * provides both the `decoder` video cap and this `audio-codec` cap). The parent
25398
+ * addon owns lifecycle: it resolves the ffmpeg path once, calls {@link start} in
25399
+ * `onInitialize`, and {@link stop} in `onShutdown`.
25400
+ */
25401
+ var FfmpegAudioCodecProvider = class {
25402
+ deps;
25403
+ sessions = /* @__PURE__ */ new Map();
25404
+ reaperTimer = null;
25405
+ constructor(deps) {
25406
+ this.deps = deps;
25407
+ }
25408
+ /** Start the idle-session reaper. Called by the parent addon at init. */
25409
+ start() {
25410
+ this.reaperTimer = setInterval(() => this.reapIdleSessions(), REAPER_INTERVAL_MS);
25411
+ if (typeof this.reaperTimer.unref === "function") this.reaperTimer.unref();
25412
+ }
25413
+ /** Clear the reaper and dispose every session. Called by the parent at shutdown. */
25414
+ stop() {
25415
+ if (this.reaperTimer) {
25416
+ clearInterval(this.reaperTimer);
25417
+ this.reaperTimer = null;
25418
+ }
25419
+ for (const s of this.sessions.values()) this.disposeSession(s);
25420
+ this.sessions.clear();
25421
+ }
25422
+ async listSupportedCodecs() {
25423
+ return CODEC_CATALOG.map((e) => ({
25424
+ codec: e.codec,
25425
+ canDecode: e.canDecode,
25426
+ canEncode: e.canEncode,
25427
+ ...e.label ? { label: e.label } : {}
25428
+ }));
25429
+ }
25430
+ async canHandle(input) {
25431
+ const resolved = resolveAudioCodecAlias(input.codec);
25432
+ const entry = CODEC_CATALOG.find((e) => resolveAudioCodecAlias(e.codec) === resolved);
25433
+ if (!entry) return false;
25434
+ return input.kind === "decode" ? entry.canDecode : entry.canEncode;
25435
+ }
25436
+ async createDecodeSession(input) {
25437
+ const codec = resolveAudioCodecAlias(input.codec);
25438
+ const entry = CODEC_CATALOG.find((e) => resolveAudioCodecAlias(e.codec) === codec);
25439
+ if (!entry || !entry.canDecode) throw new Error(`audio-codec-ffmpeg: decode unsupported for codec '${input.codec}'`);
25440
+ const sessionId = `dec-${randomUUID()}`;
25441
+ const state = {
25442
+ sessionId,
25443
+ kind: "decode",
25444
+ config: {
25445
+ ...input,
25446
+ codec
25447
+ },
25448
+ ...input.tag ? { tag: input.tag } : {},
25449
+ createdAtMs: Date.now(),
25450
+ lastActivityMs: Date.now(),
25451
+ framesIn: 0,
25452
+ framesOut: 0,
25453
+ pcmQueue: [],
25454
+ session: null
25455
+ };
25456
+ state.session = this.spawnDecodeSession(state);
25457
+ this.sessions.set(sessionId, state);
25458
+ this.deps.logger.info("audio-codec-ffmpeg: decode session created", {
25459
+ tags: { sessionId },
25460
+ meta: {
25461
+ codec,
25462
+ target: `${input.targetSampleRate}Hz×${input.targetChannels}`
25463
+ }
25464
+ });
25465
+ return {
25466
+ sessionId,
25467
+ nodeId: this.deps.resolveLocalNodeId()
25468
+ };
25469
+ }
25470
+ async createEncodeSession(input) {
25471
+ const codec = resolveAudioCodecAlias(input.codec);
25472
+ const entry = CODEC_CATALOG.find((e) => resolveAudioCodecAlias(e.codec) === codec);
25473
+ if (!entry || !entry.canEncode) throw new Error(`audio-codec-ffmpeg: encode unsupported for codec '${input.codec}'`);
25474
+ const sessionId = `enc-${randomUUID()}`;
25475
+ const state = {
25476
+ sessionId,
25477
+ kind: "encode",
25478
+ config: {
25479
+ ...input,
25480
+ codec
25481
+ },
25482
+ ...input.tag ? { tag: input.tag } : {},
25483
+ createdAtMs: Date.now(),
25484
+ lastActivityMs: Date.now(),
25485
+ framesIn: 0,
25486
+ framesOut: 0,
25487
+ encodedQueue: [],
25488
+ session: null
25489
+ };
25490
+ state.session = this.spawnEncodeSession(state);
25491
+ this.sessions.set(sessionId, state);
25492
+ this.deps.logger.info("audio-codec-ffmpeg: encode session created", {
25493
+ tags: { sessionId },
25494
+ meta: {
25495
+ codec,
25496
+ target: `${input.targetSampleRate}Hz×${input.targetChannels}`
25497
+ }
25498
+ });
25499
+ return {
25500
+ sessionId,
25501
+ nodeId: this.deps.resolveLocalNodeId()
25502
+ };
25503
+ }
25504
+ async closeSession(input) {
25505
+ const s = this.sessions.get(input.sessionId);
25506
+ if (!s) return;
25507
+ this.disposeSession(s);
25508
+ this.sessions.delete(input.sessionId);
25509
+ }
25510
+ async pushEncodedFrame(input) {
25511
+ const s = this.sessions.get(input.sessionId);
25512
+ if (!s || s.kind !== "decode") throw new Error(`audio-codec-ffmpeg: decode session '${input.sessionId}' not found`);
25513
+ s.lastActivityMs = Date.now();
25514
+ s.framesIn++;
25515
+ if (!s.session) s.session = this.spawnDecodeSession(s);
25516
+ s.session.pushEncoded(input.data);
25517
+ }
25518
+ async pullPcm(input) {
25519
+ const s = this.sessions.get(input.sessionId);
25520
+ if (!s || s.kind !== "decode") throw new Error(`audio-codec-ffmpeg: decode session '${input.sessionId}' not found`);
25521
+ s.lastActivityMs = Date.now();
25522
+ const out = s.pcmQueue.splice(0, input.maxCount);
25523
+ s.framesOut += out.length;
25524
+ return out;
25525
+ }
25526
+ async pushPcm(input) {
25527
+ const s = this.sessions.get(input.sessionId);
25528
+ if (!s || s.kind !== "encode") throw new Error(`audio-codec-ffmpeg: encode session '${input.sessionId}' not found`);
25529
+ s.lastActivityMs = Date.now();
25530
+ s.framesIn++;
25531
+ if (!s.session) s.session = this.spawnEncodeSession(s);
25532
+ s.session.pushPcm(input.data);
25533
+ }
25534
+ async pullEncoded(input) {
25535
+ const s = this.sessions.get(input.sessionId);
25536
+ if (!s || s.kind !== "encode") throw new Error(`audio-codec-ffmpeg: encode session '${input.sessionId}' not found`);
25537
+ s.lastActivityMs = Date.now();
25538
+ const out = s.encodedQueue.splice(0, input.maxCount);
25539
+ s.framesOut += out.length;
25540
+ return out;
25541
+ }
25542
+ async flushEncode(input) {
25543
+ const s = this.sessions.get(input.sessionId);
25544
+ if (!s || s.kind !== "encode") throw new Error(`audio-codec-ffmpeg: encode session '${input.sessionId}' not found`);
25545
+ s.lastActivityMs = Date.now();
25546
+ s.session?.flush();
25547
+ await new Promise((resolve) => setTimeout(resolve, FLUSH_DRAIN_MS));
25548
+ const out = s.encodedQueue.splice(0);
25549
+ s.framesOut += out.length;
25550
+ return out;
25551
+ }
25552
+ async listActiveSessions() {
25553
+ return [...this.sessions.values()].map((s) => ({
25554
+ sessionId: s.sessionId,
25555
+ kind: s.kind,
25556
+ codec: s.config.codec,
25557
+ sourceSampleRate: s.config.sourceSampleRate,
25558
+ sourceChannels: s.config.sourceChannels,
25559
+ targetSampleRate: s.config.targetSampleRate,
25560
+ targetChannels: s.config.targetChannels,
25561
+ format: this.resolveFormat(s),
25562
+ ...s.tag ? { tag: s.tag } : {},
25563
+ createdAtMs: s.createdAtMs,
25564
+ lastActivityMs: s.lastActivityMs,
25565
+ framesIn: s.framesIn,
25566
+ framesOut: s.framesOut
25567
+ }));
25568
+ }
25569
+ spawnDecodeSession(s) {
25570
+ return new FfmpegAudioDecodeSession({
25571
+ codec: s.config.codec,
25572
+ sourceSampleRate: s.config.sourceSampleRate,
25573
+ sourceChannels: s.config.sourceChannels,
25574
+ targetSampleRate: s.config.targetSampleRate,
25575
+ targetChannels: s.config.targetChannels,
25576
+ targetFormat: this.pcmFormat(s.config.targetFormat),
25577
+ ffmpegPath: this.deps.ffmpegPath,
25578
+ oggSerialSeed: s.sessionId
25579
+ }, this.deps.logger, (chunk) => {
25580
+ s.pcmQueue.push(chunk);
25581
+ if (s.pcmQueue.length > MAX_PCM_QUEUE_CHUNKS) s.pcmQueue.splice(0, s.pcmQueue.length - MAX_PCM_QUEUE_CHUNKS);
25582
+ });
25583
+ }
25584
+ spawnEncodeSession(s) {
25585
+ return new FfmpegAudioEncodeSession({
25586
+ codec: s.config.codec,
25587
+ sourceSampleRate: s.config.sourceSampleRate,
25588
+ sourceChannels: s.config.sourceChannels,
25589
+ sourceFormat: this.pcmFormat(s.config.sourceFormat),
25590
+ targetSampleRate: s.config.targetSampleRate,
25591
+ targetChannels: s.config.targetChannels,
25592
+ ...s.config.bitrateKbps !== void 0 ? { bitrateKbps: s.config.bitrateKbps } : {},
25593
+ ffmpegPath: this.deps.ffmpegPath
25594
+ }, this.deps.logger, (chunk) => {
25595
+ s.encodedQueue.push(chunk);
25596
+ });
25597
+ }
25598
+ /** Narrow the cap's PCM format enum to the two ffmpeg sessions produce/read. */
25599
+ pcmFormat(format) {
25600
+ return format === "f32le" ? "f32le" : "s16le";
25601
+ }
25602
+ resolveFormat(s) {
25603
+ if (s.kind === "decode") return this.pcmFormat(s.config.targetFormat);
25604
+ return this.pcmFormat(s.config.sourceFormat);
25605
+ }
25606
+ reapIdleSessions() {
25607
+ const now = Date.now();
25608
+ for (const [id, s] of this.sessions) {
25609
+ const limit = s.config.idleMs ?? this.deps.defaultIdleMs ?? DEFAULT_IDLE_MS;
25610
+ if (now - s.lastActivityMs > limit) {
25611
+ this.deps.logger.info("audio-codec-ffmpeg: reaping idle session", {
25612
+ tags: { sessionId: id },
25613
+ meta: {
25614
+ kind: s.kind,
25615
+ idleMs: now - s.lastActivityMs,
25616
+ limit
25617
+ }
25618
+ });
25619
+ try {
25620
+ this.disposeSession(s);
25621
+ } catch (err) {
25622
+ this.deps.logger.warn("audio-codec-ffmpeg: dispose failed during reap", {
25623
+ tags: { sessionId: id },
25624
+ meta: { error: errMsg(err) }
25625
+ });
25626
+ }
25627
+ this.sessions.delete(id);
25628
+ }
25629
+ }
25630
+ }
25631
+ disposeSession(s) {
25632
+ try {
25633
+ s.session?.destroy();
25634
+ } catch (err) {
25635
+ this.deps.logger.warn("audio-codec-ffmpeg: session destroy failed", {
25636
+ tags: { sessionId: s.sessionId },
25637
+ meta: { error: errMsg(err) }
25638
+ });
25639
+ }
25640
+ s.session = null;
25641
+ }
25642
+ };
25643
+ //#endregion
24137
25644
  //#region src/addon/index.ts
24138
25645
  var FRAME_BUFFER_CAPACITY = 32;
24139
25646
  /**
@@ -24173,6 +25680,14 @@ var DecoderFfmpegAddon = class extends BaseAddon {
24173
25680
  * process — e.g. a videotoolbox build whose decode returns software frames.
24174
25681
  */
24175
25682
  unsupportedGpuScaleFilters = /* @__PURE__ */ new Set();
25683
+ /**
25684
+ * The merged-in ffmpeg AUDIO codec provider — registers the `audio-codec` cap
25685
+ * ALWAYS (independent of the per-node video decoder backend), so this addon
25686
+ * serves both video decode and bidirectional audio transcode. Owns its own
25687
+ * ffmpeg subprocess sessions + idle reaper; started at init, stopped at
25688
+ * shutdown. Shares the single node-level ffmpeg binary this addon resolves.
25689
+ */
25690
+ audioProvider = null;
24176
25691
  constructor() {
24177
25692
  super(DEFAULT_DECODER_FFMPEG_ADDON_CONFIG);
24178
25693
  }
@@ -24210,23 +25725,40 @@ var DecoderFfmpegAddon = class extends BaseAddon {
24210
25725
  if (!this.config.probedBestHwaccel) this.reprobeHwaccel().catch((err) => {
24211
25726
  this.ctx.logger.warn("ffmpeg: auto-reprobe hwaccel failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
24212
25727
  });
25728
+ const registrations = [];
25729
+ this.ffmpegPath = await this.resolveFfmpegBinaryPath();
25730
+ this.audioProvider = new FfmpegAudioCodecProvider({
25731
+ logger: this.ctx.logger,
25732
+ ffmpegPath: this.ffmpegPath,
25733
+ resolveLocalNodeId: () => this.resolveLocalNodeId()
25734
+ });
25735
+ this.audioProvider.start();
25736
+ registrations.push({
25737
+ capability: audioCodecCapability,
25738
+ provider: this.audioProvider
25739
+ });
24213
25740
  const backend = await resolveDecoderBackend(this.ctx.api, this.resolveLocalNodeId(), this.ctx.logger);
24214
25741
  if (backend !== "ffmpeg") {
24215
- this.ctx.logger.info("ffmpeg decoder: this node selects a different decoder backend — standing down (no decoder provider registered)", { meta: { selectedBackend: backend } });
24216
- return [];
25742
+ this.ctx.logger.info("ffmpeg decoder: this node selects a different decoder backend — standing down (no decoder provider registered; audio-codec stays)", { meta: { selectedBackend: backend } });
25743
+ return registrations;
24217
25744
  }
24218
25745
  this.ctx.logger.info("ffmpeg decoder addon initialized", { meta: { selectedBackend: backend } });
25746
+ const purged = purgeOrphanSegments(SEGMENT_NAME_PREFIX);
25747
+ if (purged.removed > 0) this.ctx.logger.warn("ffmpeg decoder: reclaimed orphaned shm segments at startup", { meta: {
25748
+ removed: purged.removed,
25749
+ scanned: purged.scanned
25750
+ } });
24219
25751
  this.frameReaders = new FrameRingReaderCache(this.ctx.logger);
24220
- this.ffmpegPath = await this.resolveFfmpegBinaryPath();
24221
25752
  this.probedGpuScaleFilters = await probeGpuScaleFilters(this.ffmpegPath, this.ctx.logger);
24222
25753
  this.ctx.logger.info("decoder-ffmpeg: probed GPU scale filters", { meta: {
24223
25754
  filters: [...this.probedGpuScaleFilters],
24224
25755
  ffmpeg: this.ffmpegPath
24225
25756
  } });
24226
- return [{
25757
+ registrations.push({
24227
25758
  capability: decoderCapability,
24228
25759
  provider: this
24229
- }];
25760
+ });
25761
+ return registrations;
24230
25762
  }
24231
25763
  /**
24232
25764
  * Resolve the ffmpeg binary the sessions spawn — node-level only.
@@ -24514,6 +26046,8 @@ var DecoderFfmpegAddon = class extends BaseAddon {
24514
26046
  }
24515
26047
  async onShutdown() {
24516
26048
  this.ctx.logger.info("ffmpeg decoder addon shutdown — destroying all sessions");
26049
+ this.audioProvider?.stop();
26050
+ this.audioProvider = null;
24517
26051
  const destroyPromises = [];
24518
26052
  for (const [sessionId, session] of this.sessions) {
24519
26053
  const unsub = this.unsubscribers.get(sessionId);