@trillboards/edge-sdk 0.2.160 → 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.
Files changed (57) hide show
  1. package/deploy/macos/TrillboardsSetupApp.m +36 -0
  2. package/deploy/macos/pair.command +13 -0
  3. package/deploy/windows/e2e/test-local-sense.ps1 +13 -1
  4. package/deploy/windows/e2e/test-recorder-family.ps1 +85 -0
  5. package/deploy/windows/setup-litertlm.ps1 +22 -10
  6. package/deploy/windows/trillboards-pair.cmd +8 -0
  7. package/deploy/windows/trillboards-setup.ps1 +68 -17
  8. package/dist/ChannelProber.d.ts +3 -7
  9. package/dist/ChannelProber.d.ts.map +1 -1
  10. package/dist/ChannelProber.js +270 -41
  11. package/dist/ChannelProber.js.map +1 -1
  12. package/dist/EdgeAgent.js +1 -1
  13. package/dist/InstallerOnboardingClient.d.ts +1 -0
  14. package/dist/InstallerOnboardingClient.d.ts.map +1 -1
  15. package/dist/InstallerOnboardingClient.js +10 -0
  16. package/dist/InstallerOnboardingClient.js.map +1 -1
  17. package/dist/LiteRtVlmProvider.d.ts +2 -1
  18. package/dist/LiteRtVlmProvider.d.ts.map +1 -1
  19. package/dist/LiteRtVlmProvider.js +30 -4
  20. package/dist/LiteRtVlmProvider.js.map +1 -1
  21. package/dist/SetupSessionClient.d.ts +6 -0
  22. package/dist/SetupSessionClient.d.ts.map +1 -1
  23. package/dist/SetupSessionClient.js +1 -0
  24. package/dist/SetupSessionClient.js.map +1 -1
  25. package/dist/autoSense.d.ts +10 -1
  26. package/dist/autoSense.d.ts.map +1 -1
  27. package/dist/autoSense.js +135 -5
  28. package/dist/autoSense.js.map +1 -1
  29. package/dist/cli.d.ts.map +1 -1
  30. package/dist/cli.js +24 -1
  31. package/dist/cli.js.map +1 -1
  32. package/dist/connectorCameraSetup.d.ts +26 -0
  33. package/dist/connectorCameraSetup.d.ts.map +1 -0
  34. package/dist/connectorCameraSetup.js +225 -0
  35. package/dist/connectorCameraSetup.js.map +1 -0
  36. package/dist/dataDir.d.ts +5 -0
  37. package/dist/dataDir.d.ts.map +1 -1
  38. package/dist/dataDir.js +9 -0
  39. package/dist/dataDir.js.map +1 -1
  40. package/dist/diagnose.d.ts +1 -1
  41. package/dist/diagnose.js +1 -1
  42. package/dist/gemmaModelOta.d.ts.map +1 -1
  43. package/dist/gemmaModelOta.js +1 -5
  44. package/dist/gemmaModelOta.js.map +1 -1
  45. package/dist/installerOnboardingMode.d.ts +1 -0
  46. package/dist/installerOnboardingMode.d.ts.map +1 -1
  47. package/dist/installerOnboardingMode.js +25 -5
  48. package/dist/installerOnboardingMode.js.map +1 -1
  49. package/dist/setupMode.d.ts +38 -0
  50. package/dist/setupMode.d.ts.map +1 -1
  51. package/dist/setupMode.js +218 -49
  52. package/dist/setupMode.js.map +1 -1
  53. package/dist/setupProgress.d.ts +1 -0
  54. package/dist/setupProgress.d.ts.map +1 -1
  55. package/dist/setupProgress.js +2 -0
  56. package/dist/setupProgress.js.map +1 -1
  57. package/package.json +1 -1
@@ -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',