@camstack/addon-provider-rtsp 0.1.12 → 0.1.14

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.
package/dist/addon.js CHANGED
@@ -23,292 +23,556 @@ __export(addon_exports, {
23
23
  RtspProviderAddon: () => RtspProviderAddon
24
24
  });
25
25
  module.exports = __toCommonJS(addon_exports);
26
+ var import_types2 = require("@camstack/types");
26
27
 
27
- // src/rtsp-device.ts
28
+ // src/rtsp-camera.ts
29
+ var import_zod = require("zod");
28
30
  var import_types = require("@camstack/types");
29
- var RtspDevice = class {
30
- id;
31
- name;
32
- providerId;
31
+ var streamEntrySchema = import_zod.z.object({
32
+ id: import_zod.z.string().regex(/^stream-\d+$/).describe("Stable slot id (stream-1/2/3)"),
33
+ url: import_zod.z.string().describe("RTSP stream URL"),
34
+ profileHint: import_zod.z.enum(["high", "mid", "low"]).optional().describe("Provider-suggested profile \u2014 advisory only"),
35
+ resolution: import_zod.z.object({ width: import_zod.z.number().int().positive(), height: import_zod.z.number().int().positive() }).optional().describe("Probed resolution, if known")
36
+ });
37
+ var streamsField = import_zod.z.preprocess(
38
+ (raw) => {
39
+ if (!Array.isArray(raw)) return raw;
40
+ return raw.map((entry, i) => {
41
+ if (!entry || typeof entry !== "object") return entry;
42
+ const o = entry;
43
+ if (typeof o["id"] === "string") return entry;
44
+ if (typeof o["label"] === "string" && typeof o["url"] === "string") {
45
+ return {
46
+ id: `stream-${i + 1}`,
47
+ url: o["url"],
48
+ profileHint: o["label"]
49
+ };
50
+ }
51
+ return entry;
52
+ });
53
+ },
54
+ import_zod.z.array(streamEntrySchema).min(1)
55
+ );
56
+ var rtspCameraSchema = import_zod.z.object({
57
+ // `name` is now base meta (DB column on `device-meta`, not in this
58
+ // hardware-config schema). Read via `this.name` (resolved by
59
+ // `BaseDevice` from `ctx.deviceMeta.name`); mutated via
60
+ // `kernel.devices.setName(id, name)`.
61
+ streams: streamsField.describe("Published RTSP streams"),
62
+ snapshotUrl: import_zod.z.string().default("").describe("Snapshot URL (optional)"),
63
+ username: import_zod.z.string().default("").describe("Username"),
64
+ password: import_zod.z.string().default("").describe("Password")
65
+ });
66
+ var legacyStreamSchema = import_zod.z.object({
67
+ label: import_zod.z.enum(["high", "mid", "low"]),
68
+ url: import_zod.z.string()
69
+ });
70
+ var RtspCamera = class extends import_types.BaseDevice {
33
71
  type = import_types.DeviceType.Camera;
34
- capabilities;
35
- ctx;
36
- stableId;
37
- settings;
38
- capabilityMap = /* @__PURE__ */ new Map();
39
- constructor(device, settings, ctx) {
40
- this.id = device.id;
41
- this.stableId = device.stableId;
42
- this.name = device.name;
43
- this.providerId = device.integrationId;
44
- this.settings = settings;
45
- this.ctx = ctx;
46
- this.capabilities = ["camera"];
47
- this.capabilityMap.set("camera", this.createCamera());
48
- }
49
- getCapability(cap) {
50
- return this.capabilityMap.get(cap) ?? null;
51
- }
52
- hasCapability(cap) {
53
- return this.capabilityMap.has(cap);
72
+ features = [];
73
+ constructor(ctx) {
74
+ super(
75
+ ctx,
76
+ rtspCameraSchema,
77
+ { type: import_types.DeviceType.Camera }
78
+ );
79
+ this.migrateLegacyStreamsIfNeeded(ctx.persistedConfig ?? {});
80
+ this.registerSnapshotProvider();
54
81
  }
55
- getState() {
56
- return { online: true };
82
+ /**
83
+ * Detect legacy `{label, url}` stream shapes and reshape to
84
+ * `{id, url, profileHint}`. Persists via `config.setAll` once, so
85
+ * subsequent boots find the new shape and this branch is inert.
86
+ *
87
+ * Runs fire-and-forget — the constructor can't await. The reshape is
88
+ * additive (ids are newly minted) so a failed persist is recoverable
89
+ * on next boot.
90
+ */
91
+ migrateLegacyStreamsIfNeeded(initialData) {
92
+ const raw = initialData["streams"];
93
+ if (!Array.isArray(raw)) return;
94
+ if (raw.every((s) => s && typeof s === "object" && typeof s["id"] === "string")) {
95
+ return;
96
+ }
97
+ const migrated = [];
98
+ let nextIdx = 1;
99
+ for (const entry of raw) {
100
+ const parsed = legacyStreamSchema.safeParse(entry);
101
+ if (!parsed.success) continue;
102
+ migrated.push({
103
+ id: `stream-${nextIdx++}`,
104
+ url: parsed.data.url,
105
+ profileHint: parsed.data.label
106
+ });
107
+ }
108
+ if (migrated.length === 0) return;
109
+ const snapshotUrl = this.config.get("snapshotUrl") ?? "";
110
+ const username = this.config.get("username") ?? "";
111
+ const password = this.config.get("password") ?? "";
112
+ this.ctx.logger.info("Migrating legacy {label,url} streams to {id,url,profileHint}", {
113
+ tags: { stableId: this.stableId },
114
+ meta: { streamCount: migrated.length }
115
+ });
116
+ void this.config.setAll({ streams: migrated, snapshotUrl, username, password }).catch((err) => {
117
+ this.ctx.logger.warn("Legacy stream migration failed", {
118
+ tags: { stableId: this.stableId },
119
+ meta: { error: err instanceof Error ? err.message : String(err) }
120
+ });
121
+ });
57
122
  }
58
- getMetadata() {
59
- return { manufacturer: "Generic RTSP" };
123
+ /**
124
+ * Publish every configured stream to the system stream-broker as a
125
+ * `pull-rtsp` cam stream. Idempotent — the broker's publishCameraStream
126
+ * entry is keyed by `(deviceId, camStreamId)` so callers may invoke
127
+ * this at will (e.g. on stream-broker restart). Fire-and-forget safe.
128
+ */
129
+ /**
130
+ * Lifecycle hook fired by the kernel after registration. Publishes
131
+ * the camera's streams to the broker — the kernel doesn't know
132
+ * about the broker, but the camera does. Best-effort: if the
133
+ * broker isn't ready, the provider's `system.ready-state`
134
+ * subscription re-publishes on the next ready fire.
135
+ */
136
+ async onActivate() {
137
+ await this.publishToBroker().catch((err) => {
138
+ this.ctx.logger.warn("publishToBroker on activate failed \u2014 will retry on broker ready", {
139
+ meta: { error: err instanceof Error ? err.message : String(err) }
140
+ });
141
+ });
60
142
  }
61
- createCamera() {
62
- const mainUrl = String(this.settings["main_stream_url"] ?? "");
63
- const subUrl = String(this.settings["sub_stream_url"] ?? "");
64
- const snapshotUrl = String(this.settings["snapshot_url"] ?? "");
65
- const deviceId = this.id;
66
- return {
67
- kind: "camera",
68
- async getSnapshot() {
69
- if (snapshotUrl) {
70
- const res = await fetch(snapshotUrl);
71
- return Buffer.from(await res.arrayBuffer());
72
- }
73
- return Buffer.alloc(0);
74
- },
75
- async getStreamOptions() {
76
- const options = [
77
- {
78
- id: `${deviceId}_main`,
79
- label: "Main",
80
- protocol: "rtsp",
81
- quality: "main",
82
- url: mainUrl
83
- }
84
- ];
85
- if (subUrl) {
86
- options.push({
87
- id: `${deviceId}_sub`,
88
- label: "Sub",
89
- protocol: "rtsp",
90
- quality: "sub",
91
- url: subUrl
92
- });
93
- }
94
- return options;
95
- },
96
- async getStreamUrl(option) {
97
- return option.url ?? mainUrl;
98
- },
99
- getConnectionMode() {
100
- return "always-on";
101
- },
102
- async setConnectionMode() {
143
+ async publishToBroker() {
144
+ const streams = this.config.get("streams");
145
+ for (const [i, s] of streams.entries()) {
146
+ try {
147
+ await this.ctx.api.streamBroker.publishCameraStream.mutate({
148
+ deviceId: this.id,
149
+ camStreamId: s.id,
150
+ kind: "pull-rtsp",
151
+ url: s.url,
152
+ ...s.resolution ? { resolution: s.resolution } : {},
153
+ label: `Stream ${i + 1}`
154
+ });
155
+ } catch (err) {
156
+ this.ctx.logger.warn("publishCameraStream failed", {
157
+ tags: { deviceId: this.id, camStreamId: s.id },
158
+ meta: { error: err instanceof Error ? err.message : String(err) }
159
+ });
103
160
  }
104
- };
105
- }
106
- };
107
-
108
- // src/rtsp-provider.ts
109
- function sanitizeStableId(name) {
110
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || `rtsp-${Date.now()}`;
111
- }
112
- var RtspProvider = class {
113
- id;
114
- type = "rtsp";
115
- name;
116
- discoveryMode = "manual";
117
- ctx;
118
- integration;
119
- registry;
120
- devices = [];
121
- constructor(integration, registry, ctx) {
122
- this.id = integration.id;
123
- this.name = integration.name;
124
- this.integration = integration;
125
- this.registry = registry;
126
- this.ctx = ctx;
127
- }
128
- async start() {
129
- const registeredDevices = this.registry.listDevices(this.integration.id);
130
- for (const device of registeredDevices) {
131
- if (!device.enabled) continue;
132
- const settings = this.registry.getDeviceSettings(device.id);
133
- this.devices.push(this.buildDevice(device, settings));
134
161
  }
135
- this.ctx.logger.info(`RTSP provider started with ${this.devices.length} cameras`);
136
- }
137
- async stop() {
138
- this.devices.length = 0;
139
- this.ctx.logger.info("RTSP provider stopped");
140
162
  }
141
- getStatus() {
142
- return { connected: true, deviceCount: this.devices.length };
163
+ /**
164
+ * Thin compat shim: reflects the stored `{id, url, profileHint?}`
165
+ * streams into the legacy `StreamSourceEntry` shape so
166
+ * `ICameraDevice`-aware consumers (device-manager legacy paths,
167
+ * device-cap-proxy fallback) still find data. The broker itself does
168
+ * NOT read this anymore — it consumes `publishCameraStream`. This
169
+ * shim goes away when every consumer migrates (C5/C7).
170
+ */
171
+ async getStreamSources() {
172
+ const streams = this.config.get("streams");
173
+ return streams.map((s) => ({
174
+ id: s.id,
175
+ label: s.profileHint ?? s.id,
176
+ protocol: "rtsp",
177
+ url: s.url,
178
+ ...s.profileHint ? { profileHint: s.profileHint } : {},
179
+ ...s.resolution ? { resolution: s.resolution } : {}
180
+ }));
143
181
  }
144
- async discoverDevices() {
145
- return [];
146
- }
147
- getDevices() {
148
- return [...this.devices];
182
+ async removeDevice() {
183
+ this.ctx.logger.info("Removing RTSP camera", { meta: { stableId: this.stableId } });
184
+ const streams = this.config.get("streams");
185
+ await Promise.all(
186
+ streams.map(
187
+ (s) => this.ctx.api.streamBroker.retractCameraStream.mutate({ deviceId: this.id, camStreamId: s.id }).catch((err) => {
188
+ this.ctx.logger.warn("retractCameraStream failed", {
189
+ tags: { deviceId: this.id, camStreamId: s.id },
190
+ meta: { error: err instanceof Error ? err.message : String(err) }
191
+ });
192
+ })
193
+ )
194
+ );
149
195
  }
150
- getDeviceConfigSchema() {
151
- return {
196
+ // ── Driver-authored settings UI ────────────────────────────────────────
197
+ //
198
+ // Streams are stored as `Array<{id, url, profileHint?, resolution?}>`
199
+ // but the settings UI exposes them as a `multiple` probe field of raw
200
+ // URLs — the form only cares about the ordered list of URLs, the ids
201
+ // and classification live in storage. Values are projected from
202
+ // storage into the flat form keys referenced by the schema.
203
+ getSettingsUISchema() {
204
+ const schema = {
152
205
  sections: [
206
+ // The `name` field is now base meta — rendered by the
207
+ // device-manager's own settings contribution (with the
208
+ // location field), NOT by the driver's hardware-config
209
+ // schema. Driver UIs only carry technical knobs.
153
210
  {
154
- id: "device-info",
155
- title: "Device Configuration",
156
- description: "Configure the RTSP camera connection",
211
+ id: "streams",
212
+ title: "RTSP Streams",
213
+ description: "Provide 1\u20133 RTSP URLs for this camera. After save, each URL is probed and the stream-broker assigns the (high / mid / low) profiles by resolution (highest pixel count \u2192 high). Input slot order in this form does not affect the broker profile mapping.",
157
214
  columns: 1,
158
215
  fields: [
159
216
  {
160
- type: "text",
161
- key: "name",
162
- label: "Device Name",
163
- placeholder: "e.g. Front Door Camera",
164
- required: true
165
- },
166
- {
167
- type: "text",
168
- key: "main_stream_url",
169
- label: "Main Stream URL",
170
- placeholder: "rtsp://192.168.1.100:554/stream1",
217
+ type: "probe",
218
+ key: "streams",
219
+ label: "RTSP stream URL",
220
+ required: true,
221
+ placeholder: "rtsp://user:pass@host:554/Streaming/Channels/101",
171
222
  inputType: "url",
172
- required: true
173
- },
174
- {
175
- type: "text",
176
- key: "sub_stream_url",
177
- label: "Sub Stream URL",
178
- placeholder: "rtsp://192.168.1.100:554/stream2",
179
- inputType: "url"
180
- },
181
- {
182
- type: "text",
183
- key: "snapshot_url",
184
- label: "Snapshot URL",
185
- placeholder: "http://192.168.1.100/snapshot.jpg",
186
- inputType: "url"
223
+ multiple: {
224
+ min: 1,
225
+ max: 3,
226
+ addLabel: "Add stream",
227
+ itemLabel: "Stream ${n}",
228
+ itemDefault: ""
229
+ }
187
230
  }
188
231
  ]
232
+ },
233
+ {
234
+ id: "snapshot",
235
+ title: "Snapshot",
236
+ columns: 1,
237
+ fields: [
238
+ { type: "probe", key: "snapshotUrl", label: "Snapshot URL", description: "Optional HTTP(S) endpoint that returns a JPEG still.", placeholder: "http://host/ISAPI/Streaming/channels/101/picture", inputType: "url" }
239
+ ]
240
+ },
241
+ {
242
+ id: "credentials",
243
+ title: "Credentials",
244
+ description: "Optional. If the RTSP URL already contains user:pass@ you can leave these empty.",
245
+ columns: 2,
246
+ fields: [
247
+ { type: "text", key: "username", label: "Username" },
248
+ { type: "password", key: "password", label: "Password", showToggle: true }
249
+ ]
189
250
  }
190
251
  ]
191
252
  };
253
+ return (0, import_types.hydrateSchema)(schema, this.collectFormValues());
192
254
  }
193
- async createDevice(config) {
194
- const name = String(config["name"] ?? "").trim();
195
- if (!name) throw new Error("Device name is required");
196
- const mainStreamUrl = String(config["main_stream_url"] ?? "").trim();
197
- if (!mainStreamUrl) throw new Error("Main stream URL is required");
198
- const stableId = sanitizeStableId(name);
199
- const existing = this.registry.getDeviceByStableId(stableId);
200
- if (existing) throw new Error(`A device with name "${name}" already exists (stableId: ${stableId})`);
201
- const device = this.registry.createDevice({
202
- integrationId: this.integration.id,
203
- stableId,
204
- type: "camera",
205
- name,
206
- enabled: true,
207
- info: {},
208
- settings: {
209
- main_stream_url: mainStreamUrl,
210
- sub_stream_url: config["sub_stream_url"] ? String(config["sub_stream_url"]) : "",
211
- snapshot_url: config["snapshot_url"] ? String(config["snapshot_url"]) : ""
212
- }
255
+ /**
256
+ * Project stored config into the flat UI keys referenced by the schema.
257
+ * Form only sees URLs the internal id/profileHint/resolution stay
258
+ * invisible to the operator (the broker decides profiles from probed
259
+ * metadata at save time).
260
+ */
261
+ collectFormValues() {
262
+ const stored = this.config.get("streams");
263
+ const sorted = [...stored].sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true }));
264
+ const urls = sorted.map((s) => s.url).filter((u) => u.length > 0);
265
+ return {
266
+ streams: urls,
267
+ snapshotUrl: this.config.get("snapshotUrl"),
268
+ username: this.config.get("username"),
269
+ password: this.config.get("password")
270
+ };
271
+ }
272
+ async applySettingsPatch(patch) {
273
+ const current = this.collectFormValues();
274
+ const merged = { ...current, ...patch };
275
+ const pickStr = (k) => typeof merged[k] === "string" ? merged[k].trim() : "";
276
+ const next = {};
277
+ const rawStreams = merged["streams"];
278
+ const incomingUrls = Array.isArray(rawStreams) ? rawStreams.filter((s) => typeof s === "string").map((s) => s.trim()).filter((s) => s.length > 0) : [];
279
+ if (incomingUrls.length === 0) {
280
+ next.streams = this.config.get("streams");
281
+ } else {
282
+ const probed = await this.probeAndClassify(incomingUrls.slice(0, 3));
283
+ next.streams = probed;
284
+ }
285
+ next.snapshotUrl = pickStr("snapshotUrl");
286
+ next.username = pickStr("username");
287
+ next.password = typeof merged["password"] === "string" ? merged["password"] : this.config.get("password");
288
+ await this.config.setAll(next);
289
+ await this.publishToBroker();
290
+ }
291
+ /**
292
+ * Probe a list of RTSP URLs through the kernel stream-probe and return
293
+ * the new `{id, url, profileHint?, resolution?}` entries. Ids are
294
+ * assigned `stream-1/2/3` in input order so the UI's slot ordering is
295
+ * preserved across edits. The broker is in charge of the actual
296
+ * (high/mid/low) profile assignment via `computeInitialAssignment`.
297
+ */
298
+ async probeAndClassify(urls) {
299
+ const streamProbe = this.ctx.streamProbe;
300
+ if (!streamProbe) {
301
+ this.ctx.logger.warn(
302
+ "[rtsp-edit] ctx.streamProbe unavailable \u2014 falling back to input-order profile assignment",
303
+ { meta: { streamCount: urls.length } }
304
+ );
305
+ const sequence = urls.length === 1 ? ["high"] : urls.length === 2 ? ["high", "low"] : ["high", "mid", "low"];
306
+ return urls.map((url, i) => ({
307
+ id: `stream-${i + 1}`,
308
+ url,
309
+ profileHint: sequence[i]
310
+ }));
311
+ }
312
+ const probed = await Promise.all(
313
+ urls.map(async (url) => {
314
+ try {
315
+ const metadata = await streamProbe.probe(url, { force: false });
316
+ return { url, metadata };
317
+ } catch (err) {
318
+ this.ctx.logger.warn(
319
+ "[rtsp-edit] probe failed \u2014 landing in the lowest tier via classifyStreams",
320
+ { meta: { url: (0, import_types.maskUrlCredentials)(url), error: err instanceof Error ? err.message : String(err) } }
321
+ );
322
+ const emptyMetadata = {};
323
+ return { url, metadata: emptyMetadata };
324
+ }
325
+ })
326
+ );
327
+ const classified = (0, import_types.classifyStreams)(probed);
328
+ const metadataByUrl = new Map(probed.map((p) => [p.url, p.metadata]));
329
+ const classifiedByUrl = new Map(classified.map((c) => [c.url, c]));
330
+ return urls.map((url, i) => {
331
+ const tag = classifiedByUrl.get(url);
332
+ const meta = metadataByUrl.get(url);
333
+ const entry = { id: `stream-${i + 1}`, url };
334
+ if (tag) entry.profileHint = tag.quality;
335
+ if (meta?.width && meta?.height) entry.resolution = { width: meta.width, height: meta.height };
336
+ return entry;
213
337
  });
214
- const settings = this.registry.getDeviceSettings(device.id);
215
- const rtspDevice = this.buildDevice(device, settings);
216
- this.devices.push(rtspDevice);
217
- this.ctx.logger.info(`Created RTSP device: ${device.id} / ${stableId} (${name})`);
218
- return rtspDevice;
219
338
  }
220
- subscribeLiveEvents(_callback) {
221
- return () => {
339
+ // ── Native capabilities ────────────────────────────────────────────────
340
+ registerSnapshotProvider() {
341
+ const snapshotUrl = (this.config.get("snapshotUrl") ?? "").trim();
342
+ if (!snapshotUrl) return;
343
+ const provider = {
344
+ getSnapshot: async ({ deviceId }) => {
345
+ if (deviceId !== this.id) {
346
+ throw new Error(`RtspCamera: deviceId mismatch, expected ${this.id}, got ${deviceId}`);
347
+ }
348
+ const buf = await this.fetchHttpSnapshot(snapshotUrl);
349
+ if (buf.length === 0) return null;
350
+ return { base64: buf.toString("base64"), contentType: "image/jpeg" };
351
+ },
352
+ invalidateCache: async () => {
353
+ }
222
354
  };
355
+ this.ctx.registerNativeCap(import_types.snapshotCapability, provider);
223
356
  }
224
- buildDevice(device, settings) {
225
- const deviceCtx = {
226
- id: `device:${device.id}`,
227
- logger: this.ctx.logger.child(device.name),
228
- eventBus: this.ctx.eventBus,
229
- storage: this.ctx.storage,
230
- config: this.ctx.config
231
- };
232
- return new RtspDevice(device, settings, deviceCtx);
357
+ async fetchHttpSnapshot(url) {
358
+ const username = (this.config.get("username") ?? "").trim();
359
+ const password = (this.config.get("password") ?? "").trim();
360
+ const headers = {};
361
+ if (username || password) {
362
+ const creds = Buffer.from(`${username}:${password}`).toString("base64");
363
+ headers["authorization"] = `Basic ${creds}`;
364
+ }
365
+ const res = await fetch(url, { headers });
366
+ if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
367
+ const ab = await res.arrayBuffer();
368
+ return Buffer.from(ab);
233
369
  }
234
370
  };
235
371
 
236
372
  // src/addon.ts
237
- var RtspProviderAddon = class {
238
- manifest = {
239
- id: "provider-rtsp",
240
- name: "RTSP Camera Provider",
241
- version: "0.1.0",
242
- description: "Direct connection to cameras via RTSP URL",
243
- capabilities: ["device-provider"]
373
+ function getString(obj, key) {
374
+ const v = obj[key];
375
+ return typeof v === "string" ? v : "";
376
+ }
377
+ function getStringArray(obj, key) {
378
+ const v = obj[key];
379
+ if (!Array.isArray(v)) return [];
380
+ return v.filter((s) => typeof s === "string").map((s) => s.trim()).filter((s) => s.length > 0);
381
+ }
382
+ function buildCreationFormSchema() {
383
+ return {
384
+ sections: [
385
+ {
386
+ id: "identity",
387
+ title: "Camera",
388
+ columns: 1,
389
+ fields: [
390
+ { type: "text", key: "name", label: "Name", required: true, placeholder: "Living room" }
391
+ ]
392
+ },
393
+ {
394
+ id: "streams",
395
+ title: "RTSP Streams",
396
+ description: "Provide 1\u20133 RTSP URLs for this camera. Each URL is probed and published to the stream-broker; the broker assigns the (high / mid / low) profiles by resolution \u2014 you do not need to label the streams manually.",
397
+ columns: 1,
398
+ fields: [
399
+ {
400
+ type: "probe",
401
+ key: "streams",
402
+ label: "RTSP stream URL",
403
+ required: true,
404
+ placeholder: "rtsp://user:pass@host:554/Streaming/Channels/101",
405
+ inputType: "url",
406
+ multiple: {
407
+ min: 1,
408
+ max: 3,
409
+ addLabel: "Add stream",
410
+ itemLabel: "Stream ${n}",
411
+ itemDefault: ""
412
+ }
413
+ }
414
+ ]
415
+ },
416
+ {
417
+ id: "snapshot",
418
+ title: "Snapshot",
419
+ columns: 1,
420
+ fields: [
421
+ { type: "probe", key: "snapshotUrl", label: "Snapshot URL", description: "Optional HTTP(S) endpoint that returns a JPEG still.", placeholder: "http://host/ISAPI/Streaming/channels/101/picture", inputType: "url" }
422
+ ]
423
+ },
424
+ {
425
+ id: "credentials",
426
+ title: "Credentials",
427
+ description: "Optional. If the RTSP URL already contains user:pass@ you can leave these empty.",
428
+ columns: 2,
429
+ fields: [
430
+ { type: "text", key: "username", label: "Username" },
431
+ { type: "password", key: "password", label: "Password", showToggle: true }
432
+ ]
433
+ }
434
+ ]
244
435
  };
245
- provider = null;
246
- async initialize(context) {
247
- const registry = context.integrationRegistry;
248
- if (!registry) {
249
- context.logger.warn("IntegrationRegistry not available \u2014 RTSP provider cannot start");
250
- return;
251
- }
252
- let integration = registry.getIntegrationByAddonId("provider-rtsp");
253
- if (!integration) {
254
- integration = registry.createIntegration({
255
- addonId: "provider-rtsp",
256
- name: "RTSP Cameras",
257
- enabled: true,
258
- info: { discoveryMode: "manual", icon: "assets/icon.svg", color: "#78716c" }
259
- });
260
- context.logger.info(`Created RTSP integration: ${integration.id}`);
261
- }
262
- if (!integration.enabled) {
263
- context.logger.info("RTSP integration is disabled \u2014 skipping start");
264
- return;
265
- }
266
- this.provider = new RtspProvider(integration, registry, {
267
- id: context.id,
268
- logger: context.logger,
269
- eventBus: context.eventBus,
270
- storage: context.storage,
271
- config: context.config
272
- });
273
- await this.provider.start();
274
- context.logger.info(`RTSP provider started (integration=${integration.id}, devices=${this.provider.getDevices().length})`);
436
+ }
437
+ function isStreamBrokerReady(event) {
438
+ if (event.category !== "system.ready-state") return false;
439
+ const data = event.data;
440
+ return data["capName"] === "stream-broker" && data["state"] === "ready";
441
+ }
442
+ var RtspProviderAddon = class extends import_types2.BaseDeviceProvider {
443
+ addonId = "provider-rtsp";
444
+ providerName = "RTSP";
445
+ deviceClasses = {
446
+ [import_types2.DeviceType.Camera]: RtspCamera
447
+ };
448
+ constructor() {
449
+ super({});
275
450
  }
276
- async shutdown() {
277
- await this.provider?.stop();
278
- this.provider = null;
451
+ async onInitialize() {
452
+ const regs = await super.onInitialize();
453
+ this.subscribe(
454
+ { category: import_types2.EventCategory.DeviceStateChanged },
455
+ (event) => {
456
+ const data = event.data;
457
+ if (data.capName !== "camera-streams") return;
458
+ const deviceId = data.deviceId;
459
+ if (typeof deviceId !== "number") return;
460
+ const registry = this.ctx.kernel.deviceRegistry;
461
+ if (!registry) return;
462
+ if (registry.getAddonId(deviceId) !== this.addonId) return;
463
+ const device = registry.getById(deviceId);
464
+ if (!device) return;
465
+ const online = data.slice?.online === true;
466
+ if (device.online !== online) device.online = online;
467
+ }
468
+ );
469
+ this.subscribe(
470
+ { category: import_types2.EventCategory.SystemReadyState },
471
+ (event) => {
472
+ if (!isStreamBrokerReady(event)) return;
473
+ void this.republishAll().catch((err) => {
474
+ this.ctx.logger.warn("Failed to re-publish RTSP streams after broker ready", {
475
+ meta: { error: err instanceof Error ? err.message : String(err) }
476
+ });
477
+ });
478
+ }
479
+ );
480
+ return regs;
279
481
  }
280
- getCapabilityProvider(name) {
281
- if (name === "device-provider" && this.provider) {
282
- return this.provider;
283
- }
284
- return null;
482
+ // ── Creation ─────────────────────────────────────────────────────────
483
+ async onGetCreationSchema(type) {
484
+ if (type !== import_types2.DeviceType.Camera) return null;
485
+ return buildCreationFormSchema();
285
486
  }
286
- getConfigSchema() {
287
- return {
288
- sections: [
289
- {
290
- id: "general",
291
- title: "RTSP Provider",
292
- description: "Configure generic RTSP camera connections",
293
- columns: 1,
294
- fields: [
295
- { type: "text", key: "name", label: "Provider Name", placeholder: "RTSP Cameras" },
296
- {
297
- type: "info",
298
- key: "info",
299
- label: "Camera Configuration",
300
- content: "Individual cameras are configured via the device management interface after adding this provider.",
301
- variant: "info"
302
- }
303
- ]
487
+ async onCreateDevice(type, config) {
488
+ if (type !== import_types2.DeviceType.Camera) {
489
+ throw new Error(`RTSP provider does not support device type: ${type}`);
490
+ }
491
+ const name = getString(config, "name").trim();
492
+ if (!name) throw new Error("Camera name is required");
493
+ const rawStreams = getStringArray(config, "streams");
494
+ if (rawStreams.length === 0) throw new Error("At least one RTSP stream URL is required");
495
+ if (rawStreams.length > 3) throw new Error("At most 3 RTSP stream URLs are supported");
496
+ const streamProbe = this.ctx.kernel.streamProbe;
497
+ if (!streamProbe) throw new Error("ctx.kernel.streamProbe unavailable \u2014 cannot probe streams");
498
+ const probed = await Promise.all(
499
+ rawStreams.map(async (url) => {
500
+ try {
501
+ const metadata = await streamProbe.probe(url, { force: false });
502
+ return { url, metadata, ok: true };
503
+ } catch (err) {
504
+ this.ctx.logger.warn(
505
+ "[rtsp-create] probe failed \u2014 publishing without probed metadata",
506
+ { meta: { url: (0, import_types2.maskUrlCredentials)(url), error: err instanceof Error ? err.message : String(err) } }
507
+ );
508
+ return { url, metadata: void 0, ok: false };
304
509
  }
305
- ]
510
+ })
511
+ );
512
+ const classified = (0, import_types2.classifyStreams)(
513
+ probed.map((p) => ({ url: p.url, metadata: p.metadata ?? {} }))
514
+ );
515
+ const hintByUrl = new Map(classified.map((c) => [c.url, c.quality]));
516
+ const streams = probed.map((p, i) => {
517
+ const entry = { id: `stream-${i + 1}`, url: p.url };
518
+ const hint = hintByUrl.get(p.url);
519
+ if (hint) entry.profileHint = hint;
520
+ if (p.metadata?.width && p.metadata?.height) {
521
+ entry.resolution = { width: p.metadata.width, height: p.metadata.height };
522
+ }
523
+ return entry;
524
+ });
525
+ const parsed = rtspCameraSchema.parse({
526
+ streams,
527
+ snapshotUrl: getString(config, "snapshotUrl"),
528
+ username: getString(config, "username"),
529
+ password: getString(config, "password")
530
+ });
531
+ return {
532
+ meta: { type: import_types2.DeviceType.Camera, name },
533
+ config: parsed
306
534
  };
307
535
  }
308
- getConfig() {
309
- return {};
536
+ // ── Field probing ────────────────────────────────────────────────────
537
+ async testCreationField(input) {
538
+ if (input.type !== import_types2.DeviceType.Camera) {
539
+ return { status: "error", error: `Unsupported device type: ${input.type}` };
540
+ }
541
+ const streamProbe = this.ctx.kernel.streamProbe;
542
+ if (!streamProbe) {
543
+ return { status: "error", error: "ctx.kernel.streamProbe unavailable \u2014 cannot reach kernel probe" };
544
+ }
545
+ return streamProbe.probeField(input.key, input.value);
310
546
  }
311
- async onConfigChange(_config) {
547
+ // ── Restore ──────────────────────────────────────────────────────────
548
+ //
549
+ // `BaseDeviceProvider.onRestoreDevices` default impl iterates
550
+ // `savedDevices`, looks up the right class via `deviceClasses`,
551
+ // and calls `kernel.devices.create()`. Each created device fires
552
+ // its `onCreated` lifecycle hook (see `RtspCamera.onCreated()`)
553
+ // which publishes streams to the broker — no per-provider override
554
+ // needed here.
555
+ // ── Internal — re-publish every RtspCamera to the broker ────────────
556
+ async republishAll() {
557
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
558
+ let published = 0;
559
+ for (const dev of all) {
560
+ if (!(dev instanceof RtspCamera)) continue;
561
+ try {
562
+ await dev.publishToBroker();
563
+ published++;
564
+ } catch (err) {
565
+ this.ctx.logger.debug("publishToBroker threw during republish", {
566
+ tags: { deviceId: dev.id },
567
+ meta: { error: err instanceof Error ? err.message : String(err) }
568
+ });
569
+ }
570
+ }
571
+ if (published > 0) {
572
+ this.ctx.logger.info("Re-published RTSP streams to stream-broker", {
573
+ meta: { published, total: all.length }
574
+ });
575
+ }
312
576
  }
313
577
  };
314
578
  // Annotate the CommonJS export names for ESM import in node: