@camstack/addon-provider-reolink 1.2.147 → 1.2.149

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/addon.js +925 -59
  2. package/dist/addon.mjs +925 -59
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -5385,7 +5385,7 @@ var ZodIssueCode = {
5385
5385
  var ZodFirstPartyTypeKind;
5386
5386
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5387
5387
  //#endregion
5388
- //#region ../types/dist/sleep-CaB_hL5g.mjs
5388
+ //#region ../types/dist/sleep-BVhJDJka.mjs
5389
5389
  /**
5390
5390
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5391
5391
  * window to float samples (D455).
@@ -6956,6 +6956,18 @@ function systemMethod(input, output, options) {
6956
6956
  systemOnly: true
6957
6957
  };
6958
6958
  }
6959
+ /**
6960
+ * A method a SOURCE of a collection cap may legitimately not serve — OPTIONAL
6961
+ * on `InferProvider`. The `providerOptional: true` literal is what
6962
+ * `InferProvider` keys on; see {@link CapabilityMethodSchema.providerOptional}
6963
+ * for when this is the honest answer and when it is a soft stub.
6964
+ */
6965
+ function optionalMethod(input, output, options) {
6966
+ return {
6967
+ ...method(input, output, options),
6968
+ providerOptional: true
6969
+ };
6970
+ }
6959
6971
  /** Shorthand to define an event schema */
6960
6972
  function event(data) {
6961
6973
  return { data };
@@ -25341,6 +25353,77 @@ var ClipPlaybackSchema = object({
25341
25353
  * which days it asked for and got nothing — "no clips" would be a lie about a
25342
25354
  * card that is full of them.
25343
25355
  */
25356
+ /**
25357
+ * The operator's authorisation to WAKE a sleeping camera for one clip read.
25358
+ *
25359
+ * ONE value, absent by default, and it is a `force`-shaped operator signal in
25360
+ * exactly the sense `snapshot-wake-gate.ts` uses the word: *"`snapshot.getSnapshot`'s
25361
+ * `force` flag, and nothing else… a background caller must never set it…
25362
+ * Stale but honest beats woken"*. A scheduler, a retry, a reconcile and a
25363
+ * prefetch never set it; a surface sets it only behind the same confirm the
25364
+ * "Wake and refresh" gesture uses, and it is refused below 15 % battery
25365
+ * exactly as that gesture is.
25366
+ *
25367
+ * The gate is decided BEFORE `getApi()`, because on UDP the login IS the wake
25368
+ * (D549) — a read that opened a session and then checked would have woken the
25369
+ * camera to find out it was not allowed to.
25370
+ *
25371
+ * **One authorised yes is one wake.** `next-natural` — take the clip the next
25372
+ * time the camera is awake for its own reasons — is deliberately not a member:
25373
+ * it was proposed, it is free on the battery, and the operator declined it on
25374
+ * 2026-09-20 (*"Quando un export viene richiesto si sveglia la camera."*,
25375
+ * D558 "Considered and not taken").
25376
+ */
25377
+ var ClipWakeSchema = _enum(["authorised"]);
25378
+ /**
25379
+ * Hard ceiling on ONE {@link videoclipsCapability.methods.readClipBytes} — the
25380
+ * same 50 MiB `RECORDING_EXPORT_MAX_READ_BYTES` uses, and for the same second
25381
+ * reason: the envelope is unary, so a base64 payload is held whole (~1.33× its
25382
+ * size) in the provider AND in the caller, on a hub this repo has already
25383
+ * OOM'd once (D9/D18).
25384
+ *
25385
+ * Measured clips sit far below it — 92 KB–2.29 MB for a sub twin, 455 KB for a
25386
+ * 16 s main clip — so the bound bites rarely. "Rarely" is not "never": a long
25387
+ * 4K main twin can exceed it, and above the bound the provider REFUSES with
25388
+ * the size in the message, never truncates. Half a video is worse than an
25389
+ * honest refusal.
25390
+ *
25391
+ * The clean follow-on is a CHUNKED read so a `high` twin of a long clip stops
25392
+ * being refusable at all. That is a later slice, named here so the bound is
25393
+ * not mistaken for a design ceiling.
25394
+ */
25395
+ var VIDEOCLIPS_MAX_READ_BYTES = 50 * 1024 * 1024;
25396
+ /**
25397
+ * A clip's finished bytes, inline — the twin of `recordingExport.readExportBytes`.
25398
+ *
25399
+ * `bytes` is the DECODED length, so nobody infers it from the base64 length,
25400
+ * and `served` says which twin the caller actually got.
25401
+ */
25402
+ var ClipBytesSchema = object({
25403
+ base64: string(),
25404
+ contentType: string(),
25405
+ /** Suggested filename, extension included. */
25406
+ name: string(),
25407
+ bytes: number().int().nonnegative(),
25408
+ /**
25409
+ * Which twin was actually served — the same contract
25410
+ * {@link ClipPlaybackSchema.served} carries, and REQUIRED here because the
25411
+ * export record persists it: a row read a week later must say the same thing
25412
+ * the panel said at the moment of the tap. A missing main twin is never
25413
+ * served silently as if it were the asked-for quality (D549 15).
25414
+ */
25415
+ served: CamProfileSchema,
25416
+ /**
25417
+ * The DECODED duration of the delivered file, when the fetch measured one.
25418
+ *
25419
+ * A clip fetch verifies its own completion against the catalog row and
25420
+ * retries a materially short pass (D568); this is that measurement, carried
25421
+ * so a consumer can say the same thing rather than re-deriving it. Absent
25422
+ * when the producer did not measure — never zero, which would say the file
25423
+ * is empty.
25424
+ */
25425
+ durationMs: number().positive().optional()
25426
+ });
25344
25427
  var ClipSourceAvailabilitySchema = object({
25345
25428
  state: _enum([
25346
25429
  "ok",
@@ -25442,22 +25525,40 @@ var videoclipsCapability = {
25442
25525
  limit: number().int().positive().optional(),
25443
25526
  /**
25444
25527
  * WHICH provider to ask — the `addonId` a {@link ClipSourceSchema} row
25445
- * carries, never a source id and never a list.
25528
+ * carries, never a source id and never a list. **Required** (D554 amended).
25529
+ *
25530
+ * A provider the device is not bound to is refused by name rather than
25531
+ * answered by another one (D552's `rejectUnresolvedAddonPin` rule).
25532
+ *
25533
+ * It was optional, documented as "absent means the device's BOUND
25534
+ * provider, which is CamStack on every camera". No code implemented
25535
+ * that. Measured on the live hub 2026-09-20 — device 592, bound to
25536
+ * `recorder` AND `provider-reolink` — a bare call with `limit: 3`
25537
+ * answered SIX rows, three from each source, merged newest-first:
25538
+ * `device-collection-dispatch.ts` simply left the fan-out un-narrowed,
25539
+ * so absence bought the union this method exists not to be, and
25540
+ * `limit` meant `limit × sources`.
25446
25541
  *
25447
- * Absent means the device's BOUND provider, which is CamStack on every
25448
- * camera today because that is what `deviceManager.getBindings`
25449
- * answers with. A provider the device is not bound to is refused by
25450
- * name rather than answered by another one (D552's
25451
- * `rejectUnresolvedAddonPin` rule).
25542
+ * There is nothing to restore the default to. `getBindings` answers a
25543
+ * collection cap with a DERIVED, PLURAL set (D554 amended, step 0);
25544
+ * `setWrapperActive` — the singleton authority that could name one —
25545
+ * throws for a collection cap by design. Naming CamStack here instead
25546
+ * would privilege one addon by id inside a surface whose premise is
25547
+ * that sources are peers, and would be wrong on the first camera with
25548
+ * no recorder binding. So absence is REFUSED, in the schema, where the
25549
+ * generated types make it unomittable rather than merely discouraged.
25550
+ *
25551
+ * The default belongs to the SURFACE, which has the `listSources` rows
25552
+ * and can say which one it picked (D569 § 1–3; the viewer already
25553
+ * always sends this).
25452
25554
  *
25453
25555
  * It replaced `sources?: string[]`, a VIEW filter over source ids that
25454
25556
  * assumed the answer was a fan-out over everything a camera has. The
25455
- * operator settled otherwise on 2026-09-20 — *"il get videoclips
25456
- * prendere un provider opzionale, di default va su camstack"*,
25457
- * *"l'utilizzatore è uno solo"* — so the list is asked of one provider
25458
- * at a time and there is nothing to filter out of it.
25557
+ * operator settled otherwise on 2026-09-20 — *"l'utilizzatore è uno
25558
+ * solo"* — so the list is asked of one provider at a time and there is
25559
+ * nothing to filter out of it.
25459
25560
  */
25460
- provider: string().optional()
25561
+ provider: string().min(1)
25461
25562
  }), array(ClipSchema).readonly(), {
25462
25563
  kind: "query",
25463
25564
  auth: "protected"
@@ -25494,6 +25595,68 @@ var videoclipsCapability = {
25494
25595
  }), ClipPlaybackSchema, {
25495
25596
  kind: "query",
25496
25597
  auth: "protected"
25598
+ }),
25599
+ /**
25600
+ * This clip's BYTES, base64, bounded — the by-handle read a clip EXPORT
25601
+ * pulls once (D558).
25602
+ *
25603
+ * `getClipPlayback` is the right answer for a player: it hands back a URL
25604
+ * on a plane the hub serves `access:'authenticated'`, which a browser and a
25605
+ * viewer session satisfy. It is the wrong answer for another ADDON. There
25606
+ * is no addon→addon byte transport in this framework — `AddonDataPlane`
25607
+ * only lets an addon SERVE, on `127.0.0.1` behind a per-listener secret
25608
+ * only the hub may present — so a recorder that wants a camera's clip
25609
+ * cannot fetch that URL. This method is the one seam that exists for it,
25610
+ * and it is deliberately the same shape (and the same bound) as
25611
+ * `recordingExport.readExportBytes`, which exists for the mirror-image
25612
+ * reason.
25613
+ *
25614
+ * Routing needs no `provider` pin: the id is source-prefixed and
25615
+ * self-contained, so `device-collection-dispatch.ts` rule 3 hands the call
25616
+ * to the source that claims it — and an id nobody claims is REFUSED rather
25617
+ * than answered by another source.
25618
+ *
25619
+ * The producer reuses the fetch path it already has, completion rules
25620
+ * included: a clip is taken by cmd 5 and finished on a short idle window
25621
+ * whose result is PROVED against the catalog row's own span, retried once
25622
+ * when it comes up materially short, and served-and-named when it is still
25623
+ * short (D568). A second fetch with different completion rules is exactly
25624
+ * the second authority D558 refuses to create.
25625
+ *
25626
+ * Every refusal THROWS with its reason and none of them is silent — the
25627
+ * sleep gate (decided before `getApi()`, liftable only by
25628
+ * {@link ClipWakeSchema}), a catalog row nobody claims, a clip with no
25629
+ * bytes behind it, a mux that failed, and the size bound. The caller turns
25630
+ * that reason into an operator-facing one; a truncated file is never an
25631
+ * answer.
25632
+ */
25633
+ readClipBytes: optionalMethod(object({
25634
+ deviceId: number(),
25635
+ clipId: string().min(1),
25636
+ /**
25637
+ * Which twin to fetch, on the mapping D549 15 already fixed:
25638
+ * `low | mid` → the sub file, `high` → the main twin. `auto` is not
25639
+ * accepted here for the same reason it is not accepted by
25640
+ * `getClipPlayback` — a stored file has no broker session, so the
25641
+ * adaptive tier cannot be resolved for it.
25642
+ */
25643
+ profile: CamProfileSchema.optional(),
25644
+ /**
25645
+ * The CALLER's byte bound, so an over-size clip is refused before it is
25646
+ * read and encoded rather than after. Capped by
25647
+ * {@link VIDEOCLIPS_MAX_READ_BYTES} whatever is passed; absent means
25648
+ * that ceiling.
25649
+ */
25650
+ maxBytes: number().int().positive().optional(),
25651
+ /**
25652
+ * The operator's authorisation to wake a sleeping camera for this
25653
+ * read. Absent — the default — means a sleeping standalone battery
25654
+ * camera is REFUSED by name, before any session is opened.
25655
+ */
25656
+ wake: ClipWakeSchema.optional()
25657
+ }), ClipBytesSchema, {
25658
+ kind: "query",
25659
+ auth: "protected"
25497
25660
  })
25498
25661
  }
25499
25662
  };
@@ -33447,13 +33610,101 @@ var ExportStateSchema = _enum([
33447
33610
  "expired",
33448
33611
  "deleted"
33449
33612
  ]);
33450
- /** One export job / history row. */
33613
+ /**
33614
+ * WHAT an export is — the authority, as opposed to the four top-level fields
33615
+ * the Library sorts and labels on (D558 § 2.2).
33616
+ *
33617
+ * Read it through {@link exportSubjectOf}, never off the record directly: the
33618
+ * field is optional for the history rows written before it existed, and that
33619
+ * absence has exactly one interpreter.
33620
+ */
33621
+ var ExportSubjectSchema = discriminatedUnion("kind", [object({
33622
+ kind: literal("footage"),
33623
+ deviceId: number(),
33624
+ profiles: array(string()).min(1),
33625
+ fromMs: number(),
33626
+ toMs: number()
33627
+ }), object({
33628
+ kind: literal("clip"),
33629
+ deviceId: number(),
33630
+ provider: string().min(1),
33631
+ source: string().min(1),
33632
+ sourceLabel: string().min(1),
33633
+ clipId: string().min(1),
33634
+ /**
33635
+ * WHERE IN THE CATALOG to confirm this clip — the day window the surface was
33636
+ * already listing when the operator picked the segment.
33637
+ *
33638
+ * It is **not** a time range control and it never becomes one: the record's
33639
+ * `fromMs`/`toMs` come from the catalog ROW and from nothing a caller
33640
+ * supplied (D558 § 5.4.3), and a window that does not contain the clip is a
33641
+ * `catalog-miss`, not a silently wider search. It exists because
33642
+ * `videoclips.listClips` takes `since`/`until` and has no by-handle twin:
33643
+ * the catalog check D558 asks for is literally that call, and a call needs a
33644
+ * window. The surface has one — `ClipsBrowser`'s `dayWindow`, one local
33645
+ * wall-clock day, which is also the only width measured to be cheap (one
33646
+ * day on 592 lists 171 clips in 712 ms, a busy day 546 in 2.0 s; twenty days
33647
+ * of one child's events took 3.6–5.4 s).
33648
+ */
33649
+ catalogWindow: object({
33650
+ sinceMs: number(),
33651
+ untilMs: number()
33652
+ }),
33653
+ profile: _enum([
33654
+ "high",
33655
+ "mid",
33656
+ "low"
33657
+ ]),
33658
+ /**
33659
+ * The operator's authorisation to wake a sleeping camera for this export.
33660
+ * ONE definition, in the cap that owns the clip read ({@link ClipWakeSchema}),
33661
+ * because the gate that honours it is the clip provider's sleep gate — a
33662
+ * second enum here would be a second contract. Absent by default; never
33663
+ * settable by a scheduler or a retry.
33664
+ *
33665
+ * **One authorised yes is ONE wake.** A failed clip export is retried only by
33666
+ * an operator act that asks again; a queued job that outlived its wake fails
33667
+ * with a reason rather than waking on its turn; and this subject carries
33668
+ * exactly one profile precisely so one tap is never two fetches (D558 § 5.2).
33669
+ */
33670
+ wake: ClipWakeSchema.optional()
33671
+ })]);
33672
+ /**
33673
+ * One export job / history row.
33674
+ *
33675
+ * **`subject` is the AUTHORITY on what was exported. `deviceId`, `profile`,
33676
+ * `fromMs` and `toMs` are its PROJECTION** — kept top-level because the whole
33677
+ * Library sorts and labels on them (`library-items.ts` orders an export by
33678
+ * `fromMs`; `export-format.ts` draws `rangeLabel` from the pair), and a row
33679
+ * that did not fill them would sort under the epoch and render a blank range.
33680
+ * Write to the subject and read from the projection and the two will disagree;
33681
+ * the projection is derived at creation and never edited afterwards.
33682
+ *
33683
+ * And they mean DIFFERENT FACTS for the two kinds, which is the part a reader
33684
+ * who knows only the recording export will get wrong:
33685
+ *
33686
+ * | field | `kind:'footage'` | `kind:'clip'` |
33687
+ * | --- | --- | --- |
33688
+ * | `fromMs`/`toMs` | the stretch the operator ASKED for | the camera's own boundaries, always `clip.timeRange`, never anything a caller supplied |
33689
+ * | `profile` | the stream rendered | the twin actually SERVED (`subject.profile` is the one asked for) |
33690
+ *
33691
+ * Same type, different fact — the shape this repo keeps getting wrong (D385's
33692
+ * two authorities, D224's second copy).
33693
+ */
33451
33694
  var ExportRecordSchema = object({
33452
33695
  id: string(),
33453
33696
  deviceId: number(),
33454
33697
  profile: string(),
33455
33698
  fromMs: number(),
33456
33699
  toMs: number(),
33700
+ /**
33701
+ * What this export IS. Optional ONLY for the rows written before D558: the
33702
+ * store parses every row through this schema on every read, so a required
33703
+ * field would make the export AUDIT — which is the whole reason rows survive
33704
+ * file deletion — unreadable in one release. Absence means `footage`, and
33705
+ * {@link exportSubjectOf} is the one place that says so.
33706
+ */
33707
+ subject: ExportSubjectSchema.optional(),
33457
33708
  options: ExportOptionsSchema,
33458
33709
  state: ExportStateSchema,
33459
33710
  /** 0–100 while rendering; null otherwise. */
@@ -33470,6 +33721,22 @@ var ExportRecordSchema = object({
33470
33721
  /** Failure reason when state is 'failed'; null otherwise. */
33471
33722
  error: string().nullable()
33472
33723
  });
33724
+ _enum([
33725
+ "catalog-miss",
33726
+ "catalog-unreachable",
33727
+ "no-file-for-window",
33728
+ "clip-in-progress",
33729
+ "unsupported-option",
33730
+ "sleeping",
33731
+ "camera-refused",
33732
+ "fetch-failed",
33733
+ "too-large-to-transfer",
33734
+ "wake-expired"
33735
+ ]);
33736
+ /** `<token>: <prose>` — the ONE composition of a clip export's failure string. */
33737
+ function clipExportFailure(code, detail) {
33738
+ return detail.length > 0 ? `${code}: ${detail}` : code;
33739
+ }
33473
33740
  /** Candidate download URLs (LAN first, then operator extra hosts). */
33474
33741
  var ExportDownloadSchema = object({
33475
33742
  url: string(),
@@ -33488,16 +33755,50 @@ var ExportBytesSchema = object({
33488
33755
  name: string(),
33489
33756
  bytes: number().int().nonnegative()
33490
33757
  });
33758
+ /** Canonical `profiles[]`, falling back to the legacy singular `profile`. */
33759
+ function resolveExportProfiles(input) {
33760
+ if (input.profiles !== void 0 && input.profiles.length > 0) return [...input.profiles];
33761
+ if (typeof input.profile === "string" && input.profile.length > 0) return [input.profile];
33762
+ return [];
33763
+ }
33491
33764
  method(object({
33492
33765
  deviceId: number(),
33493
33766
  /** @deprecated Prefer `profiles`. Kept so timelapse/notifiers keep working. */
33494
33767
  profile: string().optional(),
33495
33768
  profiles: array(string()).min(1).optional(),
33496
- fromMs: number(),
33497
- toMs: number(),
33769
+ /** Footage only — a clip's boundaries are the camera's. */
33770
+ fromMs: number().optional(),
33771
+ toMs: number().optional(),
33772
+ /** What to export. Absent means the legacy flat footage request. */
33773
+ subject: ExportSubjectSchema.optional(),
33498
33774
  options: ExportOptionsSchema
33499
33775
  }).superRefine((v, ctx) => {
33500
- if ((v.profiles !== void 0 && v.profiles.length > 0 ? v.profiles : v.profile !== void 0 ? [v.profile] : []).length < 1) ctx.addIssue({
33776
+ if (v.subject?.kind === "clip") {
33777
+ if (v.subject.deviceId !== v.deviceId) ctx.addIssue({
33778
+ code: ZodIssueCode.custom,
33779
+ message: `subject.deviceId (${v.subject.deviceId}) must equal deviceId (${v.deviceId}) — the top-level field is what per-device scope enforcement reads`,
33780
+ path: ["subject", "deviceId"]
33781
+ });
33782
+ if (v.fromMs !== void 0 || v.toMs !== void 0) ctx.addIssue({
33783
+ code: ZodIssueCode.custom,
33784
+ message: "a clip export asks for no time range: the camera chose the boundaries and they are read from the catalog row",
33785
+ path: ["fromMs"]
33786
+ });
33787
+ return;
33788
+ }
33789
+ if (v.subject?.kind === "footage" && v.subject.deviceId !== v.deviceId) ctx.addIssue({
33790
+ code: ZodIssueCode.custom,
33791
+ message: `subject.deviceId (${v.subject.deviceId}) must equal deviceId (${v.deviceId})`,
33792
+ path: ["subject", "deviceId"]
33793
+ });
33794
+ const fromMs = v.subject?.kind === "footage" ? v.subject.fromMs : v.fromMs;
33795
+ const toMs = v.subject?.kind === "footage" ? v.subject.toMs : v.toMs;
33796
+ if (typeof fromMs !== "number" || typeof toMs !== "number") ctx.addIssue({
33797
+ code: ZodIssueCode.custom,
33798
+ message: "a footage export needs fromMs and toMs",
33799
+ path: ["fromMs"]
33800
+ });
33801
+ if ((v.subject?.kind === "footage" ? [...v.subject.profiles] : resolveExportProfiles(v)).length < 1) ctx.addIssue({
33501
33802
  code: ZodIssueCode.custom,
33502
33803
  message: "pass profiles[] (min 1) or legacy profile",
33503
33804
  path: ["profiles"]
@@ -44039,6 +44340,12 @@ Object.freeze({
44039
44340
  addonId: null,
44040
44341
  access: "view"
44041
44342
  },
44343
+ "videoclips.readClipBytes": {
44344
+ capName: "videoclips",
44345
+ capScope: "device",
44346
+ addonId: null,
44347
+ access: "view"
44348
+ },
44042
44349
  "viewerUi.getStaticDir": {
44043
44350
  capName: "viewer-ui",
44044
44351
  capScope: "system",
@@ -46057,6 +46364,11 @@ Object.freeze({
46057
46364
  form: "single",
46058
46365
  optional: false
46059
46366
  }],
46367
+ "videoclips.readClipBytes": [{
46368
+ name: "deviceId",
46369
+ form: "single",
46370
+ optional: false
46371
+ }],
46060
46372
  "waterHeater.setAway": [{
46061
46373
  name: "deviceId",
46062
46374
  form: "single",
@@ -148229,6 +148541,51 @@ function describeMuxFailure(run) {
148229
148541
  return null;
148230
148542
  }
148231
148543
  //#endregion
148544
+ //#region src/clips/clip-truncation.ts
148545
+ /**
148546
+ * The window a TRUNCATED fetch is retried on: the library's own default, the
148547
+ * one this repo shipped for its whole life. A retry exists to answer "was that
148548
+ * the window or the camera?", so it must be the conservative number and not a
148549
+ * second short one.
148550
+ */
148551
+ var CLIP_IDLE_WINDOW_RETRY_MS = 2e3;
148552
+ /**
148553
+ * Did this pass deliver the clip the row describes?
148554
+ *
148555
+ * Only a SHORTFALL is a defect. A decode that runs longer than the row is
148556
+ * routine — the row's stamps are whole seconds and its twins differ by up to
148557
+ * four — and calling it truncated would refuse a clip that is more complete
148558
+ * than the catalog knew.
148559
+ */
148560
+ function judgeClipDuration(input) {
148561
+ if (input.inProgress === true) return {
148562
+ kind: "unknown",
148563
+ reason: "clip-open"
148564
+ };
148565
+ if (input.decodedSeconds === null || !Number.isFinite(input.decodedSeconds)) return {
148566
+ kind: "unknown",
148567
+ reason: "duration-unmeasured"
148568
+ };
148569
+ if (!Number.isFinite(input.expectedMs) || input.expectedMs <= 0) return {
148570
+ kind: "unknown",
148571
+ reason: "row-window-unknown"
148572
+ };
148573
+ const expectedSeconds = input.expectedMs / 1e3;
148574
+ const decodedSeconds = input.decodedSeconds;
148575
+ const shortfallSeconds = expectedSeconds - decodedSeconds;
148576
+ if (shortfallSeconds > 1.5) return {
148577
+ kind: "short",
148578
+ expectedSeconds,
148579
+ decodedSeconds,
148580
+ shortfallSeconds
148581
+ };
148582
+ return {
148583
+ kind: "complete",
148584
+ expectedSeconds,
148585
+ decodedSeconds
148586
+ };
148587
+ }
148588
+ //#endregion
148232
148589
  //#region src/clips/clip-thumb-queue.ts
148233
148590
  /**
148234
148591
  * The provider's OWN CoverPreview lane — two queues, one in flight per host.
@@ -148371,6 +148728,43 @@ var ClipThumbQueue = class {
148371
148728
  }
148372
148729
  };
148373
148730
  //#endregion
148731
+ //#region src/clips/clip-prefetch.ts
148732
+ /** The longest a device may stay quiet after refusals, whatever its interval. */
148733
+ var PREFETCH_QUIET_MAX_MS = 720 * 6e4;
148734
+ /**
148735
+ * How long a device that refused stays un-asked, in INTERVALS rather than
148736
+ * wall-clock: the refresh interval is an operator setting (5 min – 24 h), and
148737
+ * a quiet period in minutes would be either no gap at all at one end or a day
148738
+ * at the other. One refusal skips the next two passes, two skips four, and so
148739
+ * on, capped.
148740
+ */
148741
+ function prefetchQuietMs(consecutiveRefusals, intervalMs) {
148742
+ if (consecutiveRefusals <= 0) return 0;
148743
+ const doubled = intervalMs * 2 ** consecutiveRefusals;
148744
+ return Number.isFinite(doubled) ? Math.min(doubled, PREFETCH_QUIET_MAX_MS) : PREFETCH_QUIET_MAX_MS;
148745
+ }
148746
+ /**
148747
+ * May this camera's stills be prefetched right now?
148748
+ *
148749
+ * The topology comes first and is absolute: no amount of idle host or empty
148750
+ * ladder makes a still on a standalone battery camera free.
148751
+ */
148752
+ function decideClipPrefetch(input) {
148753
+ if (input.mode === "forced-wake") return {
148754
+ kind: "skip",
148755
+ reason: "battery-wake-cost"
148756
+ };
148757
+ if (input.quiet) return {
148758
+ kind: "skip",
148759
+ reason: "quiet-after-refusal"
148760
+ };
148761
+ if (input.hostBusy) return {
148762
+ kind: "skip",
148763
+ reason: "host-busy"
148764
+ };
148765
+ return { kind: "run" };
148766
+ }
148767
+ //#endregion
148374
148768
  //#region src/clips/clip-identity.ts
148375
148769
  /**
148376
148770
  * A Reolink clip's IDENTITY — the id the operator's surface carries around and
@@ -148962,6 +149356,18 @@ function normaliseHour(hour) {
148962
149356
  }
148963
149357
  //#endregion
148964
149358
  //#region src/clips/reolink-videoclips-provider.ts
149359
+ /**
149360
+ * The filename an export carries away, from the camera's own handle.
149361
+ *
149362
+ * A hub child's handle is a full path (`/mnt/sda/U10…/RecS02_….mp4`) and a
149363
+ * standalone's is a bare name, so only the last segment is a name; the
149364
+ * extension is re-stated because what we produce is an MP4 whatever the
149365
+ * camera called its file.
149366
+ */
149367
+ function clipFileLabel(fileName) {
149368
+ const stem = (fileName.split("/").at(-1) ?? fileName).replace(/\.[^.]+$/, "");
149369
+ return `${stem === "" ? "clip" : stem}.mp4`;
149370
+ }
148965
149371
  function createReolinkVideoclipsProvider(deps) {
148966
149372
  /** Last known availability per `deviceId|source`, written by every read. */
148967
149373
  const health = /* @__PURE__ */ new Map();
@@ -149282,6 +149688,120 @@ function createReolinkVideoclipsProvider(deps) {
149282
149688
  format: "mp4",
149283
149689
  served: prepared.served
149284
149690
  };
149691
+ },
149692
+ /**
149693
+ * This clip's BYTES, base64, bounded — the producing half of a clip
149694
+ * export (D558 § 3, D572).
149695
+ *
149696
+ * ## What it refuses, and in whose words
149697
+ *
149698
+ * Every exit throws `clipExportFailure(<token>, <prose>)`. The engine
149699
+ * recovers the token with `clipExportFailureOf` and BELIEVES it; anything
149700
+ * that does not parse becomes `fetch-failed` with the prose kept verbatim.
149701
+ * So a refusal this side can name is named here — a `sleeping` that
149702
+ * arrives as prose is a `sleeping` the modal cannot render.
149703
+ *
149704
+ * ## The order of the questions, and why it is this order
149705
+ *
149706
+ * The cheap ones come first and none of them touches the camera: the id,
149707
+ * the row, whether the file is still being written, which twin exists, and
149708
+ * the SIZE the catalog already declared for it. A main twin over the bound
149709
+ * is refused for nothing — no session, no transfer, no mux — which is the
149710
+ * rule bulk work over stored media already follows (D54). Only then does
149711
+ * `prepareBytes` reach a camera, behind the sleep gate that has to sit in
149712
+ * front of the login.
149713
+ *
149714
+ * ## `high` against a 50 MiB ceiling
149715
+ *
149716
+ * A missing main twin is a DIVERGENCE, not a refusal: the sub is served
149717
+ * and `served` says `low`, exactly as the player does (D549 15), because
149718
+ * 17 of 546 clips on 592 have no main copy and an export of the copy that
149719
+ * exists beats no export. A main twin that exists and is too BIG is the
149720
+ * other case and is refused by name — the cap's own docblock settles it
149721
+ * ("above the bound the provider REFUSES with the size in the message,
149722
+ * never truncates"), the operator keeps the unbounded playback route for
149723
+ * that file, and the chunked read the cap names is what removes the
149724
+ * refusal rather than a silent 33× quality substitution.
149725
+ */
149726
+ readClipBytes: async ({ deviceId, clipId, profile, maxBytes, wake }) => {
149727
+ const tags = { deviceId };
149728
+ const refuse = (code, detail, meta) => {
149729
+ deps.logger.warn("videoclips: refusing a clip byte read", {
149730
+ tags,
149731
+ meta: {
149732
+ clipId,
149733
+ branch: code,
149734
+ ...meta
149735
+ }
149736
+ });
149737
+ throw new Error(clipExportFailure(code, detail));
149738
+ };
149739
+ const parsed = parseClipId(clipId);
149740
+ if (parsed === null) return refuse("catalog-miss", `clip id "${clipId}" was not minted by the Reolink provider`, {});
149741
+ const clipKey = clipKeyFor(parsed.channel, parsed.fileName);
149742
+ const row = rowsByKey.get(`${deviceId}|${clipKey}`);
149743
+ if (row === void 0) return refuse("catalog-miss", `clip "${clipId}" is not in this node's catalog for device ${deviceId} — list the day that holds it first`, { clipKey });
149744
+ if (row.inProgress === true) return refuse("clip-in-progress", `clip "${clipId}" is still being written, so it has no end to export`, { clipKey });
149745
+ const mainFileName = profile === "high" ? row.mainFileName : void 0;
149746
+ if (profile === "high" && mainFileName === void 0) deps.logger.warn("videoclips: no main twin for this clip — serving the sub copy", {
149747
+ tags,
149748
+ meta: {
149749
+ clipId,
149750
+ clipKey,
149751
+ branch: "no-main-twin",
149752
+ asked: profile
149753
+ }
149754
+ });
149755
+ const twin = mainFileName === void 0 ? "sub" : "main";
149756
+ const fileName = mainFileName ?? row.subFileName;
149757
+ if (fileName === "") return refuse("no-file-for-window", `clip "${clipId}" is listed with no byte handle behind it`, {
149758
+ clipKey,
149759
+ twin
149760
+ });
149761
+ const served = twin === "main" ? "high" : "low";
149762
+ const bound = Math.min(maxBytes ?? 52428800, VIDEOCLIPS_MAX_READ_BYTES);
149763
+ const declaredBytes = twin === "main" ? row.mainBytes : row.subBytes;
149764
+ if (declaredBytes !== void 0 && declaredBytes > bound) return refuse("too-large-to-transfer", `the camera lists the ${twin} file of clip "${clipId}" as ${declaredBytes} bytes, over the ${bound}-byte bound for an inline read — play it from its playback URL instead`, {
149765
+ clipKey,
149766
+ twin,
149767
+ declaredBytes,
149768
+ bound
149769
+ });
149770
+ const outcome = await deps.prepareBytes({
149771
+ deviceId,
149772
+ row,
149773
+ fileName,
149774
+ twin,
149775
+ ...wake !== void 0 ? { wake } : {}
149776
+ });
149777
+ if (outcome.kind === "refused") throw new Error(clipExportFailure(outcome.code, outcome.detail));
149778
+ if (outcome.bytes.byteLength > bound) return refuse("too-large-to-transfer", `clip "${clipId}" muxed to ${outcome.bytes.byteLength} bytes, over the ${bound}-byte bound for an inline read`, {
149779
+ clipKey,
149780
+ twin,
149781
+ bytes: outcome.bytes.byteLength,
149782
+ bound
149783
+ });
149784
+ deps.logger.info("videoclips: served a Reolink clip inline", {
149785
+ tags,
149786
+ meta: {
149787
+ clipId,
149788
+ clipKey,
149789
+ twin,
149790
+ served,
149791
+ asked: profile ?? null,
149792
+ bytes: outcome.bytes.byteLength,
149793
+ durationMs: outcome.durationMs,
149794
+ wake: wake ?? "none"
149795
+ }
149796
+ });
149797
+ return {
149798
+ base64: outcome.bytes.toString("base64"),
149799
+ contentType: "video/mp4",
149800
+ name: clipFileLabel(fileName),
149801
+ bytes: outcome.bytes.byteLength,
149802
+ served,
149803
+ ...outcome.durationMs !== null ? { durationMs: outcome.durationMs } : {}
149804
+ };
149285
149805
  }
149286
149806
  };
149287
149807
  /**
@@ -149543,6 +150063,12 @@ var ClipCatalogRefreshScheduler = class {
149543
150063
  lastRunAt = /* @__PURE__ */ new Map();
149544
150064
  /** Cameras whose refresh has not come back yet. */
149545
150065
  inFlight = /* @__PURE__ */ new Set();
150066
+ /** Consecutive prefetch passes this camera stopped on a refusal. Cleared by
150067
+ * the first pass that lands, so a camera that recovers is asked again on
150068
+ * the very next tick. */
150069
+ prefetchRefusals = /* @__PURE__ */ new Map();
150070
+ /** Until when this camera's prefetch stays un-asked. */
150071
+ prefetchQuietUntil = /* @__PURE__ */ new Map();
149546
150072
  constructor(deps) {
149547
150073
  this.deps = deps;
149548
150074
  }
@@ -149612,6 +150138,7 @@ var ClipCatalogRefreshScheduler = class {
149612
150138
  elapsedMs: this.deps.now() - now
149613
150139
  }
149614
150140
  });
150141
+ await this.prefetch(target, mode);
149615
150142
  } catch (err) {
149616
150143
  this.deps.markStale(target.deviceId);
149617
150144
  this.deps.logger.warn("videoclips: catalog refresh failed — the catalog stays as it was", {
@@ -149626,10 +150153,92 @@ var ClipCatalogRefreshScheduler = class {
149626
150153
  this.inFlight.delete(target.deviceId);
149627
150154
  }
149628
150155
  }
150156
+ /**
150157
+ * The still prefetch for a camera whose catalog was just re-read.
150158
+ *
150159
+ * It NEVER throws — a prefetch is an enhancement to a refresh that already
150160
+ * landed, and letting it reach the refresh's own catch would mark a catalog
150161
+ * stale that is not. Every exit says which branch it took, per camera.
150162
+ */
150163
+ async prefetch(target, mode) {
150164
+ const deviceId = target.deviceId;
150165
+ const tags = { deviceId };
150166
+ const quietUntil = this.prefetchQuietUntil.get(deviceId) ?? 0;
150167
+ const decision = decideClipPrefetch({
150168
+ mode,
150169
+ hostBusy: this.deps.hostBusy(target.hostKey),
150170
+ quiet: quietUntil > this.deps.now()
150171
+ });
150172
+ if (decision.kind === "skip") {
150173
+ this.deps.logger.info("videoclips: still prefetch skipped", {
150174
+ tags,
150175
+ meta: {
150176
+ branch: `prefetch-${decision.reason}`,
150177
+ mode,
150178
+ host: target.hostKey,
150179
+ quietForMs: Math.max(0, quietUntil - this.deps.now())
150180
+ }
150181
+ });
150182
+ return;
150183
+ }
150184
+ try {
150185
+ const outcome = await this.deps.prefetchStills(deviceId);
150186
+ if (outcome.stop === "refused") {
150187
+ this.quieten(target, {
150188
+ branch: "prefetch-refused",
150189
+ mode,
150190
+ minted: outcome.minted,
150191
+ scanned: outcome.scanned,
150192
+ alreadyHeld: outcome.alreadyHeld,
150193
+ code: outcome.refusal?.code ?? null,
150194
+ disposition: outcome.refusal?.disposition ?? null,
150195
+ clipKey: outcome.refusal?.clipKey ?? null
150196
+ });
150197
+ return;
150198
+ }
150199
+ this.prefetchRefusals.delete(deviceId);
150200
+ this.prefetchQuietUntil.delete(deviceId);
150201
+ this.deps.logger.info("videoclips: stills prefetched", {
150202
+ tags,
150203
+ meta: {
150204
+ branch: `prefetch-${outcome.stop}`,
150205
+ mode,
150206
+ minted: outcome.minted,
150207
+ scanned: outcome.scanned,
150208
+ alreadyHeld: outcome.alreadyHeld
150209
+ }
150210
+ });
150211
+ } catch (err) {
150212
+ this.quieten(target, {
150213
+ branch: "prefetch-failed",
150214
+ mode,
150215
+ error: errMessage$1(err)
150216
+ });
150217
+ }
150218
+ }
150219
+ /** Arm the doubling quiet period and say so, with what the pass reported. */
150220
+ quieten(target, meta) {
150221
+ const deviceId = target.deviceId;
150222
+ const refusals = (this.prefetchRefusals.get(deviceId) ?? 0) + 1;
150223
+ this.prefetchRefusals.set(deviceId, refusals);
150224
+ const quietForMs = prefetchQuietMs(refusals, target.intervalMinutes * 6e4);
150225
+ this.prefetchQuietUntil.set(deviceId, this.deps.now() + quietForMs);
150226
+ this.deps.logger.warn("videoclips: still prefetch stopped — the host is not serving stills", {
150227
+ tags: { deviceId },
150228
+ meta: {
150229
+ ...meta,
150230
+ host: target.hostKey,
150231
+ consecutiveRefusals: refusals,
150232
+ quietForMs
150233
+ }
150234
+ });
150235
+ }
149629
150236
  };
149630
150237
  function errMessage$1(err) {
149631
150238
  return err instanceof Error ? err.message : String(err);
149632
150239
  }
150240
+ //#endregion
150241
+ //#region src/clips/clip-service.ts
149633
150242
  function createClipService(deps) {
149634
150243
  const now = deps.now ?? (() => Date.now());
149635
150244
  const cache = new ClipCatalogCache({ now });
@@ -149652,8 +150261,15 @@ function createClipService(deps) {
149652
150261
  ffmpegBinaryPath: deps.ffmpegBinaryPath ?? "ffmpeg",
149653
150262
  spawnFn: spawn$1
149654
150263
  });
149655
- /** One prepare per clip: two clicks on one row must not pay cmd 5 twice. */
149656
- const preparing = /* @__PURE__ */ new Map();
150264
+ /**
150265
+ * One production per `(device, clip, twin)`: two clicks on one row — or a
150266
+ * click and an EXPORT of the same row — must not pay cmd 5 twice. It is
150267
+ * keyed by the twin because the two files are different bytes, and it is
150268
+ * shared by the player and the byte read because those two are the only
150269
+ * callers there are: an in-flight map per caller would be a second wake on
150270
+ * a battery camera the operator authorised once.
150271
+ */
150272
+ const producing = /* @__PURE__ */ new Map();
149657
150273
  const rowFor = (deviceId, clipKey) => {
149658
150274
  return cache.findBy(deviceId, (row) => row.clipKey === clipKey);
149659
150275
  };
@@ -149713,52 +150329,189 @@ function createClipService(deps) {
149713
150329
  return refuseStill("camera-refused", reason);
149714
150330
  }
149715
150331
  };
149716
- const prepareClip = async (deviceId, clipKey) => {
149717
- const ready = await media.pathIfPresent(deviceId, clipKey);
149718
- if (ready !== null) return ready;
149719
- const key = `${deviceId}|${clipKey}`;
149720
- const inFlight = preparing.get(key);
149721
- if (inFlight !== void 0) return inFlight;
149722
- const run = prepareClipOnce(deviceId, clipKey).finally(() => {
149723
- preparing.delete(key);
150332
+ /**
150333
+ * ONE clip's bytes, on the short window, with the fetch PROVED (D568).
150334
+ *
150335
+ * Completion is an idle window because nothing on the wire ends a cmd 5
150336
+ * transfer, and that window is short. What makes it safe is not the window,
150337
+ * it is the decoded duration judged against the row that asked for it.
150338
+ */
150339
+ const fetchVerifiedClipBytes = async (device, row, clipKey, fileName) => {
150340
+ const deviceId = device.deviceId;
150341
+ const api = await device.getApi();
150342
+ const fetchPass = (idleTimeoutMs) => fetchClipBytes({
150343
+ download: () => api.downloadRecordingDemuxed({
150344
+ channel: device.channel,
150345
+ ...device.uid !== void 0 ? { uid: device.uid } : {},
150346
+ fileName,
150347
+ idleTimeoutMs
150348
+ }),
150349
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
149724
150350
  });
149725
- preparing.set(key, run);
149726
- return run;
150351
+ const judge = (pass) => judgeClipDuration({
150352
+ expectedMs: row.endMs - row.startMs,
150353
+ decodedSeconds: pass.stats.durationSeconds,
150354
+ ...row.inProgress === true ? { inProgress: true } : {}
150355
+ });
150356
+ const first = await fetchPass(300);
150357
+ const firstVerdict = judge(first);
150358
+ if (firstVerdict.kind === "unknown") {
150359
+ const line = {
150360
+ tags: { deviceId },
150361
+ meta: {
150362
+ clipKey,
150363
+ branch: "completeness-unverified",
150364
+ reason: firstVerdict.reason,
150365
+ idleTimeoutMs: 300,
150366
+ expectedMs: row.endMs - row.startMs,
150367
+ decodedSeconds: first.stats.durationSeconds
150368
+ }
150369
+ };
150370
+ if (firstVerdict.reason === "clip-open") deps.logger.debug("videoclips: an open clip cannot be checked for truncation", line);
150371
+ else deps.logger.warn("videoclips: a clip fetch could not be checked for truncation", line);
150372
+ return first;
150373
+ }
150374
+ if (firstVerdict.kind === "complete") return first;
150375
+ deps.logger.warn("videoclips: a clip fetch came back truncated", {
150376
+ tags: { deviceId },
150377
+ meta: {
150378
+ clipKey,
150379
+ branch: "truncated-fetch",
150380
+ idleTimeoutMs: 300,
150381
+ expectedSeconds: firstVerdict.expectedSeconds,
150382
+ decodedSeconds: firstVerdict.decodedSeconds,
150383
+ shortfallSeconds: firstVerdict.shortfallSeconds,
150384
+ bytes: first.annexB.byteLength,
150385
+ keyframes: first.stats.keyframes
150386
+ }
150387
+ });
150388
+ const retry = await fetchPass(CLIP_IDLE_WINDOW_RETRY_MS);
150389
+ const keepRetry = (retry.stats.durationSeconds ?? 0) >= (first.stats.durationSeconds ?? 0);
150390
+ const kept = keepRetry ? retry : first;
150391
+ const verdict = keepRetry ? judge(retry) : firstVerdict;
150392
+ const keptWindowMs = keepRetry ? CLIP_IDLE_WINDOW_RETRY_MS : 300;
150393
+ if (verdict.kind === "short") {
150394
+ deps.logger.warn("videoclips: a clip is still short after the long window", {
150395
+ tags: { deviceId },
150396
+ meta: {
150397
+ clipKey,
150398
+ branch: "truncated-after-retry",
150399
+ idleTimeoutMs: keptWindowMs,
150400
+ retriedOnMs: CLIP_IDLE_WINDOW_RETRY_MS,
150401
+ expectedSeconds: verdict.expectedSeconds,
150402
+ decodedSeconds: verdict.decodedSeconds,
150403
+ shortfallSeconds: verdict.shortfallSeconds,
150404
+ bytes: kept.annexB.byteLength
150405
+ }
150406
+ });
150407
+ return kept;
150408
+ }
150409
+ deps.logger.info("videoclips: a truncated clip fetch landed whole on the long window", {
150410
+ tags: { deviceId },
150411
+ meta: {
150412
+ clipKey,
150413
+ branch: "truncation-recovered",
150414
+ idleTimeoutMs: keptWindowMs,
150415
+ decodedSeconds: verdict.kind === "complete" ? verdict.decodedSeconds : null,
150416
+ bytes: kept.annexB.byteLength
150417
+ }
150418
+ });
150419
+ return kept;
149727
150420
  };
149728
- const prepareClipOnce = async (deviceId, clipKey) => {
150421
+ /**
150422
+ * ONE production of one twin's MP4 — the only place a clip's bytes are made.
150423
+ *
150424
+ * The player and `readClipBytes` are both served from here, which is the
150425
+ * whole point: D568's completion rules (the 300 ms window, the decoded
150426
+ * duration proved against the row, the single retry on 2 000 ms) and D567's
150427
+ * mux (the MEASURED rate, the AAC copy, `+faststart`) exist once. A byte
150428
+ * read with its own fetch would be the second authority those records were
150429
+ * written to prevent.
150430
+ *
150431
+ * It never throws for a gated branch: every exit is a NAMED refusal in the
150432
+ * clip-export vocabulary, so the provider can hand the engine a token it
150433
+ * believes rather than prose it has to guess at (D572).
150434
+ */
150435
+ const produceTwin = async (input) => {
150436
+ const { deviceId, row, fileName, twin } = input;
150437
+ const clipKey = row.clipKey;
150438
+ const tags = { deviceId };
149729
150439
  const device = await deps.resolveDevice(deviceId);
149730
- if (device === null) return null;
150440
+ if (device === null) {
150441
+ deps.logger.warn("videoclips: no Reolink camera here to fetch this clip from", {
150442
+ tags,
150443
+ meta: {
150444
+ clipKey,
150445
+ twin,
150446
+ branch: "unknown-device"
150447
+ }
150448
+ });
150449
+ return {
150450
+ kind: "refused",
150451
+ code: "catalog-unreachable",
150452
+ detail: `device ${deviceId} is not a Reolink camera on this node`
150453
+ };
150454
+ }
149731
150455
  if (device.isBattery && device.sleeping && !device.isHubChild) {
149732
- deps.logger.warn("videoclips: refusing to fetch a clip from a sleeping camera", {
149733
- tags: { deviceId },
150456
+ if (input.wake !== "authorised") {
150457
+ deps.logger.warn("videoclips: refusing to fetch a clip from a sleeping camera", {
150458
+ tags,
150459
+ meta: {
150460
+ clipKey,
150461
+ twin,
150462
+ branch: "sleeping"
150463
+ }
150464
+ });
150465
+ return {
150466
+ kind: "refused",
150467
+ code: "sleeping",
150468
+ detail: `device ${deviceId} is a standalone battery camera and is sleeping — fetching a clip would wake it, and no operator authorisation was carried`
150469
+ };
150470
+ }
150471
+ deps.logger.warn("videoclips: waking a sleeping battery camera on an authorised clip read", {
150472
+ tags,
149734
150473
  meta: {
149735
150474
  clipKey,
149736
- branch: "sleeping"
150475
+ twin,
150476
+ branch: "wake-authorised"
149737
150477
  }
149738
150478
  });
149739
- return null;
149740
150479
  }
149741
- const row = rowFor(deviceId, clipKey);
149742
- if (row === null) {
149743
- deps.logger.warn("videoclips: no catalog row for this clip", {
149744
- tags: { deviceId },
150480
+ if (uidIsMissing(device)) {
150481
+ deps.logger.warn("videoclips: no uid for this camera — its clip cannot be addressed", {
150482
+ tags,
149745
150483
  meta: {
149746
150484
  clipKey,
149747
- branch: "no-catalog-row"
150485
+ twin,
150486
+ branch: "uid-missing"
149748
150487
  }
149749
150488
  });
149750
- return null;
150489
+ return {
150490
+ kind: "refused",
150491
+ code: "catalog-unreachable",
150492
+ detail: UID_MISSING_REASON
150493
+ };
150494
+ }
150495
+ let downloaded;
150496
+ try {
150497
+ downloaded = await fetchVerifiedClipBytes(device, row, clipKey, fileName);
150498
+ } catch (err) {
150499
+ const reason = err instanceof Error ? err.message : String(err);
150500
+ deps.logger.warn("videoclips: the camera never delivered this clip", {
150501
+ tags,
150502
+ meta: {
150503
+ clipKey,
150504
+ twin,
150505
+ branch: "camera-refused",
150506
+ error: reason
150507
+ }
150508
+ });
150509
+ return {
150510
+ kind: "refused",
150511
+ code: "camera-refused",
150512
+ detail: reason
150513
+ };
149751
150514
  }
149752
- const fileName = row.subFileName;
149753
- const api = await device.getApi();
149754
- const downloaded = await fetchClipBytes({
149755
- download: () => api.downloadRecordingDemuxed({
149756
- channel: device.channel,
149757
- ...device.uid !== void 0 ? { uid: device.uid } : {},
149758
- fileName
149759
- }),
149760
- sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
149761
- });
149762
150515
  const audio = decideClipAudio(downloaded.audio);
149763
150516
  if (audio.kind === "silent") deps.logger.warn("videoclips: serving a clip with no sound", {
149764
150517
  tags: { deviceId },
@@ -149802,14 +150555,24 @@ function createClipService(deps) {
149802
150555
  tags: { deviceId },
149803
150556
  meta: {
149804
150557
  clipKey,
150558
+ twin,
149805
150559
  branch: "mux-failed",
149806
150560
  error: failure
149807
150561
  }
149808
150562
  });
149809
- return null;
150563
+ return {
150564
+ kind: "refused",
150565
+ code: "fetch-failed",
150566
+ detail: failure
150567
+ };
149810
150568
  }
149811
150569
  const muxed = await readFile(outPath);
149812
- return await media.put(deviceId, clipKey, muxed);
150570
+ const decoded = downloaded.stats.durationSeconds;
150571
+ return {
150572
+ kind: "ok",
150573
+ bytes: muxed,
150574
+ durationMs: decoded !== null && Number.isFinite(decoded) && decoded > 0 ? Math.round(decoded * 1e3) : null
150575
+ };
149813
150576
  } finally {
149814
150577
  await rm(scratch, {
149815
150578
  recursive: true,
@@ -149817,6 +150580,85 @@ function createClipService(deps) {
149817
150580
  });
149818
150581
  }
149819
150582
  };
150583
+ /** {@link produceTwin}, deduplicated per `(device, clip, twin)`. */
150584
+ const produceOnce = (input) => {
150585
+ const key = `${input.deviceId}|${input.row.clipKey}|${input.twin}`;
150586
+ const inFlight = producing.get(key);
150587
+ if (inFlight !== void 0) return inFlight;
150588
+ const run = produceTwin(input).finally(() => {
150589
+ producing.delete(key);
150590
+ });
150591
+ producing.set(key, run);
150592
+ return run;
150593
+ };
150594
+ /**
150595
+ * The PLAYER's path: the sub twin, filed in the scratch, served by URL.
150596
+ *
150597
+ * `null` for every refusal — the playback route answers a status code and
150598
+ * has no vocabulary to carry a token; the named reason is already in the log
150599
+ * line `produceTwin` wrote.
150600
+ */
150601
+ const prepareClip = async (deviceId, clipKey) => {
150602
+ const ready = await media.pathIfPresent(deviceId, clipKey);
150603
+ if (ready !== null) return ready;
150604
+ const row = rowFor(deviceId, clipKey);
150605
+ if (row === null) {
150606
+ deps.logger.warn("videoclips: no catalog row for this clip", {
150607
+ tags: { deviceId },
150608
+ meta: {
150609
+ clipKey,
150610
+ branch: "no-catalog-row"
150611
+ }
150612
+ });
150613
+ return null;
150614
+ }
150615
+ const outcome = await produceOnce({
150616
+ deviceId,
150617
+ row,
150618
+ fileName: row.subFileName,
150619
+ twin: "sub"
150620
+ });
150621
+ if (outcome.kind !== "ok") return null;
150622
+ return media.put(deviceId, clipKey, outcome.bytes);
150623
+ };
150624
+ /**
150625
+ * The EXPORT's path: the asked twin's bytes, in memory, once.
150626
+ *
150627
+ * The scratch is the PLAYER's cache and its key
150628
+ * (`clipKeyFor(channel, subFileName)`) carries no twin, so it holds exactly
150629
+ * one thing: the sub file. A `sub` read therefore reuses it and warms it — a
150630
+ * clip the operator just watched costs no second cmd 5, and one he exports
150631
+ * first is already there when he plays it. A `main` read BYPASSES it in both
150632
+ * directions: writing a main file under that key would serve 33× the bytes
150633
+ * to every `low` playback of the clip, and filing it under a second key
150634
+ * would evict the sub clips the player really does re-read (10 files /
150635
+ * 200 MiB per device) to cache a one-shot export nobody reads twice.
150636
+ */
150637
+ const prepareBytes = async (input) => {
150638
+ const { deviceId, row, twin } = input;
150639
+ if (twin === "sub") {
150640
+ const cached = await media.read(deviceId, row.clipKey);
150641
+ if (cached !== null) {
150642
+ deps.logger.info("videoclips: a clip byte read was served from the scratch", {
150643
+ tags: { deviceId },
150644
+ meta: {
150645
+ clipKey: row.clipKey,
150646
+ twin,
150647
+ branch: "scratch-hit",
150648
+ bytes: cached.byteLength
150649
+ }
150650
+ });
150651
+ return {
150652
+ kind: "ok",
150653
+ bytes: cached,
150654
+ durationMs: null
150655
+ };
150656
+ }
150657
+ }
150658
+ const outcome = await produceOnce(input);
150659
+ if (outcome.kind === "ok" && twin === "sub") await media.put(deviceId, row.clipKey, outcome.bytes);
150660
+ return outcome;
150661
+ };
149820
150662
  const provider = createReolinkVideoclipsProvider({
149821
150663
  now,
149822
150664
  cache,
@@ -149828,6 +150670,7 @@ function createClipService(deps) {
149828
150670
  playbackUrl: `/addon/${REOLINK_ADDON_ID}/${CLIP_MEDIA_PREFIX}/${device.deviceId}/${clipKey}.mp4`,
149829
150671
  served: profile === "high" ? "high" : "low"
149830
150672
  }),
150673
+ prepareBytes,
149831
150674
  logger: deps.logger
149832
150675
  });
149833
150676
  return {
@@ -149838,7 +150681,8 @@ function createClipService(deps) {
149838
150681
  await provider.listClips({
149839
150682
  deviceId,
149840
150683
  since: until - CLIP_CATALOG_REFRESH_WINDOW_MS,
149841
- until
150684
+ until,
150685
+ provider: REOLINK_ADDON_ID
149842
150686
  });
149843
150687
  },
149844
150688
  hostBusy: (hostKey) => queue.busy(hostKey),
@@ -149853,15 +150697,36 @@ function createClipService(deps) {
149853
150697
  resolvePath: (deviceId, clipKey, _req) => prepareClip(deviceId, clipKey),
149854
150698
  logger: deps.logger
149855
150699
  }),
149856
- prefetchThumbnails: async (deviceId, limit = 20) => {
149857
- const rows = cache.allRows(deviceId).toSorted((a, b) => b.startMs - a.startMs).slice(0, limit);
150700
+ prefetchThumbnails: async (deviceId, limit = 60) => {
150701
+ const rows = cache.allRows(deviceId).toSorted((a, b) => b.startMs - a.startMs);
149858
150702
  let minted = 0;
150703
+ let scanned = 0;
150704
+ let alreadyHeld = 0;
150705
+ const outcome = (stop, refusal = null) => ({
150706
+ minted,
150707
+ scanned,
150708
+ alreadyHeld,
150709
+ stop,
150710
+ refusal
150711
+ });
150712
+ if (!await thumbs.hasHeadroomForPrefetch(deviceId)) return outcome("no-headroom");
149859
150713
  for (const row of rows) {
149860
- if (!await thumbs.hasHeadroomForPrefetch(deviceId)) break;
149861
- if (await thumbs.has(deviceId, row.clipKey)) continue;
149862
- if ((await mintThumbnail(deviceId, row.clipKey, "prefetch")).ok) minted += 1;
150714
+ scanned += 1;
150715
+ if (await thumbs.has(deviceId, row.clipKey)) {
150716
+ alreadyHeld += 1;
150717
+ continue;
150718
+ }
150719
+ if (minted >= limit) return outcome("budget");
150720
+ const result = await mintThumbnail(deviceId, row.clipKey, "prefetch");
150721
+ if (!result.ok) return outcome("refused", {
150722
+ code: result.code,
150723
+ disposition: result.disposition,
150724
+ clipKey: row.clipKey
150725
+ });
150726
+ minted += 1;
150727
+ if (minted % 16 === 0 && !await thumbs.hasHeadroomForPrefetch(deviceId)) return outcome("no-headroom");
149863
150728
  }
149864
- return minted;
150729
+ return outcome("rows-exhausted");
149865
150730
  }
149866
150731
  };
149867
150732
  }
@@ -164000,6 +164865,7 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
164000
164865
  if (!(device instanceof ReolinkCamera)) throw new Error(`clip refresh: device ${String(deviceId)} is not a Reolink camera here`);
164001
164866
  await device.wakeForClipCatalogRefresh();
164002
164867
  },
164868
+ prefetchStills: async (deviceId) => service.prefetchThumbnails(deviceId),
164003
164869
  hostBusy: (hostKey) => service.hostBusy(hostKey),
164004
164870
  logger: this.ctx.logger
164005
164871
  });