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