@trillboards/edge-sdk 0.2.165 → 0.2.169

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.
@@ -276,37 +276,20 @@ if ($Mode -eq 'bench') {
276
276
  # NO real-model coverage on any lane until this ran. A regression that
277
277
  # breaks only the operator schema (an enum the model cannot satisfy, a
278
278
  # custom field the prompt never mentions) is invisible to the audience arm.
279
- # setup already graded the delegates with a real image and retained its winner.
280
- # Starting another failed GPU engine can block this serial service before the
281
- # healthy CPU engine receives the schema request. Exercise the installed winner.
282
- function Get-InstalledInferenceAccelerator([string]$ConfigPath) {
283
- if (-not (Test-Path -LiteralPath $ConfigPath -PathType Leaf)) { return 'auto' }
284
- $config = Get-Content -LiteralPath $ConfigPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
285
- $models = $config.PSObject.Properties['models']
286
- if ($null -eq $models) { return 'auto' }
287
- $model = $models.Value.PSObject.Properties['gemma-4-E2B-it.litertlm']
288
- if ($null -eq $model) { return 'auto' }
289
- $backend = $model.Value.PSObject.Properties['backend']
290
- if ($null -ne $backend -and [string]$backend.Value -eq 'cpu') { return 'cpu' }
291
- return 'auto'
292
- }
293
- $litertDirectory = if ([string]::IsNullOrWhiteSpace($env:LITERT_LM_DIR)) {
294
- Join-Path $env:USERPROFILE '.litert-lm'
295
- } else { $env:LITERT_LM_DIR }
296
- $installedAccelerator = Get-InstalledInferenceAccelerator (Join-Path $litertDirectory 'config.json')
297
- Log "schema smoke uses installer-verified delegate policy: $installedAccelerator"
279
+ # Exercise the connector's normal automatic policy. The provider must reuse
280
+ # setup's verified backend itself; pinning CPU here would hide a startup bug.
298
281
  $verifyExit = 1
299
282
  try {
300
283
  $verify = Join-Path $PkgRoot 'scripts\verify-gemma4-vlm.mjs'
301
284
  $sopFields = Join-Path $PkgRoot 'scripts\fixtures\sop-profile-fields.json'
302
285
 
303
286
  Log "running real Gemma inference — AUDIENCE field set (--require-person)…"
304
- node $verify $Frame --litert "http://127.0.0.1:$Port" --accelerator $installedAccelerator --require-person
287
+ node $verify $Frame --litert "http://127.0.0.1:$Port" --require-person
305
288
  $verifyExit = $LASTEXITCODE
306
289
 
307
290
  if ($verifyExit -eq 0) {
308
291
  Log "running real Gemma inference — OPERATOR/SOP field set (--require-person)…"
309
- node $verify $Frame --litert "http://127.0.0.1:$Port" --accelerator $installedAccelerator --require-person `
292
+ node $verify $Frame --litert "http://127.0.0.1:$Port" --require-person `
310
293
  --field-set operator --profile-fields $sopFields
311
294
  $verifyExit = $LASTEXITCODE
312
295
  if ($verifyExit -ne 0) { Log "OPERATOR field set FAILED (exit $verifyExit)" }
@@ -0,0 +1,85 @@
1
+ [CmdletBinding()]
2
+ param(
3
+ [string]$FfmpegPath,
4
+ [string]$OutputDirectory
5
+ )
6
+ $ErrorActionPreference = 'Stop'
7
+ Set-StrictMode -Version Latest
8
+ $packageRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..\..')).Path
9
+ $module = Join-Path $packageRoot 'dist\ChannelProber.js'
10
+ if (-not (Test-Path -LiteralPath $module -PathType Leaf)) { throw 'Build the connector before native recorder qualification.' }
11
+ $nodeVersion = (& node -p 'process.versions.node' | Out-String).Trim()
12
+ if ($LASTEXITCODE -ne 0 -or ([Version]$nodeVersion).Major -ne 22) { throw 'Native recorder qualification requires Node 22.' }
13
+
14
+ $tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\')
15
+ $scratch = Join-Path $tempRoot ('tb-recorder-protocol-' + [Guid]::NewGuid().ToString('N'))
16
+ New-Item -ItemType Directory -Path $scratch | Out-Null
17
+ if (-not $OutputDirectory) { $OutputDirectory = Join-Path $tempRoot 'recorder-family-native' }
18
+ New-Item -ItemType Directory -Force -Path $OutputDirectory | Out-Null
19
+ $succeeded = $false
20
+ try {
21
+ # Read the product's actual FFmpeg pin. A host binary on PATH cannot qualify
22
+ # a different binary, and an old shared fixture cache must not vouch for it.
23
+ $pin = ((& (Join-Path $packageRoot 'deploy\windows\build-windows.ps1') -PrintFfmpegPin) | Out-String).Trim() -split '\s+'
24
+ if ($LASTEXITCODE -ne 0 -or $pin.Count -ne 2) { throw 'Could not read the shipped FFmpeg pin.' }
25
+ $expected = $pin[1].ToLowerInvariant()
26
+ if (-not $FfmpegPath) {
27
+ $candidates = @(
28
+ (Join-Path $packageRoot 'deploy\windows\dist-installer\stage-x64\Trillboards\edge\bin\ffmpeg.exe'),
29
+ (Join-Path $tempRoot 'tb-e2e-ffmpeg.exe')
30
+ )
31
+ foreach ($candidate in $candidates) {
32
+ if ((Test-Path -LiteralPath $candidate -PathType Leaf) -and
33
+ (Get-FileHash -LiteralPath $candidate -Algorithm SHA256).Hash.ToLowerInvariant() -eq $expected) {
34
+ $FfmpegPath = $candidate
35
+ break
36
+ }
37
+ }
38
+ if (-not $FfmpegPath) {
39
+ $FfmpegPath = Join-Path $scratch 'ffmpeg.exe'
40
+ Invoke-WebRequest -Uri $pin[0] -OutFile $FfmpegPath -UseBasicParsing
41
+ }
42
+ }
43
+ if ((Get-FileHash -LiteralPath $FfmpegPath -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expected) {
44
+ throw 'Native protocol FFmpeg differs from the connector release pin.'
45
+ }
46
+
47
+ # Official MediaMTX v1.21.2 checksums.sha256, pinned rather than latest.
48
+ $archive = Join-Path $scratch 'mediamtx.zip'
49
+ Invoke-WebRequest -Uri 'https://github.com/bluenviron/mediamtx/releases/download/v1.21.2/mediamtx_v1.21.2_windows_amd64.zip' -OutFile $archive -UseBasicParsing
50
+ if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant() -ne 'a84224f5a490855684e62ba6fb71e80ea2a5e16aed61883bb58380290e93e467') {
51
+ throw 'MediaMTX fixture checksum mismatch.'
52
+ }
53
+ Expand-Archive -LiteralPath $archive -DestinationPath $scratch
54
+ $media = Join-Path $scratch 'mediamtx.exe'
55
+ if (-not (Test-Path -LiteralPath $media -PathType Leaf)) { throw 'Pinned RTSP fixture executable is missing.' }
56
+ $cases = @('alias', 'onvif', 'onvif-sparse', 'onvif-variant', 'hikvision', 'single', 'ambiguous')
57
+ $count = 0
58
+ foreach ($case in $cases) {
59
+ $receipt = Join-Path $OutputDirectory ($case + '.json')
60
+ & node --max-old-space-size=1536 (Join-Path $packageRoot 'scripts\run-recorder-family-native.mjs') --ffmpeg $FfmpegPath --mediamtx $media --case $case --out $receipt
61
+ if ($LASTEXITCODE -ne 0) { throw "Native recorder case '$case' failed. See $receipt" }
62
+ $result = Get-Content -LiteralPath $receipt -Raw | ConvertFrom-Json
63
+ $expectedCases = if ($case -in @('alias', 'onvif-variant')) { 2 } else { 1 }
64
+ if (-not $result.passed -or -not $result.ownedChildrenStopped -or @($result.cases).Count -ne $expectedCases) {
65
+ throw "Native recorder case '$case' did not produce a complete passing receipt."
66
+ }
67
+ $count += @($result.cases).Count
68
+ }
69
+ if ($count -ne 9) { throw 'The Windows recorder qualification did not execute all nine behavioral cases.' }
70
+ $summary = @{ passed = $true; nativeBehaviorCases = $count; compiledProbe = $module; nodeVersion = $nodeVersion;
71
+ ffmpegSha256 = $expected; physicalRecorderQualified = $false; witnessedDesktopAcceptance = $false }
72
+ $summary | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $OutputDirectory 'summary.json') -Encoding UTF8
73
+ $succeeded = $true
74
+ Write-Host 'PASS: nine recorder-family cases through actual RTSP/RTP/H.264 and the compiled Windows connector.'
75
+ } finally {
76
+ # Only this owned temporary directory, after all native children exited.
77
+ if ($succeeded) {
78
+ $resolved = [IO.Path]::GetFullPath($scratch)
79
+ if ((Split-Path -Parent $resolved).TrimEnd('\') -cne $tempRoot -or
80
+ -not (Split-Path -Leaf $resolved).StartsWith('tb-recorder-protocol-')) {
81
+ throw 'Refusing cleanup outside the owned native protocol directory.'
82
+ }
83
+ Remove-Item -LiteralPath $resolved -Recurse -Force
84
+ }
85
+ }
@@ -62,6 +62,8 @@ export interface ProbeTarget {
62
62
  username: string;
63
63
  password: string;
64
64
  brandHint?: string;
65
+ /** A discovered family is evidence to verify; an explicit owner choice stays authoritative. */
66
+ brandHintSource?: 'discovery' | 'user';
65
67
  channelHint?: number;
66
68
  /**
67
69
  * An operator-typed RTSP stream path (`/live/ch1`, or the whole URL pasted out
@@ -111,7 +113,7 @@ export declare function brandPathCandidates(brand: string | undefined, ch: numbe
111
113
  password: string;
112
114
  }): string[];
113
115
  /** Remove XM query credentials before a probe result leaves the connector. */
114
- export declare function credentialFreePathTemplate(pathValue: string, brand: string | undefined): string;
116
+ export declare function credentialFreePathTemplate(pathValue: string, _brand: string | undefined): string;
115
117
  /** Restore a credential-free path recipe while writing the local-only config. */
116
118
  export declare function materializeCredentialPathTemplate(pathTemplate: string, username: string, password: string): string;
117
119
  /**
@@ -204,12 +206,6 @@ export declare function classifyFfmpegStderr(stderr: string): {
204
206
  failureClass: ProbeFailureClass;
205
207
  message: string;
206
208
  };
207
- /**
208
- * Probe one recorder. Streams results via opts.onResult as channels settle and
209
- * returns the full list. NEVER throws for per-channel problems — only for
210
- * programmer errors; credential rejection yields a single `rtsp_auth` result
211
- * for the host (the circuit-breaker contract).
212
- */
213
209
  export declare function probeHost(target: ProbeTarget, opts?: ProbeOptions): Promise<ChannelProbeResult[]>;
214
210
  export {};
215
211
  //# sourceMappingURL=ChannelProber.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ChannelProber.d.ts","sourceRoot":"","sources":["../src/ChannelProber.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAOtC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAI1D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,MAAM,MAAM,WAAW,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAE3D,MAAM,MAAM,iBAAiB,GACzB,WAAW,GACX,gBAAgB,GAChB,kBAAkB,GAClB,cAAc,GACd,UA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ACV,SAAiB,EACjB,OAAe,EACf,SAAiB,GAClB,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,KAAK,CAAC;IAAC,SAAS,CAAC,EAAE,aAAa,CAAA;CAAO,GACrG,OAAO,CAAC,SAAS,CAAC,CAuEpB;AAWD,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,MAAM,EACf,IAAI,EAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,KAAK,CAAA;CAAE,GACxE,OAAO,CAAC,kBAAkB,CAAC,CAmB7B;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAQpF;AAED,oEAAoE;AACpE,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG;IAAE,YAAY,EAAE,iBAAiB,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CA8BzG;AA8GD,wBAAsB,SAAS,CAAC,MAAM,EAAE,WAAW,EAAE,IAAI,GAAE,YAAiB,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAivB3G"}
@@ -51,6 +51,7 @@ exports.usernameCaseMismatchHint = usernameCaseMismatchHint;
51
51
  exports.classifyFfmpegStderr = classifyFfmpegStderr;
52
52
  exports.probeHost = probeHost;
53
53
  const child_process_1 = require("child_process");
54
+ const jpeg_js_1 = require("jpeg-js");
54
55
  const crypto_1 = require("crypto");
55
56
  const fs = __importStar(require("fs"));
56
57
  const net = __importStar(require("net"));
@@ -303,13 +304,12 @@ function brandPathCandidates(brand, ch, credentials) {
303
304
  // Unknown brand: walk common retail/OEM families (substreams first).
304
305
  // TVT/INVID-class recorders can return a misleading 401 on Dahua-style
305
306
  // paths even when the credentials are correct, so try TVT before Dahua.
306
- return [...hik, ...tvt, ...dahua, ...uniview];
307
+ return [...hik, ...tvt, ...dahua, ...uniview, ...xmeye];
307
308
  }
308
309
  }
309
310
  /** Remove XM query credentials before a probe result leaves the connector. */
310
- function credentialFreePathTemplate(pathValue, brand) {
311
- if (!isXmeyeBrand(brand))
312
- return pathValue;
311
+ function credentialFreePathTemplate(pathValue, _brand) {
312
+ // Unknown-family fallback can also reach an XM credential-bearing path.
313
313
  return pathValue.replace(/^\/user=[^&]*&password=[^&]*(&channel=)/i, '/user={username}&password={password}$1');
314
314
  }
315
315
  function canUseLegacyXmeyePathCredential(value) {
@@ -714,6 +714,89 @@ async function pooled(items, limit, fn) {
714
714
  * programmer errors; credential rejection yields a single `rtsp_auth` result
715
715
  * for the host (the circuit-breaker contract).
716
716
  */
717
+ /** A path family is a protocol recipe, never a claim about the retail brand. */
718
+ function recorderFamilyForPath(value) {
719
+ if (/^\/Streaming\/Channels\//i.test(value))
720
+ return 'hikvision';
721
+ if (/^\/cam\/realmonitor\?/i.test(value))
722
+ return 'dahua';
723
+ if (/^\/unicast\/c\d+\//i.test(value))
724
+ return 'uniview';
725
+ if (/^\/(?:\??chID=|ch\d+\/)/i.test(value))
726
+ return 'tvt';
727
+ if (/^\/user=[^&]*&password=[^&]*&channel=/i.test(value))
728
+ return 'xmeye';
729
+ return undefined;
730
+ }
731
+ /** Preserve an explicit one-based recorder input; an ONVIF list index is not it. */
732
+ function recorderInputForPath(value) {
733
+ const family = recorderFamilyForPath(value);
734
+ let raw;
735
+ if (family === 'hikvision')
736
+ raw = value.match(/^\/Streaming\/Channels\/(\d+)(?:[/?]|$)/i)?.[1];
737
+ else if (family === 'uniview')
738
+ raw = value.match(/^\/unicast\/c(\d+)\//i)?.[1];
739
+ else if (family === 'dahua')
740
+ raw = value.match(/[?&]channel=(\d+)(?:&|$)/i)?.[1];
741
+ else if (family === 'tvt')
742
+ raw = value.match(/(?:[?&]|\/)chID=(\d+)(?:&|$)/i)?.[1]
743
+ ?? value.match(/^\/ch(\d+)\//i)?.[1];
744
+ else if (family === 'xmeye')
745
+ raw = value.match(/&channel=(\d+)(?:&|$)/i)?.[1];
746
+ if (raw == null)
747
+ return undefined;
748
+ const input = family === 'hikvision' ? Math.floor(Number(raw) / 100) : Number(raw);
749
+ return Number.isSafeInteger(input) && input >= 1 && input <= 64 ? input : undefined;
750
+ }
751
+ // Cheap local dHash, using the already-declared pure JS JPEG decoder. Blank or
752
+ // undecodable frames provide no alias evidence and never trim channel counts.
753
+ function informativeProbeHash(base64) {
754
+ if (!base64)
755
+ return null;
756
+ try {
757
+ const image = (0, jpeg_js_1.decode)(Buffer.from(base64, 'base64'), {
758
+ useTArray: true, maxResolutionInMP: 4, maxMemoryUsageInMB: 32,
759
+ });
760
+ if (image.width < 9 || image.height < 8)
761
+ return null;
762
+ const luminance = [];
763
+ for (let y = 0; y < 8; y++)
764
+ for (let x = 0; x < 9; x++) {
765
+ let sum = 0;
766
+ let count = 0;
767
+ for (let py = Math.floor(y * image.height / 8); py < Math.floor((y + 1) * image.height / 8); py++) {
768
+ for (let px = Math.floor(x * image.width / 9); px < Math.floor((x + 1) * image.width / 9); px++) {
769
+ const offset = (py * image.width + px) * 4;
770
+ sum += image.data[offset] * 77 + image.data[offset + 1] * 150 + image.data[offset + 2] * 29;
771
+ count++;
772
+ }
773
+ }
774
+ luminance.push(sum / count);
775
+ }
776
+ let hash = 0n;
777
+ let ones = 0;
778
+ for (let y = 0; y < 8; y++)
779
+ for (let x = 0; x < 8; x++) {
780
+ const bit = luminance[y * 9 + x] > luminance[y * 9 + x + 1];
781
+ hash = (hash << 1n) | (bit ? 1n : 0n);
782
+ if (bit)
783
+ ones++;
784
+ }
785
+ return ones < 6 || ones > 58 ? null : hash;
786
+ }
787
+ catch {
788
+ return null;
789
+ }
790
+ }
791
+ function probeHashDistance(a, b) {
792
+ let difference = a ^ b;
793
+ let count = 0;
794
+ while (difference) {
795
+ difference &= difference - 1n;
796
+ count++;
797
+ }
798
+ return count;
799
+ }
717
800
  async function probeHost(target, opts = {}) {
718
801
  const host = target.host;
719
802
  const rtspPort = target.port ?? 554;
@@ -734,7 +817,11 @@ async function probeHost(target, opts = {}) {
734
817
  const results = [];
735
818
  const emit = async (r) => {
736
819
  const recorderResult = { ...r, sourceType: 'recorder' };
737
- results.push(recorderResult);
820
+ const existing = results.findIndex((entry) => entry.channelKey === r.channelKey);
821
+ if (existing < 0)
822
+ results.push(recorderResult);
823
+ else
824
+ results[existing] = recorderResult;
738
825
  if (opts.onResult)
739
826
  await opts.onResult(recorderResult);
740
827
  };
@@ -744,17 +831,101 @@ async function probeHost(target, opts = {}) {
744
831
  // ONVIF account while accepting the owner's normal login for RTSP.
745
832
  let serial = null;
746
833
  let brand = requestedBrand;
834
+ const automaticFamily = !requestedBrand || target.brandHintSource === 'discovery';
747
835
  let onvifProfiles = [];
748
836
  let onvifAvailable = false;
749
837
  let onvifAuthRejected = false;
750
838
  let rtspCredentialsProven = false;
839
+ const maxChannels = Math.min(opts.maxChannels ?? 32, 64);
840
+ const hinted = Number.isFinite(Number(target.channelHint)) ? Math.trunc(Number(target.channelHint)) : null;
841
+ let walkTo = hinted ? Math.min(hinted, maxChannels) : maxChannels;
842
+ // A requested count is an upper bound, never evidence of physical capacity.
843
+ let xmCapacityLookupAttempted = hinted === 1;
844
+ let xmIdentified = false;
845
+ const lookupXmCapacity = async () => {
846
+ if (xmCapacityLookupAttempted || !rtspCredentialsProven || budgetLeft() <= 200)
847
+ return;
848
+ xmCapacityLookupAttempted = true;
849
+ try {
850
+ const reply = await (opts.xmExchange ?? defaultXmExchange)(host, recorderRanking_1.XM_PORT, (0, recorderRanking_1.buildXmLoginFrame)({ username: target.username, password: target.password }), Math.min(1500, budgetLeft()));
851
+ const xm = reply ? (0, recorderRanking_1.parseXmLoginResponse)(reply) : null;
852
+ xmIdentified = xm?.ret === 100;
853
+ if (xmIdentified && xm?.channelCount != null)
854
+ walkTo = Math.min(walkTo, xm.channelCount);
855
+ }
856
+ catch {
857
+ // Separate management auth/availability must not erase a proven RTSP login.
858
+ }
859
+ };
860
+ let recoveryAttempted = false;
861
+ let familyRecovered = false;
862
+ const sampled = new Map();
863
+ const recoverFamily = async (firstChannel, secondChannel, useManagement = true, currentFamily) => {
864
+ // Different ONVIF tokens can advertise the same physical recorder input.
865
+ // Motion between captures cannot turn that one input into a paired proof.
866
+ if (firstChannel === secondChannel)
867
+ return null;
868
+ // One recovery pass, within the SAME host deadline and one stream at a time.
869
+ // Authenticate DVRIP only after RTSP success + alias evidence, never as a
870
+ // blind wrong-password probe or alongside normal ONVIF media enumeration.
871
+ if (useManagement)
872
+ await lookupXmCapacity();
873
+ const families = !automaticFamily ? [requestedBrand] : [...new Set([
874
+ ...(xmIdentified ? ['xmeye'] : []), ...(brand ? [brand] : []),
875
+ 'xmeye', 'hikvision', 'tvt', 'dahua', 'uniview',
876
+ ])];
877
+ // Recovery must leave most of the host deadline for the remaining inputs.
878
+ const recoveryDeadline = Date.now() + Math.min(25000, Math.max(0, budgetLeft() / 3));
879
+ for (const family of families) {
880
+ if (family === currentFamily || secondChannel > (useManagement ? walkTo : 64))
881
+ continue;
882
+ const hashes = [];
883
+ const candidateIndices = new Map();
884
+ for (const channel of [firstChannel, secondChannel]) {
885
+ for (const [candidateIndex, candidate] of brandPathCandidates(family, channel, target).entries()) {
886
+ const recoveryLeft = Math.min(budgetLeft(), recoveryDeadline - Date.now());
887
+ if (recoveryLeft <= 0)
888
+ return null;
889
+ // Mixed OEM presets include other families. Do not relabel a Dahua
890
+ // proof as TVT simply because it was inside that preset's tail.
891
+ if (recorderFamilyForPath(candidate) !== family)
892
+ continue;
893
+ const wire = materializeCredentialPathTemplate(candidate, target.username, target.password);
894
+ const proof = await grabOneFrameAnyTransport(buildRtspUrl(host, rtspPort, wire, target.username, target.password), {
895
+ ffmpegPath: opts.ffmpegPath,
896
+ timeoutMs: Math.min(grabTimeoutMs, Math.max(1, recoveryLeft)),
897
+ spawner: opts.spawner,
898
+ });
899
+ if (proof.ok) {
900
+ const hash = informativeProbeHash(proof.jpegBase64);
901
+ if (hash != null) {
902
+ hashes.push(hash);
903
+ candidateIndices.set(channel, candidateIndex);
904
+ }
905
+ break;
906
+ }
907
+ if (['nvr_busy', 'rtsp_unreachable', 'rtsp_timeout'].includes(proof.failureClass || ''))
908
+ return null;
909
+ }
910
+ if (hashes.length === 0)
911
+ break;
912
+ }
913
+ // A single playable frame is insufficient; both requested channel paths
914
+ // must produce structurally distinct, informative views before switching.
915
+ if (hashes.length === 2 && probeHashDistance(hashes[0], hashes[1]) > 10) {
916
+ return { brand: family, candidateIndices,
917
+ preferredCandidateIndex: candidateIndices.values().next().value ?? 0 };
918
+ }
919
+ }
920
+ return null;
921
+ };
751
922
  const onvifPorts = target.onvifPort ? [target.onvifPort] : [80, 8899];
752
923
  for (const onvifPort of onvifPorts) {
753
924
  const client = new OnvifClient_1.OnvifClient({ host, port: onvifPort, username: target.username, password: target.password, timeoutMs: 5000 }, opts.poster);
754
925
  try {
755
926
  const info = await client.getDeviceInformation();
756
927
  serial = info.serialNumber;
757
- if (!brand && info.manufacturer) {
928
+ if (automaticFamily && info.manufacturer) {
758
929
  brand = normalizeRecorderBrandHint([info.manufacturer, info.model].filter(Boolean).join(' '));
759
930
  }
760
931
  applyResolvedBrandBudgets(brand);
@@ -799,13 +970,22 @@ async function probeHost(target, opts = {}) {
799
970
  break;
800
971
  let preferAmcrestRecorderProxy = false;
801
972
  let preferXmeyeRecorderProxy = false;
973
+ let recoveredRecorderProxy = null;
974
+ // URI input numbers can be sparse (9/12), while ONVIF source keys and
975
+ // existing result ordinals must remain stable. Opaque URIs retain the
976
+ // previous ordinal fallback; never infer a number from an opaque token.
977
+ const recorderInputs = new Map(entries.map(([src, { uri }], index) => [src, recorderInputForPath(pathTemplateOf(uri)) ?? index + 1]));
802
978
  const validateEntry = async ([src, { profile, uri }], channel) => {
803
979
  if (budgetLeft() <= 0)
804
980
  return 'continue';
805
981
  let selectedPath = credentialFreePathTemplate(pathTemplateOf(uri), brand);
806
- const recorderProxyPath = brandPathCandidates(brand, channel, target)[0];
982
+ const recorderChannel = recorderInputs.get(src) ?? channel;
983
+ const recorderProxyCandidates = brandPathCandidates(brand, recorderChannel, target);
984
+ const preferredIndex = recoveredRecorderProxy?.candidateIndices.get(recorderChannel)
985
+ ?? recoveredRecorderProxy?.preferredCandidateIndex ?? 0;
986
+ const recorderProxyPath = recorderProxyCandidates[preferredIndex] ?? recorderProxyCandidates[0];
807
987
  const skipKnownBadOnvifUri = recorderProxyPath != null &&
808
- ((brand === 'amcrest-recorder' && preferAmcrestRecorderProxy) ||
988
+ (recoveredRecorderProxy != null || (brand === 'amcrest-recorder' && preferAmcrestRecorderProxy) ||
809
989
  (brand === 'xmeye' && preferXmeyeRecorderProxy));
810
990
  let grab;
811
991
  if (skipKnownBadOnvifUri) {
@@ -837,7 +1017,7 @@ async function probeHost(target, opts = {}) {
837
1017
  if (!grab.ok && grab.failureClass !== 'empty_channel' && brand === 'xmeye') {
838
1018
  let strongest = grab;
839
1019
  let strongestPath = selectedPath;
840
- for (const candidatePath of brandPathCandidates(brand, channel, target)) {
1020
+ for (const candidatePath of brandPathCandidates(brand, recorderChannel, target)) {
841
1021
  if (budgetLeft() <= 0)
842
1022
  break;
843
1023
  const candidateTemplate = credentialFreePathTemplate(candidatePath, brand);
@@ -911,14 +1091,22 @@ async function probeHost(target, opts = {}) {
911
1091
  // remaining channels. Keep this model-scoped: an invented fallback on
912
1092
  // other vendors can turn a wrong path into a misleading 401 and lock
913
1093
  // the owner's account.
914
- if (!grab.ok && grab.failureClass !== 'empty_channel' && brand === 'amcrest-recorder') {
1094
+ // Evidence-based family recovery may prove a non-first variant.
1095
+ // Keep that variant per input; later inputs can try the other proven
1096
+ // family's variants, without widening ordinary ONVIF behavior.
1097
+ const retryRecoveredVariant = recoveredRecorderProxy != null && brand !== 'xmeye'
1098
+ && !['nvr_busy', 'rtsp_unreachable', 'rtsp_timeout'].includes(grab.failureClass || '');
1099
+ if (!grab.ok && grab.failureClass !== 'empty_channel' &&
1100
+ (brand === 'amcrest-recorder' || retryRecoveredVariant)) {
915
1101
  let strongest = grab;
916
1102
  let strongestPath = selectedPath;
917
- for (const candidatePath of brandPathCandidates(brand, channel, target)) {
1103
+ for (const candidatePath of recorderProxyCandidates) {
918
1104
  if (budgetLeft() <= 0)
919
1105
  break;
920
1106
  if (candidatePath === selectedPath)
921
1107
  continue;
1108
+ if (recoveredRecorderProxy && recorderFamilyForPath(candidatePath) !== brand)
1109
+ continue;
922
1110
  let candidate = await grabOneFrameAnyTransport(buildRtspUrl(host, rtspPort, candidatePath, target.username, target.password), {
923
1111
  ffmpegPath: opts.ffmpegPath,
924
1112
  timeoutMs: Math.min(grabTimeoutMs, Math.max(2000, budgetLeft())),
@@ -926,7 +1114,8 @@ async function probeHost(target, opts = {}) {
926
1114
  });
927
1115
  if (candidate.ok || candidate.failureClass === 'decode_error' || candidate.failureClass === 'empty_channel') {
928
1116
  rtspCredentialsProven = true;
929
- preferAmcrestRecorderProxy = true;
1117
+ if (brand === 'amcrest-recorder')
1118
+ preferAmcrestRecorderProxy = true;
930
1119
  }
931
1120
  if (candidate.failureClass === 'rtsp_auth' && !rtspCredentialsProven) {
932
1121
  await emit({
@@ -956,12 +1145,18 @@ async function probeHost(target, opts = {}) {
956
1145
  if (candidate.ok || candidate.failureClass === 'empty_channel') {
957
1146
  strongest = candidate;
958
1147
  strongestPath = credentialFreePathTemplate(candidatePath, brand);
1148
+ if (candidate.ok && recoveredRecorderProxy) {
1149
+ recoveredRecorderProxy.candidateIndices.set(recorderChannel, recorderProxyCandidates.indexOf(candidatePath));
1150
+ }
959
1151
  break;
960
1152
  }
961
1153
  if (failureSignalRank(candidate.failureClass) >= failureSignalRank(strongest.failureClass)) {
962
1154
  strongest = candidate;
963
1155
  strongestPath = credentialFreePathTemplate(candidatePath, brand);
964
1156
  }
1157
+ if (recoveredRecorderProxy &&
1158
+ ['nvr_busy', 'rtsp_unreachable', 'rtsp_timeout'].includes(candidate.failureClass || ''))
1159
+ break;
965
1160
  }
966
1161
  grab = strongest;
967
1162
  selectedPath = strongestPath;
@@ -1022,6 +1217,33 @@ async function probeHost(target, opts = {}) {
1022
1217
  // profile and lock the recorder account. Once proven, honor the caller's
1023
1218
  // bounded concurrency for the remaining channels.
1024
1219
  let nextEntry = 0;
1220
+ if (!normalizeOperatorPathHint(target.pathHint) && entries.length > 1 &&
1221
+ (automaticFamily || brandPathCandidates(brand, 1, target).length > 0)) {
1222
+ // Distinct ONVIF tokens/URIs can still point to the default camera.
1223
+ // Compare two actual streams before trusting that advertised recipe.
1224
+ for (; nextEntry < 2; nextEntry++) {
1225
+ if (await validateEntry(entries[nextEntry], nextEntry + 1) === 'abort_auth')
1226
+ return results;
1227
+ }
1228
+ const first = results.find(result => result.channel === 1 && result.status === 'validated');
1229
+ const second = results.find(result => result.channel === 2 && result.status === 'validated');
1230
+ const a = informativeProbeHash(first?.thumbnailBase64);
1231
+ const b = informativeProbeHash(second?.thumbnailBase64);
1232
+ if (a != null && b != null && probeHashDistance(a, b) <= 10) {
1233
+ const recovered = await recoverFamily(recorderInputs.get(entries[0][0]), recorderInputs.get(entries[1][0]), false, recorderFamilyForPath(first?.pathTemplate || ''));
1234
+ if (recovered) {
1235
+ for (const prior of [...results]) {
1236
+ if (prior.status === 'validated')
1237
+ await emit({ ...prior, status: 'failed', failureClass: 'bad_path',
1238
+ message: 'Checking a better recorder path for this channel.' });
1239
+ }
1240
+ brand = recovered.brand;
1241
+ applyResolvedBrandBudgets(brand);
1242
+ recoveredRecorderProxy = recovered;
1243
+ nextEntry = 0;
1244
+ }
1245
+ }
1246
+ }
1025
1247
  while (nextEntry < entries.length && !rtspCredentialsProven) {
1026
1248
  const outcome = await validateEntry(entries[nextEntry], nextEntry + 1);
1027
1249
  nextEntry++;
@@ -1094,10 +1316,7 @@ async function probeHost(target, opts = {}) {
1094
1316
  // ── Stage 2b: brand-candidate walk (no ONVIF enumeration available). The
1095
1317
  // FIRST RTSP auth rejection trips the breaker (≤1 RTSP auth touch beyond the
1096
1318
  // ONVIF attempt). Channels walk until maxConsecutiveDead in a row.
1097
- const maxDead = opts.maxConsecutiveDead ?? (brand === 'xmeye' ? 8 : 4);
1098
- const maxChannels = Math.min(opts.maxChannels ?? 32, 64);
1099
- const hinted = Number.isFinite(Number(target.channelHint)) ? Math.trunc(Number(target.channelHint)) : null;
1100
- let walkTo = hinted ? Math.min(hinted, maxChannels) : maxChannels;
1319
+ let maxDead = opts.maxConsecutiveDead ?? (brand === 'xmeye' ? 8 : 4);
1101
1320
  // The operator's own path goes FIRST, ahead of every brand guess, and only on
1102
1321
  // channel 1: a hand-typed path names ONE stream, so walking it across channels
1103
1322
  // would just re-probe the same URL. If it fails the walk continues into the
@@ -1124,7 +1343,6 @@ async function probeHost(target, opts = {}) {
1124
1343
  return results;
1125
1344
  }
1126
1345
  let consecutiveDead = 0;
1127
- let xmCapacityLookupAttempted = hinted !== null;
1128
1346
  // A custom path is its OWN camera. The non-ONVIF channelKey is a hash of
1129
1347
  // host:port:channel, and every operator path is forced onto channel 1 — so two
1130
1348
  // different custom paths on one recorder (`/stream/camera2`, `/stream/camera3`)
@@ -1135,14 +1353,14 @@ async function probeHost(target, opts = {}) {
1135
1353
  const keyForPath = (path, ch) => (operatorPath && path === operatorPath
1136
1354
  ? `nvr:${(0, crypto_1.createHash)('sha1').update(`${host}:${rtspPort}:${path}`).digest('hex').slice(0, 16)}`
1137
1355
  : channelKeyFor({ serial, host, port: rtspPort, channel: ch }));
1138
- for (let ch = 1; ch <= walkTo; ch++) {
1356
+ channelWalk: for (let ch = 1; ch <= walkTo; ch++) {
1139
1357
  if (budgetLeft() <= 0)
1140
1358
  break;
1141
1359
  if (!hinted && consecutiveDead >= maxDead)
1142
1360
  break;
1143
1361
  const key = channelKeyFor({ serial, host, port: rtspPort, channel: ch });
1144
1362
  let channelResult = null;
1145
- const candidates = ch === 1 ? firstCandidates : brandPathCandidates(brand, ch, target);
1363
+ const candidates = ch === 1 && !familyRecovered ? firstCandidates : brandPathCandidates(brand, ch, target);
1146
1364
  if (candidates.length === 0)
1147
1365
  break;
1148
1366
  for (const path of candidates) {
@@ -1165,32 +1383,43 @@ async function probeHost(target, opts = {}) {
1165
1383
  // paths, so a later 401 must not erase an earlier stream success.
1166
1384
  rtspCredentialsProven = true;
1167
1385
  }
1168
- if (brand === 'xmeye' &&
1169
- !xmCapacityLookupAttempted &&
1170
- rtspCredentialsProven &&
1171
- budgetLeft() > 200) {
1172
- xmCapacityLookupAttempted = true;
1173
- try {
1174
- // Some XM firmware aliases every unsupported RTSP channel to channel
1175
- // 1. Do not infer capacity from thumbnails: genuine offline inputs can
1176
- // share the same coloured VIDEO LOSS slate. Once RTSP has proved the
1177
- // supplied login, use exactly one authenticated DVRIP exchange and
1178
- // trust only the recorder's own ChannelNum self-report.
1179
- const timeoutMs = Math.min(1500, budgetLeft());
1180
- const reply = await (opts.xmExchange ?? defaultXmExchange)(host, recorderRanking_1.XM_PORT, (0, recorderRanking_1.buildXmLoginFrame)({ username: target.username, password: target.password }), timeoutMs);
1181
- const xm = reply ? (0, recorderRanking_1.parseXmLoginResponse)(reply) : null;
1182
- if (xm?.ret === 100 && xm.channelCount != null) {
1183
- walkTo = Math.min(walkTo, xm.channelCount);
1184
- }
1185
- }
1186
- catch {
1187
- // Capacity lookup is additive. If the management port is unavailable
1188
- // or uses a separate account, preserve the previous bounded RTSP walk.
1189
- }
1386
+ if (grab.ok && automaticFamily && path !== operatorPath) {
1387
+ brand = recorderFamilyForPath(path) || brand;
1388
+ applyResolvedBrandBudgets(brand);
1190
1389
  }
1390
+ if (brand === 'xmeye')
1391
+ await lookupXmCapacity();
1191
1392
  if (ch > walkTo)
1192
1393
  break;
1193
1394
  if (grab.ok) {
1395
+ if (automaticFamily && !operatorPath && !recoveryAttempted && walkTo > 1) {
1396
+ const hash = informativeProbeHash(grab.jpegBase64);
1397
+ const match = hash == null ? undefined : [...sampled.entries()].find(([, prior]) => probeHashDistance(prior, hash) <= 10);
1398
+ if (hash != null)
1399
+ sampled.set(ch, hash);
1400
+ if (match) {
1401
+ recoveryAttempted = true;
1402
+ const recovered = await recoverFamily(match[0], ch, true, brand);
1403
+ if (recovered) {
1404
+ // Retract tentative old recipes before revalidating. The owner
1405
+ // projection and connector checkpoint both upsert the same stable
1406
+ // channel keys, so no camera is silently left on the alias path.
1407
+ for (const prior of [...results]) {
1408
+ if (prior.status === 'validated')
1409
+ await emit({ ...prior, status: 'failed', failureClass: 'bad_path',
1410
+ message: 'Checking a better recorder path for this channel.' });
1411
+ }
1412
+ brand = recovered.brand;
1413
+ familyRecovered = true;
1414
+ applyResolvedBrandBudgets(brand);
1415
+ maxDead = opts.maxConsecutiveDead ?? (brand === 'xmeye' ? 8 : 4);
1416
+ sampled.clear();
1417
+ consecutiveDead = 0;
1418
+ ch = 0;
1419
+ continue channelWalk;
1420
+ }
1421
+ }
1422
+ }
1194
1423
  channelResult = {
1195
1424
  channelKey: keyForPath(path, ch),
1196
1425
  status: 'validated',