matter-all-in-one-addon 1.8.21

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 (244) hide show
  1. package/README.md +183 -0
  2. package/dist/camera/ai/camera-ai-detector.d.ts +44 -0
  3. package/dist/camera/ai/camera-ai-detector.js +329 -0
  4. package/dist/camera/ai/camera-ai-detector.js.map +1 -0
  5. package/dist/camera/camera-capabilities.d.ts +13 -0
  6. package/dist/camera/camera-capabilities.js +186 -0
  7. package/dist/camera/camera-capabilities.js.map +1 -0
  8. package/dist/camera/camera-source-resolver.d.ts +18 -0
  9. package/dist/camera/camera-source-resolver.js +187 -0
  10. package/dist/camera/camera-source-resolver.js.map +1 -0
  11. package/dist/camera/camera-types.d.ts +124 -0
  12. package/dist/camera/camera-types.js +8 -0
  13. package/dist/camera/camera-types.js.map +1 -0
  14. package/dist/camera/cameraui/cameraui-client.d.ts +54 -0
  15. package/dist/camera/cameraui/cameraui-client.js +698 -0
  16. package/dist/camera/cameraui/cameraui-client.js.map +1 -0
  17. package/dist/camera/cameraui/cameraui-homekit-bridge.d.ts +21 -0
  18. package/dist/camera/cameraui/cameraui-homekit-bridge.js +343 -0
  19. package/dist/camera/cameraui/cameraui-homekit-bridge.js.map +1 -0
  20. package/dist/camera/cameraui/cameraui-storage.d.ts +17 -0
  21. package/dist/camera/cameraui/cameraui-storage.js +916 -0
  22. package/dist/camera/cameraui/cameraui-storage.js.map +1 -0
  23. package/dist/camera/cameraui/cameraui-types.d.ts +89 -0
  24. package/dist/camera/cameraui/cameraui-types.js +5 -0
  25. package/dist/camera/cameraui/cameraui-types.js.map +1 -0
  26. package/dist/camera/homekit/ffmpeg-helper.d.ts +88 -0
  27. package/dist/camera/homekit/ffmpeg-helper.js +673 -0
  28. package/dist/camera/homekit/ffmpeg-helper.js.map +1 -0
  29. package/dist/camera/homekit/fmp4-parser.d.ts +48 -0
  30. package/dist/camera/homekit/fmp4-parser.js +156 -0
  31. package/dist/camera/homekit/fmp4-parser.js.map +1 -0
  32. package/dist/camera/homekit/hevc-eligibility.d.ts +16 -0
  33. package/dist/camera/homekit/hevc-eligibility.js +153 -0
  34. package/dist/camera/homekit/hevc-eligibility.js.map +1 -0
  35. package/dist/camera/homekit/homekit-camera-recording.delegate.d.ts +73 -0
  36. package/dist/camera/homekit/homekit-camera-recording.delegate.js +445 -0
  37. package/dist/camera/homekit/homekit-camera-recording.delegate.js.map +1 -0
  38. package/dist/camera/homekit/homekit-camera-stream.delegate.d.ts +47 -0
  39. package/dist/camera/homekit/homekit-camera-stream.delegate.js +833 -0
  40. package/dist/camera/homekit/homekit-camera-stream.delegate.js.map +1 -0
  41. package/dist/camera/homekit/homekit-camera.accessory.d.ts +53 -0
  42. package/dist/camera/homekit/homekit-camera.accessory.js +697 -0
  43. package/dist/camera/homekit/homekit-camera.accessory.js.map +1 -0
  44. package/dist/camera/matter/camera-endpoint.builder.d.ts +7 -0
  45. package/dist/camera/matter/camera-endpoint.builder.js +127 -0
  46. package/dist/camera/matter/camera-endpoint.builder.js.map +1 -0
  47. package/dist/camera/matter/camera-session-manager.d.ts +46 -0
  48. package/dist/camera/matter/camera-session-manager.js +120 -0
  49. package/dist/camera/matter/camera-session-manager.js.map +1 -0
  50. package/dist/camera/matter/camera-webrtc-adapter.d.ts +62 -0
  51. package/dist/camera/matter/camera-webrtc-adapter.js +298 -0
  52. package/dist/camera/matter/camera-webrtc-adapter.js.map +1 -0
  53. package/dist/camera/motion/ffmpeg-motion-detector.d.ts +46 -0
  54. package/dist/camera/motion/ffmpeg-motion-detector.js +200 -0
  55. package/dist/camera/motion/ffmpeg-motion-detector.js.map +1 -0
  56. package/dist/camera/nest/nest-camera-adapter.d.ts +38 -0
  57. package/dist/camera/nest/nest-camera-adapter.js +109 -0
  58. package/dist/camera/nest/nest-camera-adapter.js.map +1 -0
  59. package/dist/camera/scrypted/scrypted-camera-card.d.ts +39 -0
  60. package/dist/camera/scrypted/scrypted-camera-card.js +38 -0
  61. package/dist/camera/scrypted/scrypted-camera-card.js.map +1 -0
  62. package/dist/camera/scrypted/scrypted-camera-detail.d.ts +33 -0
  63. package/dist/camera/scrypted/scrypted-camera-detail.js +34 -0
  64. package/dist/camera/scrypted/scrypted-camera-detail.js.map +1 -0
  65. package/dist/camera/scrypted/scrypted-camera-discovery-adapter.d.ts +17 -0
  66. package/dist/camera/scrypted/scrypted-camera-discovery-adapter.js +24 -0
  67. package/dist/camera/scrypted/scrypted-camera-discovery-adapter.js.map +1 -0
  68. package/dist/camera/scrypted/scrypted-camera-normalizer.d.ts +44 -0
  69. package/dist/camera/scrypted/scrypted-camera-normalizer.js +44 -0
  70. package/dist/camera/scrypted/scrypted-camera-normalizer.js.map +1 -0
  71. package/dist/camera/scrypted/scrypted-camera-policy.d.ts +11 -0
  72. package/dist/camera/scrypted/scrypted-camera-policy.js +13 -0
  73. package/dist/camera/scrypted/scrypted-camera-policy.js.map +1 -0
  74. package/dist/camera/scrypted/scrypted-camera-presentation.d.ts +13 -0
  75. package/dist/camera/scrypted/scrypted-camera-presentation.js +23 -0
  76. package/dist/camera/scrypted/scrypted-camera-presentation.js.map +1 -0
  77. package/dist/camera/scrypted/scrypted-client-discovery-adapter.d.ts +6 -0
  78. package/dist/camera/scrypted/scrypted-client-discovery-adapter.js +12 -0
  79. package/dist/camera/scrypted/scrypted-client-discovery-adapter.js.map +1 -0
  80. package/dist/camera/scrypted/scrypted-client.d.ts +152 -0
  81. package/dist/camera/scrypted/scrypted-client.js +1170 -0
  82. package/dist/camera/scrypted/scrypted-client.js.map +1 -0
  83. package/dist/camera/scrypted/scrypted-crypto.d.ts +21 -0
  84. package/dist/camera/scrypted/scrypted-crypto.js +90 -0
  85. package/dist/camera/scrypted/scrypted-crypto.js.map +1 -0
  86. package/dist/camera/scrypted/scrypted-discovery-provider.d.ts +9 -0
  87. package/dist/camera/scrypted/scrypted-discovery-provider.js +25 -0
  88. package/dist/camera/scrypted/scrypted-discovery-provider.js.map +1 -0
  89. package/dist/camera/scrypted/scrypted-homekit-bridge.d.ts +12 -0
  90. package/dist/camera/scrypted/scrypted-homekit-bridge.js +214 -0
  91. package/dist/camera/scrypted/scrypted-homekit-bridge.js.map +1 -0
  92. package/dist/camera/scrypted/scrypted-matter-bridge.d.ts +36 -0
  93. package/dist/camera/scrypted/scrypted-matter-bridge.js +226 -0
  94. package/dist/camera/scrypted/scrypted-matter-bridge.js.map +1 -0
  95. package/dist/camera/scrypted/scrypted-reconnect-manager.d.ts +40 -0
  96. package/dist/camera/scrypted/scrypted-reconnect-manager.js +353 -0
  97. package/dist/camera/scrypted/scrypted-reconnect-manager.js.map +1 -0
  98. package/dist/camera/scrypted/scrypted-runtime-connector.d.ts +7 -0
  99. package/dist/camera/scrypted/scrypted-runtime-connector.js +17 -0
  100. package/dist/camera/scrypted/scrypted-runtime-connector.js.map +1 -0
  101. package/dist/camera/scrypted/scrypted-runtime-facade.d.ts +13 -0
  102. package/dist/camera/scrypted/scrypted-runtime-facade.js +29 -0
  103. package/dist/camera/scrypted/scrypted-runtime-facade.js.map +1 -0
  104. package/dist/camera/scrypted/scrypted-runtime-ingest.d.ts +5 -0
  105. package/dist/camera/scrypted/scrypted-runtime-ingest.js +54 -0
  106. package/dist/camera/scrypted/scrypted-runtime-ingest.js.map +1 -0
  107. package/dist/camera/scrypted/scrypted-storage.d.ts +95 -0
  108. package/dist/camera/scrypted/scrypted-storage.js +698 -0
  109. package/dist/camera/scrypted/scrypted-storage.js.map +1 -0
  110. package/dist/camera/scrypted/scrypted-stream-validator.d.ts +46 -0
  111. package/dist/camera/scrypted/scrypted-stream-validator.js +412 -0
  112. package/dist/camera/scrypted/scrypted-stream-validator.js.map +1 -0
  113. package/dist/camera/scrypted/scrypted-types.d.ts +354 -0
  114. package/dist/camera/scrypted/scrypted-types.js +6 -0
  115. package/dist/camera/scrypted/scrypted-types.js.map +1 -0
  116. package/dist/converters/binary_sensor.converter.d.ts +18 -0
  117. package/dist/converters/binary_sensor.converter.js +21 -0
  118. package/dist/converters/binary_sensor.converter.js.map +1 -0
  119. package/dist/converters/camera.converter.d.ts +18 -0
  120. package/dist/converters/camera.converter.js +24 -0
  121. package/dist/converters/camera.converter.js.map +1 -0
  122. package/dist/converters/climate.converter.d.ts +21 -0
  123. package/dist/converters/climate.converter.js +55 -0
  124. package/dist/converters/climate.converter.js.map +1 -0
  125. package/dist/converters/cover.converter.d.ts +14 -0
  126. package/dist/converters/cover.converter.js +22 -0
  127. package/dist/converters/cover.converter.js.map +1 -0
  128. package/dist/converters/energy_tariff.converter.d.ts +10 -0
  129. package/dist/converters/energy_tariff.converter.js +12 -0
  130. package/dist/converters/energy_tariff.converter.js.map +1 -0
  131. package/dist/converters/fan.converter.d.ts +233 -0
  132. package/dist/converters/fan.converter.js +353 -0
  133. package/dist/converters/fan.converter.js.map +1 -0
  134. package/dist/converters/index.d.ts +14 -0
  135. package/dist/converters/index.js +15 -0
  136. package/dist/converters/index.js.map +1 -0
  137. package/dist/converters/light.converter.d.ts +26 -0
  138. package/dist/converters/light.converter.js +36 -0
  139. package/dist/converters/light.converter.js.map +1 -0
  140. package/dist/converters/lock.converter.d.ts +20 -0
  141. package/dist/converters/lock.converter.js +29 -0
  142. package/dist/converters/lock.converter.js.map +1 -0
  143. package/dist/converters/sensor.converter.d.ts +18 -0
  144. package/dist/converters/sensor.converter.js +33 -0
  145. package/dist/converters/sensor.converter.js.map +1 -0
  146. package/dist/converters/soil_sensor.converter.d.ts +14 -0
  147. package/dist/converters/soil_sensor.converter.js +21 -0
  148. package/dist/converters/soil_sensor.converter.js.map +1 -0
  149. package/dist/converters/vacuum.converter.d.ts +168 -0
  150. package/dist/converters/vacuum.converter.js +288 -0
  151. package/dist/converters/vacuum.converter.js.map +1 -0
  152. package/dist/device-profiles.d.ts +14 -0
  153. package/dist/device-profiles.js +245 -0
  154. package/dist/device-profiles.js.map +1 -0
  155. package/dist/device-registry.d.ts +58 -0
  156. package/dist/device-registry.js +288 -0
  157. package/dist/device-registry.js.map +1 -0
  158. package/dist/entities/base.entity.d.ts +40 -0
  159. package/dist/entities/base.entity.js +826 -0
  160. package/dist/entities/base.entity.js.map +1 -0
  161. package/dist/entities/camera.entity.d.ts +48 -0
  162. package/dist/entities/camera.entity.js +127 -0
  163. package/dist/entities/camera.entity.js.map +1 -0
  164. package/dist/entities/closure.entity.d.ts +9 -0
  165. package/dist/entities/closure.entity.js +52 -0
  166. package/dist/entities/closure.entity.js.map +1 -0
  167. package/dist/entities/composite-device.entity.d.ts +61 -0
  168. package/dist/entities/composite-device.entity.js +986 -0
  169. package/dist/entities/composite-device.entity.js.map +1 -0
  170. package/dist/entities/cooktop.entity.d.ts +20 -0
  171. package/dist/entities/cooktop.entity.js +59 -0
  172. package/dist/entities/cooktop.entity.js.map +1 -0
  173. package/dist/entities/energy_tariff.entity.d.ts +7 -0
  174. package/dist/entities/energy_tariff.entity.js +32 -0
  175. package/dist/entities/energy_tariff.entity.js.map +1 -0
  176. package/dist/entities/humidifier.entity.d.ts +27 -0
  177. package/dist/entities/humidifier.entity.js +187 -0
  178. package/dist/entities/humidifier.entity.js.map +1 -0
  179. package/dist/entities/lock.entity.d.ts +12 -0
  180. package/dist/entities/lock.entity.js +58 -0
  181. package/dist/entities/lock.entity.js.map +1 -0
  182. package/dist/entities/media-player.entity.d.ts +13 -0
  183. package/dist/entities/media-player.entity.js +52 -0
  184. package/dist/entities/media-player.entity.js.map +1 -0
  185. package/dist/entities/oven.entity.d.ts +20 -0
  186. package/dist/entities/oven.entity.js +112 -0
  187. package/dist/entities/oven.entity.js.map +1 -0
  188. package/dist/entities/pet_feeder.entity.d.ts +28 -0
  189. package/dist/entities/pet_feeder.entity.js +67 -0
  190. package/dist/entities/pet_feeder.entity.js.map +1 -0
  191. package/dist/entities/soil_sensor.entity.d.ts +7 -0
  192. package/dist/entities/soil_sensor.entity.js +40 -0
  193. package/dist/entities/soil_sensor.entity.js.map +1 -0
  194. package/dist/entities/vacuum.entity.d.ts +37 -0
  195. package/dist/entities/vacuum.entity.js +352 -0
  196. package/dist/entities/vacuum.entity.js.map +1 -0
  197. package/dist/frontend/assets/index-DPXu3al2.js +26 -0
  198. package/dist/frontend/assets/index-DalMl4eS.css +1 -0
  199. package/dist/frontend/assets/logo-B_gEBugV.png +0 -0
  200. package/dist/frontend/index.html +14 -0
  201. package/dist/frontend/logo.png +0 -0
  202. package/dist/homeAssistant.d.ts +1268 -0
  203. package/dist/homeAssistant.js +1623 -0
  204. package/dist/homeAssistant.js.map +1 -0
  205. package/dist/homekit.compat.d.ts +40 -0
  206. package/dist/homekit.compat.js +43 -0
  207. package/dist/homekit.compat.js.map +1 -0
  208. package/dist/index.d.ts +7 -0
  209. package/dist/index.js +31 -0
  210. package/dist/index.js.map +1 -0
  211. package/dist/mqtt/mqtt-client.d.ts +33 -0
  212. package/dist/mqtt/mqtt-client.js +138 -0
  213. package/dist/mqtt/mqtt-client.js.map +1 -0
  214. package/dist/mqtt/mqtt.entity.d.ts +30 -0
  215. package/dist/mqtt/mqtt.entity.js +286 -0
  216. package/dist/mqtt/mqtt.entity.js.map +1 -0
  217. package/dist/platform.d.ts +318 -0
  218. package/dist/platform.js +6144 -0
  219. package/dist/platform.js.map +1 -0
  220. package/dist/proxy.d.ts +1 -0
  221. package/dist/proxy.js +226 -0
  222. package/dist/proxy.js.map +1 -0
  223. package/dist/utils/ha-discovery.d.ts +30 -0
  224. package/dist/utils/ha-discovery.js +175 -0
  225. package/dist/utils/ha-discovery.js.map +1 -0
  226. package/dist/utils/ha-state.d.ts +48 -0
  227. package/dist/utils/ha-state.js +21 -0
  228. package/dist/utils/ha-state.js.map +1 -0
  229. package/dist/utils/light-color.d.ts +63 -0
  230. package/dist/utils/light-color.js +213 -0
  231. package/dist/utils/light-color.js.map +1 -0
  232. package/dist/utils/log-buffer.d.ts +13 -0
  233. package/dist/utils/log-buffer.js +50 -0
  234. package/dist/utils/log-buffer.js.map +1 -0
  235. package/dist/utils/matter-attributes.d.ts +13 -0
  236. package/dist/utils/matter-attributes.js +35 -0
  237. package/dist/utils/matter-attributes.js.map +1 -0
  238. package/dist/utils/matter-device-identity.d.ts +22 -0
  239. package/dist/utils/matter-device-identity.js +70 -0
  240. package/dist/utils/matter-device-identity.js.map +1 -0
  241. package/dist/utils/thread-credentials.d.ts +22 -0
  242. package/dist/utils/thread-credentials.js +29 -0
  243. package/dist/utils/thread-credentials.js.map +1 -0
  244. package/package.json +80 -0
@@ -0,0 +1,673 @@
1
+ import { spawn, spawnSync } from "child_process";
2
+ import fs from "fs";
3
+ /**
4
+ * Sanitizes URLs to prevent credentials, access tokens, and secrets from appearing in logs.
5
+ */
6
+ export function sanitizeUrlCredentials(url) {
7
+ if (!url || typeof url !== "string")
8
+ return "";
9
+ let sanitized = url;
10
+ // Mask user:password in scheme://user:pass@host:port/path
11
+ const protoMatch = sanitized.match(/^([a-zA-Z0-9_+.-]+:\/\/)/);
12
+ if (protoMatch) {
13
+ const proto = protoMatch[1];
14
+ const rest = sanitized.substring(proto.length);
15
+ const slashIdx = rest.indexOf("/");
16
+ const questionIdx = rest.indexOf("?");
17
+ const pathStart = slashIdx !== -1
18
+ ? slashIdx
19
+ : questionIdx !== -1
20
+ ? questionIdx
21
+ : rest.length;
22
+ const authority = rest.substring(0, pathStart);
23
+ const pathAndQuery = rest.substring(pathStart);
24
+ const atIdx = authority.lastIndexOf("@");
25
+ if (atIdx !== -1) {
26
+ const userInfo = authority.substring(0, atIdx);
27
+ const hostPort = authority.substring(atIdx + 1);
28
+ const user = userInfo.includes(":") ? userInfo.split(":")[0] : userInfo;
29
+ sanitized = `${proto}${user}:***@${hostPort}${pathAndQuery}`;
30
+ }
31
+ }
32
+ // Mask sensitive query parameters (token, auth, secret, api_key, access_token)
33
+ sanitized = sanitized.replace(/([?&](?:token|auth|secret|api_key|access_token|key)=)([^&]+)/gi, "$1***");
34
+ return sanitized;
35
+ }
36
+ /**
37
+ * Resolves the FFmpeg binary path in priority order:
38
+ * 1. process.env.FFMPEG_PATH
39
+ * 2. /usr/bin/ffmpeg (Docker/Alpine)
40
+ * 3. /usr/local/bin/ffmpeg
41
+ * 4. /opt/homebrew/bin/ffmpeg (macOS Apple Silicon)
42
+ * 5. node_modules/ffmpeg-static/ffmpeg (bundled fallback)
43
+ * 6. ffmpeg (in system PATH)
44
+ */
45
+ export function resolveFfmpegPath() {
46
+ const candidates = [];
47
+ if (process.env.FFMPEG_PATH && process.env.FFMPEG_PATH.trim()) {
48
+ candidates.push(process.env.FFMPEG_PATH.trim());
49
+ }
50
+ candidates.push("/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg", "/opt/homebrew/bin/ffmpeg", "/bin/ffmpeg", "./node_modules/ffmpeg-static/ffmpeg", "../node_modules/ffmpeg-static/ffmpeg", "ffmpeg");
51
+ for (const candidate of candidates) {
52
+ try {
53
+ if (candidate.startsWith("/") || candidate.startsWith(".")) {
54
+ if (fs.existsSync(candidate)) {
55
+ const stats = fs.statSync(candidate);
56
+ if (stats.isFile()) {
57
+ return candidate;
58
+ }
59
+ }
60
+ }
61
+ else {
62
+ // Test PATH executable
63
+ const probe = spawnSync(candidate, ["-version"], {
64
+ timeout: 2000,
65
+ stdio: ["ignore", "pipe", "ignore"],
66
+ });
67
+ if (probe.status === 0 || (probe.stdout && probe.stdout.length > 0)) {
68
+ return candidate;
69
+ }
70
+ }
71
+ }
72
+ catch {
73
+ // Continue to next candidate
74
+ }
75
+ }
76
+ return null;
77
+ }
78
+ let cachedFdkSupport = null;
79
+ /**
80
+ * Checks if the available FFmpeg binary supports the Fraunhofer FDK AAC encoder
81
+ * (libfdk_aac), which is required for Apple HomeKit native AAC-ELD real-time audio.
82
+ */
83
+ export function supportsFdkAac() {
84
+ if (cachedFdkSupport !== null)
85
+ return cachedFdkSupport;
86
+ const ffmpeg = resolveFfmpegPath();
87
+ if (!ffmpeg) {
88
+ cachedFdkSupport = false;
89
+ return false;
90
+ }
91
+ try {
92
+ const probe = spawnSync(ffmpeg, ["-encoders"], {
93
+ timeout: 5000,
94
+ stdio: ["ignore", "pipe", "ignore"],
95
+ });
96
+ cachedFdkSupport =
97
+ probe.stdout?.toString().includes("libfdk_aac") ?? false;
98
+ }
99
+ catch {
100
+ cachedFdkSupport = false;
101
+ }
102
+ return cachedFdkSupport;
103
+ }
104
+ /**
105
+ * Resolves the FFprobe binary path in priority order:
106
+ * 1. process.env.FFPROBE_PATH
107
+ * 2. /usr/local/bin/ffprobe
108
+ * 3. /usr/bin/ffprobe (Docker/Alpine)
109
+ * 4. /opt/homebrew/bin/ffprobe (macOS Apple Silicon)
110
+ * 5. ffprobe (in system PATH)
111
+ */
112
+ export function resolveFfprobePath() {
113
+ const candidates = [];
114
+ if (process.env.FFPROBE_PATH && process.env.FFPROBE_PATH.trim()) {
115
+ candidates.push(process.env.FFPROBE_PATH.trim());
116
+ }
117
+ candidates.push("/usr/local/bin/ffprobe", "/usr/bin/ffprobe", "/opt/homebrew/bin/ffprobe", "/bin/ffprobe", "ffprobe");
118
+ for (const candidate of candidates) {
119
+ try {
120
+ if (candidate.startsWith("/") || candidate.startsWith(".")) {
121
+ if (fs.existsSync(candidate)) {
122
+ const stats = fs.statSync(candidate);
123
+ if (stats.isFile()) {
124
+ return candidate;
125
+ }
126
+ }
127
+ }
128
+ else {
129
+ const probe = spawnSync(candidate, ["-version"], {
130
+ timeout: 2000,
131
+ stdio: ["ignore", "pipe", "ignore"],
132
+ });
133
+ if (probe.status === 0 || (probe.stdout && probe.stdout.length > 0)) {
134
+ return candidate;
135
+ }
136
+ }
137
+ }
138
+ catch {
139
+ // Continue to next candidate
140
+ }
141
+ }
142
+ return null;
143
+ }
144
+ /**
145
+ * Returns the version string of the selected FFmpeg binary.
146
+ */
147
+ export function getFfmpegVersion(customPath) {
148
+ const ffmpegPath = customPath || resolveFfmpegPath();
149
+ if (!ffmpegPath)
150
+ return null;
151
+ try {
152
+ const res = spawnSync(ffmpegPath, ["-version"], {
153
+ timeout: 3000,
154
+ encoding: "utf-8",
155
+ stdio: ["ignore", "pipe", "ignore"],
156
+ });
157
+ if (res.stdout) {
158
+ const match = res.stdout.match(/ffmpeg\s+version\s+([^\s]+)/i);
159
+ return match ? match[1] : res.stdout.split("\n")[0].trim();
160
+ }
161
+ }
162
+ catch {
163
+ // Ignore error
164
+ }
165
+ return null;
166
+ }
167
+ /**
168
+ * Diagnostic probe function: checks a camera stream URL using ffprobe (preferred)
169
+ * or ffmpeg (fallback) to extract video codec, audio codec, resolution, and fps.
170
+ */
171
+ export async function probeCameraSource(sourceUrl, options = {}) {
172
+ const cleanUrl = sourceUrl ? sourceUrl.trim() : "";
173
+ if (cleanUrl.includes("/api/cameraui/motion") ||
174
+ cleanUrl.includes("/api/motion") ||
175
+ cleanUrl.endsWith("/api/cameraui/motion")) {
176
+ return {
177
+ valid: false,
178
+ hasAudio: false,
179
+ error: "Esta URL es un Webhook HTTP para eventos de movimiento, no un stream de video RTSP/MJPEG. Debes configurarla en Camera.UI > Configuración > Webhooks como URL de destino, no como stream de la cámara.",
180
+ };
181
+ }
182
+ const timeoutMs = options.timeoutMs ?? 12000;
183
+ const ffprobePath = options.customFfprobePath || resolveFfprobePath();
184
+ let lastError;
185
+ if (ffprobePath) {
186
+ try {
187
+ const result = await probeWithFfprobe(ffprobePath, sourceUrl, timeoutMs, options.httpBearerToken, options.transport);
188
+ if (result.valid) {
189
+ return result;
190
+ }
191
+ lastError = result.error;
192
+ // If RTSP failed with TCP and user didn't explicitly force TCP, try UDP fallback
193
+ if (sourceUrl.startsWith("rtsp://") &&
194
+ (!options.transport || options.transport === "tcp")) {
195
+ const udpResult = await probeWithFfprobe(ffprobePath, sourceUrl, Math.min(timeoutMs, 4000), options.httpBearerToken, "udp");
196
+ if (udpResult.valid) {
197
+ return udpResult;
198
+ }
199
+ if (udpResult.error) {
200
+ lastError = `${lastError} (UDP: ${udpResult.error})`;
201
+ }
202
+ }
203
+ }
204
+ catch (err) {
205
+ lastError = String(err);
206
+ }
207
+ }
208
+ const ffmpegPath = options.customFfmpegPath || resolveFfmpegPath();
209
+ if (ffmpegPath) {
210
+ try {
211
+ const result = await probeWithFfmpeg(ffmpegPath, sourceUrl, timeoutMs, options.httpBearerToken, options.transport, lastError);
212
+ if (result.valid) {
213
+ return result;
214
+ }
215
+ lastError = result.error;
216
+ // If RTSP failed with TCP and user didn't explicitly force TCP, try UDP fallback with ffmpeg
217
+ if (sourceUrl.startsWith("rtsp://") &&
218
+ (!options.transport || options.transport === "tcp")) {
219
+ const udpResult = await probeWithFfmpeg(ffmpegPath, sourceUrl, Math.min(timeoutMs, 4000), options.httpBearerToken, "udp", lastError);
220
+ if (udpResult.valid) {
221
+ return udpResult;
222
+ }
223
+ if (udpResult.error) {
224
+ lastError = udpResult.error;
225
+ }
226
+ }
227
+ return {
228
+ ...result,
229
+ error: lastError || result.error,
230
+ };
231
+ }
232
+ catch (err) {
233
+ return {
234
+ valid: false,
235
+ hasAudio: false,
236
+ error: String(err),
237
+ };
238
+ }
239
+ }
240
+ return {
241
+ valid: false,
242
+ hasAudio: false,
243
+ error: lastError || "No FFprobe or FFmpeg binary available for probing",
244
+ };
245
+ }
246
+ function probeWithFfprobe(ffprobePath, sourceUrl, timeoutMs, httpBearerToken, transport) {
247
+ return new Promise((resolve) => {
248
+ const args = [
249
+ "-v",
250
+ "error",
251
+ "-show_entries",
252
+ "stream=codec_type,codec_name,width,height,r_frame_rate",
253
+ "-of",
254
+ "json",
255
+ ];
256
+ if ((sourceUrl.startsWith("http://") || sourceUrl.startsWith("https://")) &&
257
+ httpBearerToken) {
258
+ args.push("-headers", `Authorization: Bearer ${httpBearerToken}\r\n`);
259
+ }
260
+ if (sourceUrl.startsWith("rtsp://")) {
261
+ const rtspTransport = transport || "tcp";
262
+ args.push("-rtsp_transport", rtspTransport, "-timeout", "10000000", "-probesize", "2097152", "-analyzeduration", "3000000");
263
+ }
264
+ else if (sourceUrl.startsWith("http://") ||
265
+ sourceUrl.startsWith("https://")) {
266
+ args.push("-probesize", "1048576", "-analyzeduration", "2500000", "-rw_timeout", String(timeoutMs * 1000));
267
+ if (sourceUrl.startsWith("https://")) {
268
+ args.push("-tls_verify", "0");
269
+ }
270
+ }
271
+ args.push(sourceUrl);
272
+ const child = spawn(ffprobePath, args, {
273
+ stdio: ["ignore", "pipe", "pipe"],
274
+ });
275
+ let stdoutData = "";
276
+ let stderrData = "";
277
+ const timer = setTimeout(() => {
278
+ try {
279
+ child.kill("SIGKILL");
280
+ }
281
+ catch { }
282
+ resolve({
283
+ valid: false,
284
+ hasAudio: false,
285
+ error: `Tiempo de espera agotado (${timeoutMs}ms) al conectar al stream RTSP`,
286
+ });
287
+ }, timeoutMs);
288
+ child.stdout.on("data", (chunk) => {
289
+ stdoutData += chunk.toString();
290
+ });
291
+ child.stderr.on("data", (chunk) => {
292
+ stderrData += chunk.toString();
293
+ });
294
+ child.on("close", (code) => {
295
+ clearTimeout(timer);
296
+ if (code === 0 && stdoutData.trim()) {
297
+ try {
298
+ const data = JSON.parse(stdoutData);
299
+ const streams = Array.isArray(data.streams) ? data.streams : [];
300
+ const videoStream = streams.find((s) => s.codec_type === "video");
301
+ const audioStream = streams.find((s) => s.codec_type === "audio");
302
+ if (videoStream && videoStream.codec_name) {
303
+ let fps;
304
+ if (videoStream.r_frame_rate) {
305
+ const parts = videoStream.r_frame_rate.split("/");
306
+ if (parts.length === 2 && parseInt(parts[1], 10) > 0) {
307
+ fps = Math.round(parseInt(parts[0], 10) / parseInt(parts[1], 10));
308
+ }
309
+ }
310
+ resolve({
311
+ valid: true,
312
+ videoCodec: (videoStream.codec_name || "").toLowerCase(),
313
+ audioCodec: (audioStream?.codec_name || "").toLowerCase() || undefined,
314
+ width: videoStream.width,
315
+ height: videoStream.height,
316
+ fps,
317
+ hasAudio: Boolean(audioStream),
318
+ probeMethod: "ffprobe",
319
+ selectedTransport: transport || "tcp",
320
+ });
321
+ return;
322
+ }
323
+ }
324
+ catch {
325
+ // JSON parse failed, fall through to error
326
+ }
327
+ }
328
+ let portStr = "554";
329
+ try {
330
+ const u = new URL(sourceUrl);
331
+ portStr = u.port || (u.protocol === "http:" ? "80" : u.protocol === "https:" ? "443" : "554");
332
+ }
333
+ catch { }
334
+ const raw = stderrData.trim();
335
+ let friendly = raw;
336
+ if (raw.includes("Host is down") || raw.includes("No route to host") || raw.includes("EHOSTDOWN") || raw.includes("EHOSTUNREACH")) {
337
+ friendly = "Host inalcanzable (Host is down / No route to host). El equipo en esa IP está apagado, desconectado o cambió de dirección.";
338
+ }
339
+ else if (raw.includes("Connection refused") || raw.includes("ECONNREFUSED")) {
340
+ friendly = `Conexión rechazada (Connection refused en puerto ${portStr}). Verifica la IP y que el servicio RTSP esté activo en ese puerto.`;
341
+ }
342
+ else if (raw.includes("401") || raw.includes("Unauthorized")) {
343
+ friendly = `Autenticación requerida (401 Unauthorized). El stream RTSP requiere usuario y contraseña (rtsp://usuario:clave@ip:${portStr}/...).`;
344
+ }
345
+ else if (raw.includes("404") || raw.includes("Not Found")) {
346
+ friendly = "Ruta no encontrada (404 Not Found). La ruta RTSP no existe en este dispositivo.";
347
+ }
348
+ else if (raw.includes("timed out") || raw.includes("Operation not permitted") || raw.includes("ETIMEDOUT")) {
349
+ friendly = `Tiempo de espera agotado al conectar al stream RTSP en puerto ${portStr} (timeout). Verifica la conexión WiFi o si el host está encendido.`;
350
+ }
351
+ else if (raw.includes("Invalid data found") || raw.includes("Error opening input")) {
352
+ friendly = `Respuesta RTSP no válida (Invalid data found). La cámara en puerto ${portStr} rechazó la conexión. Verifica si requiere usuario y contraseña (rtsp://usuario:clave@ip:${portStr}/...), si la ruta es /live en vez de /stream0, o cambia a UDP.`;
353
+ }
354
+ else if (raw.includes("Could not find codec parameters")) {
355
+ friendly = "No se pudieron decodificar parámetros H.264 (no se detectaron fotogramas clave a tiempo).";
356
+ }
357
+ else if (!friendly) {
358
+ friendly = `ffprobe finalizó sin datos de video válidos (código ${code})`;
359
+ }
360
+ resolve({
361
+ valid: false,
362
+ hasAudio: false,
363
+ error: friendly,
364
+ });
365
+ });
366
+ child.on("error", (err) => {
367
+ clearTimeout(timer);
368
+ resolve({
369
+ valid: false,
370
+ hasAudio: false,
371
+ error: String(err),
372
+ });
373
+ });
374
+ });
375
+ }
376
+ function probeWithFfmpeg(ffmpegPath, sourceUrl, timeoutMs, httpBearerToken, transport, lastError) {
377
+ return new Promise((resolve) => {
378
+ const args = [
379
+ "-hide_banner",
380
+ "-probesize",
381
+ "2097152",
382
+ "-analyzeduration",
383
+ "3000000",
384
+ ];
385
+ if ((sourceUrl.startsWith("http://") || sourceUrl.startsWith("https://")) &&
386
+ httpBearerToken) {
387
+ args.push("-headers", `Authorization: Bearer ${httpBearerToken}\r\n`);
388
+ }
389
+ if (sourceUrl.startsWith("rtsp://")) {
390
+ const rtspTransport = transport || "tcp";
391
+ args.push("-rtsp_transport", rtspTransport, "-timeout", "10000000");
392
+ }
393
+ else if (sourceUrl.startsWith("http://") ||
394
+ sourceUrl.startsWith("https://")) {
395
+ args.push("-reconnect", "1", "-reconnect_at_eof", "1", "-reconnect_streamed", "1", "-rw_timeout", String(timeoutMs * 1000));
396
+ if (sourceUrl.startsWith("https://")) {
397
+ args.push("-tls_verify", "0");
398
+ }
399
+ }
400
+ args.push("-i", sourceUrl, "-t", "2", "-f", "null", "-");
401
+ const child = spawn(ffmpegPath, args, {
402
+ stdio: ["ignore", "ignore", "pipe"],
403
+ });
404
+ let stderrData = "";
405
+ const timer = setTimeout(() => {
406
+ try {
407
+ child.kill("SIGKILL");
408
+ }
409
+ catch { }
410
+ resolve({
411
+ valid: false,
412
+ hasAudio: false,
413
+ error: `Tiempo de espera agotado (${timeoutMs}ms) en FFmpeg`,
414
+ });
415
+ }, timeoutMs);
416
+ child.stderr.on("data", (chunk) => {
417
+ stderrData += chunk.toString();
418
+ });
419
+ child.on("close", () => {
420
+ clearTimeout(timer);
421
+ let videoCodec;
422
+ let audioCodec;
423
+ let width;
424
+ let height;
425
+ let fps;
426
+ const videoMatch = stderrData.match(/Video:\s+([a-zA-Z0-9_-]+)/i);
427
+ if (videoMatch) {
428
+ videoCodec = videoMatch[1].toLowerCase();
429
+ }
430
+ const resMatch = stderrData.match(/(\d{3,5})x(\d{3,5})/);
431
+ if (resMatch) {
432
+ width = parseInt(resMatch[1], 10);
433
+ height = parseInt(resMatch[2], 10);
434
+ }
435
+ const fpsMatch = stderrData.match(/(\d+(?:\.\d+)?)\s+fps/i);
436
+ if (fpsMatch) {
437
+ fps = Math.round(parseFloat(fpsMatch[1]));
438
+ }
439
+ const audioMatch = stderrData.match(/Audio:\s+([a-zA-Z0-9_-]+)/i);
440
+ if (audioMatch) {
441
+ audioCodec = audioMatch[1].toLowerCase();
442
+ }
443
+ const valid = Boolean(videoCodec);
444
+ const raw = stderrData.trim();
445
+ let friendly = raw;
446
+ if (!valid) {
447
+ let portStr = "554";
448
+ try {
449
+ const u = new URL(sourceUrl);
450
+ portStr = u.port || (u.protocol === "http:" ? "80" : u.protocol === "https:" ? "443" : "554");
451
+ }
452
+ catch { }
453
+ if (raw.includes("Host is down") || raw.includes("No route to host") || raw.includes("EHOSTDOWN") || raw.includes("EHOSTUNREACH")) {
454
+ friendly = "Host inalcanzable (Host is down / No route to host). El equipo en esa IP está apagado o cambió de dirección.";
455
+ }
456
+ else if (raw.includes("Connection refused") || raw.includes("ECONNREFUSED")) {
457
+ friendly = `Conexión rechazada (Connection refused en puerto ${portStr}). Verifica la IP y que el servicio RTSP esté activo en ese puerto.`;
458
+ }
459
+ else if (raw.includes("401") || raw.includes("Unauthorized")) {
460
+ friendly = `Autenticación requerida (401 Unauthorized). El stream RTSP requiere credenciales (rtsp://usuario:clave@ip:${portStr}/...).`;
461
+ }
462
+ else if (raw.includes("404") || raw.includes("Not Found")) {
463
+ friendly = "Ruta de stream no encontrada (404 Not Found).";
464
+ }
465
+ else if (raw.includes("timed out") || raw.includes("ETIMEDOUT")) {
466
+ friendly = `Tiempo de espera agotado al conectar al stream RTSP en puerto ${portStr} (timeout).`;
467
+ }
468
+ else if (raw.includes("Invalid data found") || raw.includes("Error opening input")) {
469
+ friendly = `Respuesta RTSP no válida (Invalid data found). Verifica si la cámara requiere usuario y contraseña (rtsp://usuario:clave@ip:${portStr}/...), si la ruta es /live en vez de /stream0, o cambia a UDP.`;
470
+ }
471
+ else if (!friendly) {
472
+ friendly = lastError || "No se detectaron paquetes de video H.264 válidos en el stream.";
473
+ }
474
+ }
475
+ resolve({
476
+ valid,
477
+ videoCodec,
478
+ audioCodec,
479
+ width,
480
+ height,
481
+ fps,
482
+ hasAudio: Boolean(audioCodec),
483
+ probeMethod: "ffmpeg",
484
+ selectedTransport: transport || "tcp",
485
+ error: valid ? undefined : friendly,
486
+ });
487
+ });
488
+ child.on("error", (err) => {
489
+ clearTimeout(timer);
490
+ resolve({
491
+ valid: false,
492
+ hasAudio: false,
493
+ error: String(err),
494
+ });
495
+ });
496
+ });
497
+ }
498
+ /**
499
+ * Measures the observed Keyframe / GOP interval in seconds by analyzing a 2-3s sample of the video stream.
500
+ * Returns undefined if keyframes cannot be observed within the sample window.
501
+ */
502
+ export async function measureStreamGop(sourceUrl, timeoutMs = 3000) {
503
+ const ffprobePath = resolveFfprobePath();
504
+ if (!ffprobePath)
505
+ return undefined;
506
+ return new Promise((resolve) => {
507
+ const args = [
508
+ "-v",
509
+ "error",
510
+ "-select_streams",
511
+ "v:0",
512
+ "-show_entries",
513
+ "frame=pkt_pts_time,key_frame",
514
+ "-read_intervals",
515
+ "%+3",
516
+ "-of",
517
+ "json",
518
+ ];
519
+ if (sourceUrl.startsWith("rtsp://")) {
520
+ args.push("-rtsp_transport", "tcp");
521
+ }
522
+ else if (sourceUrl.startsWith("http://") ||
523
+ sourceUrl.startsWith("https://")) {
524
+ args.push("-rw_timeout", String(timeoutMs * 1000));
525
+ if (sourceUrl.startsWith("https://")) {
526
+ args.push("-tls_verify", "0");
527
+ }
528
+ }
529
+ args.push(sourceUrl);
530
+ const child = spawn(ffprobePath, args, {
531
+ stdio: ["ignore", "pipe", "ignore"],
532
+ });
533
+ let stdoutData = "";
534
+ const timer = setTimeout(() => {
535
+ try {
536
+ child.kill("SIGKILL");
537
+ }
538
+ catch { }
539
+ resolve(undefined);
540
+ }, timeoutMs);
541
+ child.stdout.on("data", (chunk) => {
542
+ stdoutData += chunk.toString();
543
+ });
544
+ child.on("close", (code) => {
545
+ clearTimeout(timer);
546
+ if (code === 0 && stdoutData.trim()) {
547
+ try {
548
+ const parsed = JSON.parse(stdoutData);
549
+ const frames = Array.isArray(parsed.frames) ? parsed.frames : [];
550
+ const keyframes = frames.filter((f) => f.key_frame === 1 && f.pkt_pts_time !== undefined);
551
+ if (keyframes.length >= 2) {
552
+ const t1 = parseFloat(keyframes[0].pkt_pts_time);
553
+ const t2 = parseFloat(keyframes[1].pkt_pts_time);
554
+ if (!isNaN(t1) && !isNaN(t2) && t2 > t1) {
555
+ const diff = Math.round((t2 - t1) * 10) / 10;
556
+ resolve(diff > 0 ? diff : undefined);
557
+ return;
558
+ }
559
+ }
560
+ }
561
+ catch { }
562
+ }
563
+ resolve(undefined);
564
+ });
565
+ child.on("error", () => {
566
+ clearTimeout(timer);
567
+ resolve(undefined);
568
+ });
569
+ });
570
+ }
571
+ /**
572
+ * Builds the complete FFmpeg CLI arguments array for sending HAP RTP/SRTP packets to Apple Home.
573
+ */
574
+ export function buildFfmpegStreamArgs(config) {
575
+ const srtpSuiteStr = config.videoCryptoSuite === 1 /* SRTPCryptoSuites.AES_CM_256_HMAC_SHA1_80 */
576
+ ? "AES_CM_256_HMAC_SHA1_80"
577
+ : "AES_CM_128_HMAC_SHA1_80";
578
+ // Omit localrtcpport to allow FFmpeg to bind to an ephemeral local port without host-network port collisions
579
+ const videoSrtpUrl = `srtp://${config.targetAddress}:${config.videoPort}?rtcpport=${config.videoPort}&pkt_size=1316`;
580
+ const isPassthrough = config.strategy === "passthrough_h264" ||
581
+ config.strategy === "passthrough_video_only";
582
+ const videoPayloadArgs = ["-map", "0:v:0"];
583
+ if (isPassthrough) {
584
+ // Passthrough H.264 (Remux directly without transcoding CPU overhead)
585
+ videoPayloadArgs.push("-vcodec", "copy");
586
+ if (config.needsDumpExtra) {
587
+ videoPayloadArgs.push("-bsf:v", "dump_extra=freq=keyframe");
588
+ }
589
+ }
590
+ else {
591
+ // Transcode fallback for H.265 / MJPEG / incompatible formats
592
+ const bitrate = config.bitrateKbps || 2000;
593
+ const fps = config.fps || 30;
594
+ videoPayloadArgs.push("-vcodec", "libx264", "-pix_fmt", "yuv420p", "-profile:v", "baseline", "-level:v", "3.1", "-r", String(fps), "-g", String(Math.max(1, fps * 2)), "-keyint_min", String(Math.max(1, fps)), "-b:v", `${bitrate}k`, "-bufsize", `${bitrate * 2}k`, "-maxrate", `${bitrate}k`, "-preset", "ultrafast", "-tune", "zerolatency");
595
+ }
596
+ const inputArgs = ["-hide_banner", "-loglevel", "warning"];
597
+ if ((config.sourceUrl.startsWith("http://") ||
598
+ config.sourceUrl.startsWith("https://")) &&
599
+ config.httpBearerToken) {
600
+ inputArgs.push("-headers", `Authorization: Bearer ${config.httpBearerToken}\r\n`);
601
+ }
602
+ if (config.sourceUrl.startsWith("rtsp://")) {
603
+ const transport = config.transport || "tcp";
604
+ if (transport !== "auto") {
605
+ inputArgs.push("-rtsp_transport", transport);
606
+ }
607
+ inputArgs.push("-fflags", "+nobuffer+genpts");
608
+ inputArgs.push("-use_wallclock_as_timestamps", "1");
609
+ }
610
+ else {
611
+ inputArgs.push("-fflags", "+nobuffer");
612
+ }
613
+ inputArgs.push("-flags", "low_delay", "-i", config.sourceUrl);
614
+ const args = [
615
+ ...inputArgs,
616
+ ...videoPayloadArgs,
617
+ "-f",
618
+ "rtp",
619
+ "-payload_type",
620
+ String(config.videoPayloadType || 99),
621
+ "-ssrc",
622
+ String(config.videoSsrc),
623
+ "-srtp_out_suite",
624
+ srtpSuiteStr,
625
+ "-srtp_out_params",
626
+ config.videoKeySaltBase64,
627
+ videoSrtpUrl,
628
+ ];
629
+ // Optional audio pipeline (using tolerant -map 0:a:0? so stream won't crash if audio track is missing)
630
+ if (config.includeAudio &&
631
+ config.audioPort &&
632
+ config.audioKeySaltBase64 &&
633
+ config.strategy !== "passthrough_video_only") {
634
+ const audioSrtpUrl = `srtp://${config.targetAddress}:${config.audioPort}?rtcpport=${config.audioPort}&pkt_size=188`;
635
+ let audioArgs;
636
+ if (config.audioCodec === "opus") {
637
+ audioArgs = [
638
+ "-map",
639
+ "0:a:0?",
640
+ "-acodec",
641
+ "libopus",
642
+ "-application",
643
+ "lowdelay",
644
+ "-ar",
645
+ "16k",
646
+ "-b:a",
647
+ "24k",
648
+ "-ac",
649
+ "1",
650
+ ];
651
+ }
652
+ else if (config.audioCodec === "aac") {
653
+ audioArgs = ["-map", "0:a:0?", "-acodec", "copy"];
654
+ }
655
+ else {
656
+ audioArgs = [
657
+ "-map",
658
+ "0:a:0?",
659
+ "-acodec",
660
+ "aac",
661
+ "-ar",
662
+ "16k",
663
+ "-b:a",
664
+ "32k",
665
+ "-ac",
666
+ "1",
667
+ ];
668
+ }
669
+ args.push(...audioArgs, "-f", "rtp", "-payload_type", String(config.audioPayloadType || 110), "-ssrc", String(config.audioSsrc || 2), "-srtp_out_suite", srtpSuiteStr, "-srtp_out_params", config.audioKeySaltBase64, audioSrtpUrl);
670
+ }
671
+ return args;
672
+ }
673
+ //# sourceMappingURL=ffmpeg-helper.js.map