@camstack/addon-benchmark 1.2.32 → 1.2.34

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 (19) hide show
  1. package/dist/{MotionZonesSettings-FXWWaTYb.mjs → MotionZonesSettings-CJQ1qIkl.mjs} +2 -2
  2. package/dist/{PrivacyMaskSettings-BpMptp4x.mjs → PrivacyMaskSettings-DqyCPYRr.mjs} +4 -4
  3. package/dist/{SceneMonitorEditor-Cf3XyH9c.mjs → SceneMonitorEditor-CN-XsRrp.mjs} +3 -3
  4. package/dist/_stub.js +13 -13
  5. package/dist/{_virtual_mf-localSharedImportMap___mfe_internal__addon_benchmark_page-NljcdjRg.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_benchmark_page-BWwUyiel.mjs} +4 -4
  6. package/dist/{_virtual_mf___mfe_internal__addon_benchmark_page__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-__ozgT-Z.mjs → _virtual_mf___mfe_internal__addon_benchmark_page__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-HpVJnRY1.mjs} +1 -1
  7. package/dist/{hostInit-bULgLWrs.mjs → hostInit-CLhuyXAy.mjs} +3 -3
  8. package/dist/index.js +800 -2
  9. package/dist/index.js.map +1 -1
  10. package/dist/index.mjs +800 -2
  11. package/dist/index.mjs.map +1 -1
  12. package/dist/{player-overlays-D5oVSKal.mjs → player-overlays-0rmH0H8O.mjs} +1 -1
  13. package/dist/remoteEntry.js +1 -1
  14. package/dist/{responsive-Cf5Bnr8W.mjs → responsive-CUJot3AN.mjs} +1 -1
  15. package/dist/{square-D6nXF0kO.mjs → square-9qrfIVAE.mjs} +1 -1
  16. package/dist/{trash-2-C-_6tBsE.mjs → trash-2-DXimPeDh.mjs} +1 -1
  17. package/dist/{use-device-snapshot-BexLgV9y.mjs → use-device-snapshot-CWhgQbX2.mjs} +1 -1
  18. package/dist/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__addon_benchmark_page__remoteEntry_js-BgULD979.mjs → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__addon_benchmark_page__remoteEntry_js-oZkDdD9C.mjs} +1 -1
  19. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -14811,6 +14811,28 @@ var SustainedThroughputResultSchema = external_exports.object({
14811
14811
  batchSize: external_exports.number(),
14812
14812
  concurrency: external_exports.number()
14813
14813
  });
14814
+ var ReplaySourceSchema = external_exports.custom();
14815
+ var ReplayOverlaySchema = external_exports.custom();
14816
+ var OrchestrateReplayRunResultSchema = external_exports.custom();
14817
+ var StoredReplayRunSchema = external_exports.custom();
14818
+ var ReplayDiffSchema = external_exports.custom();
14819
+ var RunReplayClipInputSchema = external_exports.object({
14820
+ deviceId: external_exports.number(),
14821
+ nodeId: external_exports.string(),
14822
+ source: ReplaySourceSchema,
14823
+ overlay: ReplayOverlaySchema,
14824
+ fps: external_exports.number().positive(),
14825
+ maxFrames: external_exports.number().int().positive(),
14826
+ maxWidth: external_exports.number().int().positive().default(1920),
14827
+ deviceKey: external_exports.string().optional()
14828
+ });
14829
+ var UploadReplayClipInputSchema = external_exports.object({
14830
+ dataBase64: external_exports.string(),
14831
+ durationMs: external_exports.number().positive()
14832
+ });
14833
+ var UploadReplayClipResultSchema = external_exports.object({ clipId: external_exports.string() });
14834
+ var ListReplayRunsInputSchema = external_exports.object({ deviceId: external_exports.number() });
14835
+ var DiffReplayRunsInputSchema = external_exports.object({ runIdA: external_exports.string(), runIdB: external_exports.string() });
14814
14836
 
14815
14837
  // src/benchmark-actions.ts
14816
14838
  var benchmarkActions = defineCustomActions({
@@ -14913,6 +14935,20 @@ var benchmarkActions = defineCustomActions({
14913
14935
  clearBenchmarkHistory: customAction(external_exports.object({}), external_exports.object({ success: external_exports.literal(true) }), {
14914
14936
  kind: "mutation"
14915
14937
  }),
14938
+ // Replay — rigiocare una pipeline vera su una clip fissa. Regia qui,
14939
+ // FrameProcessor pass in `addon-post-analysis` via
14940
+ // `pipelineAnalytics.runReplayFrameProcessor` (see `replay/replay-wiring.ts`).
14941
+ uploadReplayClip: customAction(UploadReplayClipInputSchema, UploadReplayClipResultSchema, {
14942
+ kind: "mutation"
14943
+ }),
14944
+ runReplayClip: customAction(RunReplayClipInputSchema, OrchestrateReplayRunResultSchema, {
14945
+ kind: "mutation"
14946
+ }),
14947
+ listReplayRuns: customAction(
14948
+ ListReplayRunsInputSchema,
14949
+ external_exports.array(StoredReplayRunSchema).readonly()
14950
+ ),
14951
+ diffReplayRuns: customAction(DiffReplayRunsInputSchema, ReplayDiffSchema),
14916
14952
  // Decoder perf — fixture discovery + run control.
14917
14953
  // `z.object({})` for the same reason as `listBenchmarkHistory` above.
14918
14954
  listDecoderFixtures: customAction(external_exports.object({}), external_exports.array(DecoderFixtureSchema).readonly()),
@@ -14926,6 +14962,9 @@ var benchmarkActions = defineCustomActions({
14926
14962
  )
14927
14963
  });
14928
14964
 
14965
+ // src/benchmark-addon.ts
14966
+ import { createHash } from "crypto";
14967
+
14929
14968
  // src/decoder-perf-runner.ts
14930
14969
  import * as fs from "fs";
14931
14970
  import * as path from "path";
@@ -15224,6 +15263,557 @@ async function runDecoderPerfTest(input, deps) {
15224
15263
  };
15225
15264
  }
15226
15265
 
15266
+ // src/replay/replay-decode.ts
15267
+ import { spawn } from "child_process";
15268
+ function buildReplaySequenceArgs(opts) {
15269
+ const { startSec, durationSec, fps, maxWidth } = opts;
15270
+ return [
15271
+ "-hide_banner",
15272
+ "-loglevel",
15273
+ "error",
15274
+ "-nostdin",
15275
+ "-ss",
15276
+ String(Math.max(0, startSec)),
15277
+ "-i",
15278
+ "pipe:0",
15279
+ "-t",
15280
+ String(Math.max(0, durationSec)),
15281
+ "-vf",
15282
+ `fps=${fps},scale='min(${maxWidth},iw)':-2`,
15283
+ "-f",
15284
+ "mjpeg",
15285
+ "pipe:1"
15286
+ ];
15287
+ }
15288
+ var REPLAY_DECODE_MAX_CONCURRENT = 2;
15289
+ var REPLAY_DECODE_TIMEOUT_MS = 15e3;
15290
+ var KILL_GRACE_MS = 500;
15291
+ var ReplayDecoder = class {
15292
+ ffmpegPath;
15293
+ spawnFn;
15294
+ maxConcurrent;
15295
+ timeoutMs;
15296
+ inFlight = 0;
15297
+ constructor(deps) {
15298
+ this.ffmpegPath = deps.ffmpegPath;
15299
+ this.spawnFn = deps.spawnFn ?? ((bin, args) => spawn(bin, [...args]));
15300
+ this.maxConcurrent = deps.maxConcurrent ?? REPLAY_DECODE_MAX_CONCURRENT;
15301
+ this.timeoutMs = deps.timeoutMs ?? REPLAY_DECODE_TIMEOUT_MS;
15302
+ }
15303
+ /** Decodes currently running (tests / metrics). */
15304
+ get running() {
15305
+ return this.inFlight;
15306
+ }
15307
+ /**
15308
+ * Run the sequence once, feeding `input` on stdin (`-i pipe:0` in
15309
+ * {@link buildReplaySequenceArgs}) — the same shape as
15310
+ * `RecordedStillService`, which pipes a GOP rather than pointing ffmpeg at
15311
+ * a file path, because the source bytes (a recorder GOP window, or an
15312
+ * uploaded clip) are fetched through a capability call, not a local path.
15313
+ * Resolves with the whole MJPEG stdout stream.
15314
+ */
15315
+ async decodeSequence(args, input) {
15316
+ if (this.inFlight >= this.maxConcurrent) {
15317
+ throw new Error(
15318
+ `replay decode busy: node already running ${this.inFlight}/${this.maxConcurrent} decodes`
15319
+ );
15320
+ }
15321
+ this.inFlight += 1;
15322
+ try {
15323
+ return await this.runOnce(args, input);
15324
+ } finally {
15325
+ this.inFlight -= 1;
15326
+ }
15327
+ }
15328
+ runOnce(args, input) {
15329
+ return new Promise((resolve2, reject) => {
15330
+ const chunks = [];
15331
+ const stderrTail = [];
15332
+ let settled = false;
15333
+ const child = (() => {
15334
+ try {
15335
+ return this.spawnFn(this.ffmpegPath, args);
15336
+ } catch (err) {
15337
+ reject(new Error(`replay decode: ffmpeg spawn failed: ${String(err)}`));
15338
+ return null;
15339
+ }
15340
+ })();
15341
+ if (child === null) return;
15342
+ const settle = (fn) => {
15343
+ if (settled) return;
15344
+ settled = true;
15345
+ clearTimeout(timer);
15346
+ fn();
15347
+ };
15348
+ const kill = () => {
15349
+ try {
15350
+ child.kill("SIGTERM");
15351
+ } catch {
15352
+ }
15353
+ const t = setTimeout(() => {
15354
+ if (child.exitCode === null && child.signalCode === null) {
15355
+ try {
15356
+ child.kill("SIGKILL");
15357
+ } catch {
15358
+ }
15359
+ }
15360
+ }, KILL_GRACE_MS);
15361
+ t.unref?.();
15362
+ };
15363
+ const timer = setTimeout(() => {
15364
+ settle(() => reject(new Error("replay decode: timed out")));
15365
+ kill();
15366
+ }, this.timeoutMs);
15367
+ timer.unref?.();
15368
+ child.stdout?.on("data", (chunk) => chunks.push(chunk));
15369
+ child.stderr?.on("data", (data) => {
15370
+ const line = data.toString().trim();
15371
+ if (line) {
15372
+ stderrTail.push(line);
15373
+ if (stderrTail.length > 8) stderrTail.shift();
15374
+ }
15375
+ });
15376
+ child.on("error", (err) => {
15377
+ settle(() => reject(new Error(`replay decode: ffmpeg process error: ${err.message}`)));
15378
+ });
15379
+ child.on("exit", (code, signal) => {
15380
+ const stdout = Buffer.concat(chunks);
15381
+ if (code === 0) {
15382
+ settle(() => resolve2(stdout));
15383
+ return;
15384
+ }
15385
+ settle(
15386
+ () => reject(
15387
+ new Error(
15388
+ `replay decode: ffmpeg exited code=${String(code)} signal=${String(signal)}: ${stderrTail.join(" | ") || "(no stderr)"}`
15389
+ )
15390
+ )
15391
+ );
15392
+ });
15393
+ try {
15394
+ child.stdin?.write(Buffer.from(input.buffer, input.byteOffset, input.byteLength));
15395
+ child.stdin?.end();
15396
+ } catch {
15397
+ }
15398
+ });
15399
+ }
15400
+ };
15401
+
15402
+ // src/replay/replay-store.ts
15403
+ var REPLAY_RUNS_COLLECTION = "benchmark:replay-runs";
15404
+ var REPLAY_RUNS_COLUMNS = [
15405
+ { name: "id", type: "TEXT", primaryKey: true, notNull: true },
15406
+ { name: "deviceId", type: "INTEGER", notNull: true },
15407
+ { name: "nodeId", type: "TEXT", notNull: true },
15408
+ { name: "clipId", type: "TEXT", notNull: true },
15409
+ { name: "createdAtMs", type: "INTEGER", notNull: true },
15410
+ { name: "source", type: "JSON", notNull: true },
15411
+ { name: "plan", type: "JSON", notNull: true },
15412
+ { name: "verdict", type: "JSON", notNull: true }
15413
+ ];
15414
+ var REPLAY_RUNS_INDEXES = [
15415
+ { name: "idx_replay_runs_device_created", columns: ["deviceId", "createdAtMs"] },
15416
+ { name: "idx_replay_runs_created", columns: ["createdAtMs"] }
15417
+ ];
15418
+ var ReplayStore = class {
15419
+ constructor(store) {
15420
+ this.store = store;
15421
+ }
15422
+ store;
15423
+ /** Declare the collection. Call in `onInitialize`, before the first
15424
+ * `save` — an undeclared collection crash-loops the runner. */
15425
+ static async declare(store) {
15426
+ await store.declareCollection.mutate({
15427
+ collection: REPLAY_RUNS_COLLECTION,
15428
+ columns: [...REPLAY_RUNS_COLUMNS],
15429
+ indexes: [...REPLAY_RUNS_INDEXES]
15430
+ });
15431
+ }
15432
+ async save(run) {
15433
+ const { id, ...rest } = run;
15434
+ await this.store.insert.mutate({
15435
+ collection: REPLAY_RUNS_COLLECTION,
15436
+ record: { id, data: rest }
15437
+ // TECH-DEBT: settings-store boundary, see the comment above.
15438
+ });
15439
+ }
15440
+ /** Runs newest-first, optionally scoped to one device. */
15441
+ async list(query) {
15442
+ const filter = { orderBy: { field: "createdAtMs", direction: "desc" } };
15443
+ if (query.deviceId !== void 0) filter.where = { deviceId: query.deviceId };
15444
+ if (query.limit !== void 0) filter.limit = query.limit;
15445
+ const rows = await this.store.query.query({ collection: REPLAY_RUNS_COLLECTION, filter });
15446
+ return rows.map((r) => ({ id: r.id, ...r.data }));
15447
+ }
15448
+ /** Delete every run created before `cutoffMs`. This store's OWN retention
15449
+ * clock — see the file header for why that matters. Returns the count so
15450
+ * a caller can log it, the way `OpsLogStore`-adjacent sweeps do. */
15451
+ async pruneBefore(cutoffMs) {
15452
+ const { deleted } = await this.store.deleteWhere.mutate({
15453
+ collection: REPLAY_RUNS_COLLECTION,
15454
+ filter: { whereBetween: { createdAtMs: [0, cutoffMs] } }
15455
+ });
15456
+ return deleted;
15457
+ }
15458
+ };
15459
+
15460
+ // src/replay/replay-plan.ts
15461
+ function readPreflight(result) {
15462
+ if (!result.ok) {
15463
+ const detail = result.issues.map((i) => `${i.addonId}: ${i.detail}`).join("; ");
15464
+ return { kind: "refused", reason: "step-unrunnable", detail };
15465
+ }
15466
+ if (result.substitutions.length > 0) {
15467
+ const detail = result.substitutions.map((s) => `${s.addonId}: chose \`${s.chosen}\`, running \`${s.running}\` (${s.format})`).join("; ");
15468
+ return { kind: "refused", reason: "model-substituted", detail };
15469
+ }
15470
+ return { kind: "runnable", format: result.format };
15471
+ }
15472
+ var PACKAGE_DETECTION_STEP_ID = "package-detection";
15473
+ function hasPackageZone(overlay) {
15474
+ return overlay.packageZone !== void 0;
15475
+ }
15476
+ function applyPackageZoneOverlay(steps, overlay) {
15477
+ const existing = steps.find((s) => s.addonId === PACKAGE_DETECTION_STEP_ID);
15478
+ if (!hasPackageZone(overlay)) {
15479
+ if (!existing) return steps;
15480
+ return steps.filter((s) => s.addonId !== PACKAGE_DETECTION_STEP_ID);
15481
+ }
15482
+ if (existing) {
15483
+ if (existing.enabled === true) return steps;
15484
+ return steps.map((s) => s.addonId === PACKAGE_DETECTION_STEP_ID ? { ...s, enabled: true } : s);
15485
+ }
15486
+ const node = {
15487
+ addonId: PACKAGE_DETECTION_STEP_ID,
15488
+ enabled: true,
15489
+ children: []
15490
+ };
15491
+ return [...steps, node];
15492
+ }
15493
+ function applySettingsAndModels(steps, overlay, ignored) {
15494
+ const settingsKeys = new Set(Object.keys(overlay.stepSettings ?? {}));
15495
+ const modelKeys = new Set(Object.keys(overlay.stepModels ?? {}));
15496
+ const presentIds = new Set(steps.map((s) => s.addonId));
15497
+ for (const id of settingsKeys) if (!presentIds.has(id)) ignored.add(id);
15498
+ for (const id of modelKeys) if (!presentIds.has(id)) ignored.add(id);
15499
+ return steps.map((s) => {
15500
+ const settingsPatch = overlay.stepSettings?.[s.addonId];
15501
+ const modelOverride = overlay.stepModels?.[s.addonId];
15502
+ if (settingsPatch === void 0 && modelOverride === void 0) return s;
15503
+ return {
15504
+ ...s,
15505
+ ...modelOverride !== void 0 ? { modelId: modelOverride } : {},
15506
+ ...settingsPatch !== void 0 ? { settings: { ...s.settings, ...settingsPatch } } : {}
15507
+ };
15508
+ });
15509
+ }
15510
+ function buildReplayPlan(base, overlay) {
15511
+ const ignored = /* @__PURE__ */ new Set();
15512
+ const withPackageZone = applyPackageZoneOverlay(base.steps, overlay);
15513
+ if (!hasPackageZone(overlay) && (overlay.stepSettings?.[PACKAGE_DETECTION_STEP_ID] !== void 0 || overlay.stepModels?.[PACKAGE_DETECTION_STEP_ID] !== void 0)) {
15514
+ ignored.add(PACKAGE_DETECTION_STEP_ID);
15515
+ }
15516
+ const steps = applySettingsAndModels(withPackageZone, overlay, ignored);
15517
+ return { steps, ignoredOverlays: [...ignored] };
15518
+ }
15519
+
15520
+ // src/replay/replay-source.ts
15521
+ function planReplayFrames(source, fps, maxFrames) {
15522
+ const durationMs = source.kind === "recording" ? source.toMs - source.fromMs : source.durationMs;
15523
+ if (durationMs <= 0) return { kind: "refused", reason: "empty-window" };
15524
+ const stepMs = 1e3 / fps;
15525
+ const startAt = source.kind === "recording" ? source.fromMs : 0;
15526
+ const rawCount = Math.max(1, Math.floor(durationMs / stepMs));
15527
+ const truncated = rawCount > maxFrames;
15528
+ const count = Math.min(rawCount, maxFrames);
15529
+ const instants = [];
15530
+ for (let i = 0; i < count; i++) instants.push(startAt + Math.round(i * stepMs));
15531
+ return { kind: "planned", deviceId: source.deviceId, instants, truncated };
15532
+ }
15533
+
15534
+ // src/replay/mjpeg-split.ts
15535
+ var SOI = Buffer.from([255, 216]);
15536
+ var EOI = Buffer.from([255, 217]);
15537
+ function splitMjpegStream(bytes) {
15538
+ const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
15539
+ const out = [];
15540
+ let pos = 0;
15541
+ for (; ; ) {
15542
+ const soi = buf.indexOf(SOI, pos);
15543
+ if (soi === -1) break;
15544
+ const eoi = buf.indexOf(EOI, soi + SOI.length);
15545
+ if (eoi === -1) break;
15546
+ out.push(buf.subarray(soi, eoi + EOI.length));
15547
+ pos = eoi + EOI.length;
15548
+ }
15549
+ return out;
15550
+ }
15551
+
15552
+ // src/replay/replay-run.ts
15553
+ var DEFAULT_REPLAY_BUDGET_MS = 12e4;
15554
+ var DEFAULT_REPLAY_PACING_MS = 50;
15555
+ function sleep(ms) {
15556
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
15557
+ }
15558
+ async function runReplay(deps, frames) {
15559
+ const now = deps.now ?? Date.now;
15560
+ const budgetMs = deps.budgetMs ?? DEFAULT_REPLAY_BUDGET_MS;
15561
+ const pacingMs = deps.pacingMs ?? DEFAULT_REPLAY_PACING_MS;
15562
+ const startedAt = now();
15563
+ const tags = { deviceId: deps.deviceId };
15564
+ deps.logger.info("replay: run starting", {
15565
+ tags,
15566
+ meta: { framesPlanned: frames.length, nodeId: deps.nodeId, pacingMs, budgetMs }
15567
+ });
15568
+ const succeeded = [];
15569
+ const discarded = [];
15570
+ let framesFailed = 0;
15571
+ let stoppedOnBudget = false;
15572
+ for (let i = 0; i < frames.length; i++) {
15573
+ if (now() - startedAt >= budgetMs) {
15574
+ stoppedOnBudget = true;
15575
+ deps.logger.warn("replay: run stopped on budget \u2014 a partial census, reported as such", {
15576
+ tags,
15577
+ meta: {
15578
+ framesPlanned: frames.length,
15579
+ framesRan: succeeded.length,
15580
+ framesFailed,
15581
+ budgetMs
15582
+ }
15583
+ });
15584
+ break;
15585
+ }
15586
+ const f = frames[i];
15587
+ if (f === void 0) continue;
15588
+ try {
15589
+ const frame = await deps.runPipeline({
15590
+ timestamp: f.timestamp,
15591
+ image: f.image,
15592
+ nodeId: deps.nodeId
15593
+ });
15594
+ succeeded.push({ timestamp: f.timestamp, frame });
15595
+ if (frame.discarded !== void 0) discarded.push(...frame.discarded);
15596
+ } catch (err) {
15597
+ framesFailed += 1;
15598
+ deps.logger.warn("replay: frame failed on the node \u2014 counted, run continues", {
15599
+ tags,
15600
+ meta: { timestamp: f.timestamp, error: err instanceof Error ? err.message : String(err) }
15601
+ });
15602
+ }
15603
+ if (pacingMs > 0 && i < frames.length - 1) await sleep(pacingMs);
15604
+ }
15605
+ const tracks = succeeded.length > 0 ? (await deps.runTracking(succeeded)).tracks : [];
15606
+ const complete = !stoppedOnBudget && framesFailed === 0;
15607
+ deps.logger.info("replay: run finished", {
15608
+ tags,
15609
+ meta: {
15610
+ framesPlanned: frames.length,
15611
+ framesRan: succeeded.length,
15612
+ framesFailed,
15613
+ complete,
15614
+ tracks: tracks.length
15615
+ }
15616
+ });
15617
+ return {
15618
+ kind: succeeded.length === 0 ? "no-frame-ran" : "ran",
15619
+ deviceId: deps.deviceId,
15620
+ nodeId: deps.nodeId,
15621
+ complete,
15622
+ tracks,
15623
+ discarded,
15624
+ counters: { framesPlanned: frames.length, framesRan: succeeded.length, framesFailed }
15625
+ };
15626
+ }
15627
+
15628
+ // src/replay/replay-wiring.ts
15629
+ function clipIdOf(source) {
15630
+ return source.kind === "upload" ? source.clipId : `recording:${source.deviceId}:${source.fromMs}`;
15631
+ }
15632
+ async function orchestrateReplayRun(deps, input) {
15633
+ const tags = { deviceId: input.deviceId };
15634
+ const base = await deps.resolveBaseTree(input.deviceId);
15635
+ const plan = buildReplayPlan(base, input.overlay);
15636
+ if (plan.ignoredOverlays.length > 0) {
15637
+ deps.logger.warn("replay: overlay named a step the resolved tree does not run", {
15638
+ tags,
15639
+ meta: { ignoredOverlays: plan.ignoredOverlays }
15640
+ });
15641
+ }
15642
+ const preflight = await deps.api.pipelineExecutor.validatePipeline.query({
15643
+ steps: [...plan.steps]
15644
+ });
15645
+ const preflightVerdict = readPreflight(preflight);
15646
+ if (preflightVerdict.kind === "refused") {
15647
+ deps.logger.warn("replay: run refused at preflight", {
15648
+ tags,
15649
+ meta: { reason: preflightVerdict.reason, detail: preflightVerdict.detail }
15650
+ });
15651
+ return { kind: "refused", reason: `${preflightVerdict.reason}: ${preflightVerdict.detail}` };
15652
+ }
15653
+ const framePlan = planReplayFrames(input.source, input.fps, input.maxFrames);
15654
+ if (framePlan.kind === "refused") {
15655
+ deps.logger.warn("replay: run refused \u2014 empty window", { tags });
15656
+ return { kind: "refused", reason: framePlan.reason };
15657
+ }
15658
+ if (framePlan.truncated) {
15659
+ deps.logger.warn("replay: frame plan truncated by maxFrames", {
15660
+ tags,
15661
+ meta: { maxFrames: input.maxFrames, planned: framePlan.instants.length }
15662
+ });
15663
+ }
15664
+ const sourceFetch = await deps.fetchSourceBytes(input.source);
15665
+ if (sourceFetch.kind === "refused") {
15666
+ deps.logger.warn("replay: run refused \u2014 could not fetch source bytes", {
15667
+ tags,
15668
+ meta: { reason: sourceFetch.reason }
15669
+ });
15670
+ return { kind: "refused", reason: sourceFetch.reason };
15671
+ }
15672
+ const sourceBytes = sourceFetch.bytes;
15673
+ const first = framePlan.instants[0] ?? 0;
15674
+ const last = framePlan.instants[framePlan.instants.length - 1] ?? first;
15675
+ const startSec = (first - sourceFetch.startMs) / 1e3;
15676
+ const durationSec = Math.max(1 / input.fps, (last - first) / 1e3 + 1 / input.fps);
15677
+ const args = buildReplaySequenceArgs({
15678
+ startSec,
15679
+ durationSec,
15680
+ fps: input.fps,
15681
+ maxWidth: input.maxWidth
15682
+ });
15683
+ const mjpeg = await deps.decoder.decodeSequence(args, sourceBytes);
15684
+ const jpegFrames = splitMjpegStream(mjpeg);
15685
+ const frames = [];
15686
+ for (let i = 0; i < framePlan.instants.length; i++) {
15687
+ const timestamp = framePlan.instants[i];
15688
+ const image = jpegFrames[i];
15689
+ if (timestamp === void 0 || image === void 0) continue;
15690
+ frames.push({ timestamp, image });
15691
+ }
15692
+ if (frames.length < framePlan.instants.length) {
15693
+ deps.logger.warn("replay: decode produced fewer frames than planned", {
15694
+ tags,
15695
+ meta: { planned: framePlan.instants.length, decoded: frames.length }
15696
+ });
15697
+ }
15698
+ const verdict = await runReplay(
15699
+ {
15700
+ deviceId: input.deviceId,
15701
+ nodeId: input.nodeId,
15702
+ runPipeline: async (call) => deps.api.pipelineExecutor.runPipeline.mutate({
15703
+ nodeId: call.nodeId,
15704
+ steps: [...plan.steps],
15705
+ // Copy into a fresh `Uint8Array<ArrayBuffer>` — `mjpeg-split.ts`
15706
+ // hands back a `Buffer` view (`Uint8Array<ArrayBufferLike>`), and
15707
+ // the generated cap input is typed against the narrower
15708
+ // `ArrayBuffer` backing.
15709
+ image: new Uint8Array(call.image),
15710
+ deviceId: input.deviceId,
15711
+ ...input.deviceKey !== void 0 ? { deviceKey: input.deviceKey } : {}
15712
+ }),
15713
+ // THE cross-addon call this whole track exists for: the FrameProcessor
15714
+ // pass lives in `addon-post-analysis`, reached only through this cap
15715
+ // method — see the file header.
15716
+ runTracking: async (tracked) => deps.api.pipelineAnalytics.runReplayFrameProcessor.mutate({
15717
+ deviceId: input.deviceId,
15718
+ source: "pipeline",
15719
+ frames: [...tracked]
15720
+ }),
15721
+ logger: deps.logger
15722
+ },
15723
+ frames
15724
+ );
15725
+ const now = deps.now ?? Date.now;
15726
+ const newId = deps.newId ?? (() => `replay-${now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`);
15727
+ const replayRunId = newId();
15728
+ const record2 = {
15729
+ id: replayRunId,
15730
+ deviceId: input.deviceId,
15731
+ nodeId: input.nodeId,
15732
+ clipId: clipIdOf(input.source),
15733
+ createdAtMs: now(),
15734
+ source: input.source,
15735
+ plan,
15736
+ verdict
15737
+ };
15738
+ await deps.store.save(record2);
15739
+ return { kind: "ran", replayRunId, verdict };
15740
+ }
15741
+
15742
+ // src/replay/replay-diff.ts
15743
+ function iou(a, b) {
15744
+ const x1 = Math.max(a.x, b.x);
15745
+ const y1 = Math.max(a.y, b.y);
15746
+ const x2 = Math.min(a.x + a.w, b.x + b.w);
15747
+ const y2 = Math.min(a.y + a.h, b.y + b.h);
15748
+ const interW = Math.max(0, x2 - x1);
15749
+ const interH = Math.max(0, y2 - y1);
15750
+ const inter = interW * interH;
15751
+ if (inter <= 0) return 0;
15752
+ const union2 = a.w * a.h + b.w * b.h - inter;
15753
+ return union2 <= 0 ? 0 : inter / union2;
15754
+ }
15755
+ function windowsOverlap(a, b) {
15756
+ return a.firstSeenMs <= b.lastSeenMs && b.firstSeenMs <= a.lastSeenMs;
15757
+ }
15758
+ var TRACK_PAIR_MIN_IOU = 0.3;
15759
+ function diffTracks(a, b) {
15760
+ const bMatched = /* @__PURE__ */ new Set();
15761
+ const lost = [];
15762
+ for (const ta of a) {
15763
+ let bestIdx = -1;
15764
+ let bestIou = 0;
15765
+ for (let i = 0; i < b.length; i++) {
15766
+ if (bMatched.has(i)) continue;
15767
+ const tb = b[i];
15768
+ if (tb === void 0 || tb.className !== ta.className) continue;
15769
+ if (!windowsOverlap(ta, tb)) continue;
15770
+ const score = iou(ta.bbox, tb.bbox);
15771
+ if (score >= TRACK_PAIR_MIN_IOU && score > bestIou) {
15772
+ bestIou = score;
15773
+ bestIdx = i;
15774
+ }
15775
+ }
15776
+ if (bestIdx === -1) lost.push(ta);
15777
+ else bMatched.add(bestIdx);
15778
+ }
15779
+ const gained = b.filter((_, i) => !bMatched.has(i));
15780
+ return { gained, lost };
15781
+ }
15782
+ function diffKnobs(a, b) {
15783
+ const stepIds = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
15784
+ const changed = [];
15785
+ for (const stepId of stepIds) {
15786
+ const aStep = a[stepId] ?? {};
15787
+ const bStep = b[stepId] ?? {};
15788
+ const keys = /* @__PURE__ */ new Set([...Object.keys(aStep), ...Object.keys(bStep)]);
15789
+ for (const key of keys) {
15790
+ const from = aStep[key];
15791
+ const to = bStep[key];
15792
+ if (from !== to) changed.push({ stepId, key, from, to });
15793
+ }
15794
+ }
15795
+ return changed;
15796
+ }
15797
+ function diffPromoted(discardedA, tracksB) {
15798
+ const promoted = [];
15799
+ for (const d of discardedA) {
15800
+ const nowTracked = tracksB.some((t) => t.className === d.macroClass);
15801
+ if (nowTracked)
15802
+ promoted.push({ macroClass: d.macroClass, score: d.score, wasDiscardedBy: d.reason });
15803
+ }
15804
+ return promoted;
15805
+ }
15806
+ function diffReplayRuns(a, b) {
15807
+ if (a.clipId !== b.clipId) return { kind: "incomparable", reason: "different-input" };
15808
+ if (a.nodeId !== b.nodeId) return { kind: "incomparable", reason: "different-node" };
15809
+ return {
15810
+ kind: "compared",
15811
+ changedKnobs: diffKnobs(a.settings, b.settings),
15812
+ tracks: diffTracks(a.tracks, b.tracks),
15813
+ promoted: diffPromoted(a.discarded, b.tracks)
15814
+ };
15815
+ }
15816
+
15227
15817
  // src/throughput/sustained-runner.ts
15228
15818
  async function runSustainedLoop(opts) {
15229
15819
  const concurrency = Math.max(1, Math.floor(opts.concurrency));
@@ -15351,7 +15941,7 @@ function resolveFixturesDir() {
15351
15941
  const pkgRoot = path2.resolve(path2.dirname(here), "..");
15352
15942
  return path2.join(pkgRoot, "assets", "fixtures");
15353
15943
  }
15354
- var BenchmarkAddon = class extends BaseAddon {
15944
+ var BenchmarkAddon = class _BenchmarkAddon extends BaseAddon {
15355
15945
  id = "benchmark";
15356
15946
  /** Per-sessionId abort flags for in-flight decoder perf runs. */
15357
15947
  decoderPerfAbortFlags = /* @__PURE__ */ new Map();
@@ -15372,6 +15962,17 @@ var BenchmarkAddon = class extends BaseAddon {
15372
15962
  frameCache = /* @__PURE__ */ new Map();
15373
15963
  /** Periodic GC handle — clears expired frames every 60s. */
15374
15964
  frameCacheSweeper = null;
15965
+ /** The replay run collection — declared in `onInitialize`, before any
15966
+ * `runReplayClip` call can save into it. See `replay/replay-store.ts`. */
15967
+ replayStore = null;
15968
+ /** The replay's one ffmpeg spawn, bounded — see `replay/replay-decode.ts`. */
15969
+ replayDecoder = new ReplayDecoder({
15970
+ ffmpegPath: process.env["FFMPEG_PATH"] ?? "ffmpeg"
15971
+ });
15972
+ /** `replay:<StoredReplayRun>` — an in-memory index would drift from the
15973
+ * store; this is a thin cache over `replayStore.list`, keyed for the
15974
+ * diff action's two-id lookup. */
15975
+ replayRunCache = /* @__PURE__ */ new Map();
15375
15976
  pages = [
15376
15977
  {
15377
15978
  id: "benchmark",
@@ -15392,6 +15993,8 @@ var BenchmarkAddon = class extends BaseAddon {
15392
15993
  id: this.id,
15393
15994
  listPages: () => this.pages
15394
15995
  };
15996
+ await ReplayStore.declare(this.api.settingsStore);
15997
+ this.replayStore = new ReplayStore(this.api.settingsStore);
15395
15998
  return {
15396
15999
  providers: [{ capability: addonPagesSourceCapability, provider }],
15397
16000
  customActions: benchmarkActions,
@@ -15410,7 +16013,11 @@ var BenchmarkAddon = class extends BaseAddon {
15410
16013
  clearBenchmarkHistory: async () => this.clearBenchmarkHistory(),
15411
16014
  listDecoderFixtures: async () => this.listDecoderFixtures(),
15412
16015
  runDecoderPerformanceTest: async (input) => this.runDecoderPerformanceTest(input),
15413
- abortDecoderPerformanceTest: async (input) => this.abortDecoderPerformanceTest(input)
16016
+ abortDecoderPerformanceTest: async (input) => this.abortDecoderPerformanceTest(input),
16017
+ uploadReplayClip: async (input) => this.uploadReplayClip(input),
16018
+ runReplayClip: async (input) => this.runReplayClip(input),
16019
+ listReplayRuns: async (input) => this.listReplayRuns(input),
16020
+ diffReplayRuns: async (input) => this.diffReplayRunsAction(input)
15414
16021
  }
15415
16022
  };
15416
16023
  }
@@ -15513,6 +16120,197 @@ var BenchmarkAddon = class extends BaseAddon {
15513
16120
  "runPipelineTest"
15514
16121
  );
15515
16122
  }
16123
+ // ── Replay ────────────────────────────────────────────────────────────
16124
+ /**
16125
+ * Storage location a replay upload lands on. `replayClips` is a NEW
16126
+ * `StorageLocationType` (an open string, no schema change needed — see
16127
+ * `storage-location.ts:19`) but it still needs an actual location
16128
+ * REGISTERED for that type before `storage.write`/`.read` can resolve it
16129
+ * (`storage.upsertLocation`, `cardinality: 'single'`, its own retention).
16130
+ * That registration is an operator/boot-time provisioning step this
16131
+ * change does not perform — see the report's open items.
16132
+ */
16133
+ static REPLAY_CLIPS_LOCATION = "replayClips";
16134
+ async uploadReplayClip(input) {
16135
+ const bytes = Buffer.from(input.dataBase64, "base64");
16136
+ const clipId = `clip:${createHash("sha256").update(bytes).digest("hex").slice(0, 32)}`;
16137
+ await this.api.storage.write.mutate({
16138
+ location: _BenchmarkAddon.REPLAY_CLIPS_LOCATION,
16139
+ relativePath: `${clipId}.bin`,
16140
+ data: new Uint8Array(bytes)
16141
+ });
16142
+ this.ctx.logger.info("replay: clip uploaded", { meta: { clipId, bytes: bytes.length } });
16143
+ return { clipId };
16144
+ }
16145
+ async runReplayClip(input) {
16146
+ if (this.replayStore === null) throw new Error("replay: store not initialized");
16147
+ const store = this.replayStore;
16148
+ const source = input.source;
16149
+ const result = await orchestrateReplayRun(
16150
+ {
16151
+ api: this.api,
16152
+ logger: this.ctx.logger,
16153
+ decoder: this.replayDecoder,
16154
+ store,
16155
+ ffmpegPath: process.env["FFMPEG_PATH"] ?? "ffmpeg",
16156
+ resolveBaseTree: (deviceId) => this.api.pipelineOrchestrator.resolvePipeline.query({ deviceId }),
16157
+ fetchSourceBytes: (src) => this.fetchReplaySourceBytes(src)
16158
+ },
16159
+ {
16160
+ deviceId: input.deviceId,
16161
+ nodeId: input.nodeId,
16162
+ source,
16163
+ overlay: input.overlay,
16164
+ fps: input.fps,
16165
+ maxFrames: input.maxFrames,
16166
+ maxWidth: input.maxWidth,
16167
+ ...input.deviceKey !== void 0 ? { deviceKey: input.deviceKey } : {}
16168
+ }
16169
+ );
16170
+ if (result.kind === "ran")
16171
+ this.replayRunCache.set(result.replayRunId, {
16172
+ id: result.replayRunId,
16173
+ deviceId: input.deviceId,
16174
+ nodeId: input.nodeId,
16175
+ clipId: source.kind === "upload" ? source.clipId : `recording:${source.deviceId}:${source.fromMs}`,
16176
+ createdAtMs: Date.now(),
16177
+ source,
16178
+ plan: null,
16179
+ verdict: result.verdict
16180
+ });
16181
+ return result;
16182
+ }
16183
+ /**
16184
+ * The profile a replay window is read from. `high` — same choice
16185
+ * `RECORDED_STILL_PROFILE` makes in `addon-post-analysis` — because the
16186
+ * whole point of `recording` over `upload` is NATIVE pixels (`-c:v copy`
16187
+ * means the recorded frame IS the live frame); a window cut from a
16188
+ * lower-rate rendition would be a worse version of the thing this source
16189
+ * exists to avoid.
16190
+ */
16191
+ static REPLAY_RECORDING_PROFILE = "high";
16192
+ /**
16193
+ * Byte source for the replay decode step.
16194
+ *
16195
+ * `upload` is `storage.read` against the `replayClips` location. `recording`
16196
+ * is `recording.getDeviceConfig` → `recording.locateSegment` →
16197
+ * `recording.readWindowBytes` — the same "cheap question first" ordering
16198
+ * `RecordedStillService` uses (a camera that is not recording costs a
16199
+ * settings read, never a disk read), through `ctx.api` because addons never
16200
+ * import each other.
16201
+ *
16202
+ * Every expected failure — not recording, no footage covering `fromMs`, a
16203
+ * window that runs past its covering segment — returns a NAMED `refused`,
16204
+ * never a thrown error: "the window has no segments" is a RESULT this
16205
+ * whole feature exists to make legible (see the plan's stated unknown about
16206
+ * whether device 615's footage covers 2026-08-26 18:12), not a failure to
16207
+ * hide behind a generic exception.
16208
+ */
16209
+ async fetchReplaySourceBytes(source) {
16210
+ if (source.kind === "upload") {
16211
+ try {
16212
+ const bytes = await this.api.storage.read.query({
16213
+ location: _BenchmarkAddon.REPLAY_CLIPS_LOCATION,
16214
+ relativePath: `${source.clipId}.bin`
16215
+ });
16216
+ return { kind: "ok", bytes, startMs: 0 };
16217
+ } catch (err) {
16218
+ return { kind: "refused", reason: `clip-not-found: ${errMsg(err)}` };
16219
+ }
16220
+ }
16221
+ const profile = _BenchmarkAddon.REPLAY_RECORDING_PROFILE;
16222
+ const tags = { deviceId: source.deviceId };
16223
+ const config2 = await this.api.recording.getDeviceConfig.query({ deviceId: source.deviceId });
16224
+ if (config2.enabled === false) {
16225
+ this.ctx.logger.warn("replay: recording source refused \u2014 camera is not recording", {
16226
+ tags
16227
+ });
16228
+ return {
16229
+ kind: "refused",
16230
+ reason: `no-recording: device ${source.deviceId} does not have recording enabled`
16231
+ };
16232
+ }
16233
+ const located = await this.api.recording.locateSegment.query({
16234
+ deviceId: source.deviceId,
16235
+ profile,
16236
+ epochMs: source.fromMs
16237
+ });
16238
+ if (located.kind !== "segment") {
16239
+ this.ctx.logger.warn(
16240
+ "replay: recording source refused \u2014 no footage covers the window start",
16241
+ { tags, meta: { fromMs: source.fromMs, toMs: source.toMs, profile } }
16242
+ );
16243
+ return {
16244
+ kind: "refused",
16245
+ reason: `no-footage: device ${source.deviceId} has no ${profile} recording covering ${new Date(source.fromMs).toISOString()}`
16246
+ };
16247
+ }
16248
+ const window = await this.api.recording.readWindowBytes.query({
16249
+ deviceId: source.deviceId,
16250
+ profile,
16251
+ startMs: located.startMs,
16252
+ fromMs: source.fromMs,
16253
+ toMs: source.toMs
16254
+ });
16255
+ if (window.kind !== "ok") {
16256
+ this.ctx.logger.warn(
16257
+ "replay: recording source refused \u2014 window runs past the covering segment",
16258
+ {
16259
+ tags,
16260
+ meta: { fromMs: source.fromMs, toMs: source.toMs, segmentEndMs: window.segmentEndMs }
16261
+ }
16262
+ );
16263
+ return {
16264
+ kind: "refused",
16265
+ reason: `window-spans-multiple-segments: footage for device ${source.deviceId} changes segment at ${window.segmentEndMs}, before the requested end ${source.toMs} \u2014 shorten the window or align it to one segment`
16266
+ };
16267
+ }
16268
+ if (!window.reachesRequestedEnd) {
16269
+ this.ctx.logger.warn(
16270
+ "replay: recording window bytes truncated by the recorder read safety cap",
16271
+ { tags, meta: { fromMs: source.fromMs, toMs: source.toMs, gopDurMs: window.gopDurMs } }
16272
+ );
16273
+ }
16274
+ return { kind: "ok", bytes: window.data, startMs: window.gopStartMs };
16275
+ }
16276
+ async listReplayRuns(input) {
16277
+ if (this.replayStore === null) return [];
16278
+ const rows = await this.replayStore.list({ deviceId: input.deviceId });
16279
+ for (const row of rows) this.replayRunCache.set(row.id, row);
16280
+ return rows;
16281
+ }
16282
+ /** `verdict` round-trips through the store as opaque JSON
16283
+ * (`StoredReplayRun.verdict: unknown`) — this is the ONE narrowing back
16284
+ * to the shape `diffReplayRuns` needs, at the ONE place that reads it
16285
+ * for that purpose. Same documented boundary `ReplayStore.list` itself
16286
+ * crosses (`replay-store.ts`): this addon is the only reader that knows
16287
+ * what it wrote. */
16288
+ static verdictTracksAndDiscarded(verdict) {
16289
+ return verdict;
16290
+ }
16291
+ async diffReplayRunsAction(input) {
16292
+ const a = this.replayRunCache.get(input.runIdA);
16293
+ const b = this.replayRunCache.get(input.runIdB);
16294
+ if (a === void 0 || b === void 0) {
16295
+ throw new Error(
16296
+ "replay: diff \u2014 one or both run ids are not loaded (call listReplayRuns first)"
16297
+ );
16298
+ }
16299
+ return diffReplayRuns(
16300
+ {
16301
+ clipId: a.clipId,
16302
+ nodeId: a.nodeId,
16303
+ settings: {},
16304
+ ..._BenchmarkAddon.verdictTracksAndDiscarded(a.verdict)
16305
+ },
16306
+ {
16307
+ clipId: b.clipId,
16308
+ nodeId: b.nodeId,
16309
+ settings: {},
16310
+ ..._BenchmarkAddon.verdictTracksAndDiscarded(b.verdict)
16311
+ }
16312
+ );
16313
+ }
15516
16314
  /**
15517
16315
  * Batched pipeline tester.
15518
16316
  *