unifi-protect 4.28.0 → 4.29.0

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/README.md CHANGED
@@ -12,7 +12,7 @@
12
12
  </DIV>
13
13
  </SPAN>
14
14
 
15
- `unifi-protect` is a library that enabled you to connect to and communicate with the Ubiquiti UniFi Protect API and ecosystem. [UniFi Protect](https://ui.com/camera-security) is [Ubiquiti's](https://www.ui.com) next-generation video security platform, with rich camera, doorbell, and NVR controller hardware options for you to choose from, as well as an app which you can use to view, configure and manage your video camera and doorbells.
15
+ `unifi-protect` is a library that enables you to connect to and communicate with the Ubiquiti UniFi Protect API and ecosystem. [UniFi Protect](https://ui.com/camera-security) is [Ubiquiti's](https://www.ui.com) next-generation video security platform, with rich camera, doorbell, and NVR controller hardware options for you to choose from, as well as an app which you can use to view, configure and manage your video camera and doorbells.
16
16
 
17
17
  ## Why use this library for UniFi Protect support?
18
18
  In short - because I use it every day to support a very popular [Homebridge](https://homebridge.io) plugin named [homebridge-unifi-protect](https://www.npmjs.com/package/homebridge-unifi-protect) that I maintain. I have been occasionally asked if I would consider packaging the core API library separately from the plugin so that other open source projects can take advantage of the work that's been done here to understand and decode the UniFi Protect API.
@@ -42,6 +42,23 @@ To use this library in Node, install it from the command line:
42
42
  npm install unifi-protect
43
43
  ```
44
44
 
45
+ ## Usage
46
+
47
+ ```typescript
48
+ import { ProtectApi } from "unifi-protect";
49
+
50
+ const protect = new ProtectApi();
51
+
52
+ await protect.login("192.168.1.1", "username", "password");
53
+ await protect.getBootstrap();
54
+
55
+ // Access your devices.
56
+ const cameras = protect.bootstrap?.cameras ?? [];
57
+
58
+ // Listen for real-time events.
59
+ protect.on("message", (packet) => console.log(packet.header.modelKey, packet.header.action));
60
+ ```
61
+
45
62
  ## Documentation
46
63
 
47
64
  Documentation and examples for using this library to access UniFi Protect controllers is [available here](https://github.com/hjdhjd/unifi-protect/blob/main/docs/ProtectApi.md). Additionally, if you'd like to see all this in action in a well-documented, real-world example, please take a good look at my [homebridge-unifi-protect](https://github.com/hjdhjd/homebridge-unifi-protect) project. It relies heavily on this library for the core functionality it provides.
@@ -53,7 +70,7 @@ Reverse engineering the realtime events API is a bit more difficult than the sys
53
70
 
54
71
  The Protect realtime events API, however, is a binary protocol published over the `updates` websocket, and until now has been undocumented. I spent time analyzing what's happening in the Protect browser webUI as well as observing the controller and various Protect versions themselves to reverse engineer what's going on. Pouring through obfuscated code is like solving a puzzle with all the pieces in front of you - you know it's all there, you're just not always sure how it fits together.
55
72
 
56
- For the impatient, you can take a look at the code for how to decode and read the binary protocol here in [protect-updates-api.ts](https://github.com/hjdhjd/unifi-protect/blob/master/src/protect-api-events.ts) and the interface information located in [protect-types.ts](https://github.com/hjdhjd/unifi-protect/blob/master/src/protect-types.ts) as well.
73
+ For the impatient, you can take a look at the code for how to decode and read the binary protocol here in [protect-api-events.ts](https://github.com/hjdhjd/unifi-protect/blob/main/src/protect-api-events.ts) and the interface information located in [protect-types.ts](https://github.com/hjdhjd/unifi-protect/blob/main/src/protect-types.ts) as well.
57
74
 
58
75
  I welcome any additions or corrections to the protocol for the benefit of the community. I hope this helps others launch their own exploration and create new and interesting Protect-enabled capabilities.
59
76
 
@@ -63,9 +80,9 @@ This list represents all known apps that are using the realtime events API for U
63
80
  * [homebridge-unifi-protect](https://github.com/hjdhjd/homebridge-unifi-protect): Seamless integration of UniFi Protect into HomeKit with support for cameras, doorbells, and more.
64
81
 
65
82
  #### Connecting
66
- * Login to the UniFi Protect controller and obtain the bootstrap JSON. The URL is: `https://protect-nvr-ip/proxy/protect/api/bootstrap`. You can look through [protect-api.ts](https://github.com/hjdhjd/unifi-protect/blob/master/src/protect-api.ts) for a better understanding of the Protect login process and how to obtain the bootstrap JSON.
67
- * Open the websocket to the updates URL. The URL is: `wss://protect-nvr-ip/proxy/protect/ws/updates?lastUpdateId?lastUpdateId=X`. You can grab lastUpdateId from the bootstrap JSON in the prior step. You can [see an example in protect-api.ts](https://github.com/hjdhjd/unifi-protect/blob/src/protect-api.ts#L225).
68
- * Then you're ready to listen to messages. You can see an [example of this in protect-nvr.ts](https://github.com/hjdhjd/unifi-protect/blob/src/protect-nvr.ts#L408).
83
+ * Login to the UniFi Protect controller and obtain the bootstrap JSON. The URL is: `https://protect-nvr-ip/proxy/protect/api/bootstrap`. You can look through [protect-api.ts](https://github.com/hjdhjd/unifi-protect/blob/main/src/protect-api.ts) for a better understanding of the Protect login process and how to obtain the bootstrap JSON.
84
+ * Open the websocket to the updates URL. The URL is: `wss://protect-nvr-ip/proxy/protect/ws/updates?lastUpdateId=X`. You can grab lastUpdateId from the bootstrap JSON in the prior step. You can [see an example in protect-api.ts](https://github.com/hjdhjd/unifi-protect/blob/main/src/protect-api.ts).
85
+ * Then you're ready to listen to messages. You can see an [example of this in protect-api.ts](https://github.com/hjdhjd/unifi-protect/blob/main/src/protect-api.ts).
69
86
 
70
87
  Those are the basics and gets us up and running. Now, to explain how the updates API works...
71
88
 
@@ -89,7 +106,7 @@ So how does it all work? Cameras continuously stream updates to the UniFi Protec
89
106
  Let's look at each of these.
90
107
 
91
108
  ##### Header Frame
92
- The header frame is required overhead since websockets provide only a transport medium. It's purpose is to tell us what's coming in the frame that follows.
109
+ The header frame is required overhead since websockets provide only a transport medium. Its purpose is to tell us what's coming in the frame that follows.
93
110
 
94
111
  A packet header is composed of 8 bytes in this order:
95
112
 
@@ -118,16 +135,16 @@ The final part of the update packet is the data frame. The data frame can be thr
118
135
 
119
136
  | Payload Type | Description
120
137
  |--------------|------------------------------------------------------------------------------------
121
- | 1 | JSON. If the action frame's `action` property is set to `update` and the `modelKey` property is not set to `event` (e.g. `camera`), this will **always** a subset of the [configuration bootstrap JSON](https://github.com/hjdhjd/unifi-protect/blob/src/protect-types.ts#L6).
138
+ | 1 | JSON. If the action frame's `action` property is set to `update` and the `modelKey` property is not set to `event` (e.g. `camera`), this will **always** be a subset of the [configuration bootstrap JSON](https://github.com/hjdhjd/unifi-protect/blob/main/src/protect-types.ts).
122
139
  | 2 | A UTF8-encoded string.
123
140
  | 3 | Node Buffer.
124
141
 
125
142
  #### Tips
126
- * `update` actions are always tied to any valid modelKey that exists in the bootstrap JSON. The exception is `events` which is tied to the Protect events history list that it maintains. The supported modelKeys from the bootstrap JSON are: `bridge`, `camera`, `group`, `light`, `liveview`, `nvr`, `sensor`, `user`, and `viewer`.
127
- * `add` actions are always tied to the `event` modelKey and indicate the beginning of an event item in the Protect events list. A subsequent `update` action is sent signaling the end of the event capture, and it's confidence score for motion detection.
143
+ * `update` actions are always tied to any valid modelKey that exists in the bootstrap JSON. The exception is `event` which is tied to the Protect events history list that it maintains. The supported modelKeys from the bootstrap JSON are: `bridge`, `camera`, `chime`, `group`, `light`, `liveview`, `nvr`, `sensor`, `user`, and `viewer`.
144
+ * `add` actions are always tied to the `event` modelKey and indicate the beginning of an event item in the Protect events list. A subsequent `update` action is sent signaling the end of the event capture, and its confidence score for motion detection.
128
145
  * This is **not** the same thing as motion detection. If you want to detect motion, you should watch the `update` action for `camera` modelKeys, and look for a JSON that updates `lastMotion`. For doorbell rings, `lastRing`. The Protect events list is useful for the Protect app, but it's of limited utility to HomeKit, and it's slow relative to just looking for the `lastMotion` JSON that tends to be much more timely in its delivery. If you want true realtime events, you want to look at the `update` action.
129
146
  * JSONs are only payload type that seems to be sent, although the protocol is designed to accept all three.
130
- * With the exception of `update` actions with a `modelKey` of `event`, JSONs are always a subset of the bootstrap JSON, indexed off of `modelKey`. So for a `modelKey` of `camera`, the data payload is always a subset of ProtectCameraConfigInterface (see [protect-types.ts](https://github.com/hjdhjd/unifi-protect/blob/src/protect-types.ts#L108)).
147
+ * With the exception of `update` actions with a `modelKey` of `event`, JSONs are always a subset of the bootstrap JSON, indexed off of `modelKey`. So for a `modelKey` of `camera`, the data payload is always a subset of ProtectCameraConfigInterface (see [protect-types.ts](https://github.com/hjdhjd/unifi-protect/blob/main/src/protect-types.ts)).
131
148
 
132
149
  ## Library Development Dashboard
133
150
  This is mostly of interest to the true developer nerds amongst us.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /** @internal */
2
2
  export * from "./protect-api.js";
3
- export type { ProtectLivestream } from "./protect-api-livestream.js";
4
- export { ProtectEventPacket, decodePacket } from "./protect-api-events.js";
3
+ export type { LivestreamOptions, ProtectLivestream } from "./protect-api-livestream.js";
4
+ export { type ProtectEventHeader, type ProtectEventPacket, decodePacket } from "./protect-api-events.js";
5
5
  export * from "./protect-logging.js";
6
6
  export * from "./protect-types.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,gBAAgB;AAEhB,kBAAkB;AAClB,cAAc,kBAAkB,CAAC;AAEjC,OAAO,EAAsB,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAC3E,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,gBAAgB;AAEhB,kBAAkB;AAClB,cAAc,kBAAkB,CAAC;AAEjC,OAAO,EAAoD,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACzG,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC"}
@@ -20,7 +20,7 @@
20
20
  * ----------------
21
21
  * ```
22
22
  *
23
- * The header frame is required overhead since websockets provide only a transport medium. It's purpose is to tell us what's coming in the frame that follows.
23
+ * The header frame is required overhead since websockets provide only a transport medium. Its purpose is to tell us what's coming in the frame that follows.
24
24
  *
25
25
  * The action frame identifies what the action and category that the update contains:
26
26
  *
@@ -42,14 +42,16 @@
42
42
  *
43
43
  * Some tips:
44
44
  *
45
- * - `update` actions are always tied to the following modelKeys: camera, event, nvr, and user.
45
+ * - `update` actions are always tied to any valid modelKey that exists in the bootstrap JSON. The exception is `event` which is tied to the Protect events history list
46
+ * that it maintains. The supported modelKeys from the bootstrap JSON are: `bridge`, `camera`, `chime`, `group`, `light`, `liveview`, `nvr`, `sensor`, `user`, and
47
+ * `viewer`.
46
48
  *
47
49
  * - `add` actions are always tied to the `event` modelKey and indicate the beginning of an event item in the Protect events list. A subsequent `update` action is sent
48
- * signaling the end of the event capture, and it's confidence score for motion detection.
50
+ * signaling the end of the event capture, and its confidence score for motion detection.
49
51
  *
50
52
  * - The above is NOT the same thing as motion detection. If you want to detect motion, you should watch the `update` action for `camera` modelKeys, and look for a JSON
51
53
  * that updates lastMotion. For doorbell rings, lastRing. The Protect events list is useful for the Protect app, but it's of limited utility to HomeKit, and it's slow
52
- * = relative to looking for lastMotion that is. If you want true realtime updates, you want to look at the `update` action.
54
+ * relative to just looking for the lastMotion update. If you want true realtime updates, you want to look at the `update` action.
53
55
  *
54
56
  * - JSONs are only payload type that seems to be sent, although the protocol is designed to accept all three.
55
57
  *
@@ -63,9 +65,6 @@ import type { ProtectLogging } from "./protect-logging.js";
63
65
  /**
64
66
  * UniFi Protect event packet.
65
67
  *
66
- * @param header - Protect event header.
67
- * @param payload - Protect event payload.
68
- *
69
68
  * @remarks A UniFi Protect event packet represents a realtime event update from a UniFi Protect controller. There are two components to each packet, a `header` and
70
69
  * a `payload`. The `header` contains information about which Protect device and what action category it belongs to. The `payload` contains the detailed information
71
70
  * related to the device and action specified in the header.
@@ -77,9 +76,6 @@ export interface ProtectEventPacket {
77
76
  /**
78
77
  * UniFi Protect event header.
79
78
  *
80
- * @param header - Protect event header.
81
- * @param payload - Protect event payload.
82
- *
83
79
  * @remarks A UniFi Protect event packet represents a realtime event update from a UniFi Protect controller. There are two components to each packet, a `header` and
84
80
  * a `payload`. The `header` contains information about which Protect device and what action category it belongs to and can contain arbitrary information, though has
85
81
  * a few properties that are always present (`action`, `id`, `modelKey`, and `newUpdateId`). The `payload` contains the detailed information related to the device and
@@ -101,7 +97,7 @@ export interface ProtectEventHeader {
101
97
  * @returns Promise resolving to a decoded event packet, or `null` if decoding fails.
102
98
  *
103
99
  * @remarks A UniFi Protect event packet is an encoded representation of state updates that occur in a UniFi Protect controller. This utility function takes an
104
- * encoded packet as an input, and decodes it into an event header and payload that can be acted upon. An example of it's use is in {@link ProtectApi} where, once
100
+ * encoded packet as an input, and decodes it into an event header and payload that can be acted upon. An example of its use is in {@link ProtectApi} where, once
105
101
  * successfully logged into the Protect controller, events are generated automatically and can be accessed by listening to `message` events emitted by
106
102
  * {@link ProtectApi}.
107
103
  */
@@ -11,8 +11,8 @@ const EVENT_PACKET_HEADER_SIZE = 8;
11
11
  // Update realtime API packet types.
12
12
  var ProtectEventPacketType;
13
13
  (function (ProtectEventPacketType) {
14
- ProtectEventPacketType[ProtectEventPacketType["HEADER"] = 1] = "HEADER";
15
- ProtectEventPacketType[ProtectEventPacketType["PAYLOAD"] = 2] = "PAYLOAD";
14
+ ProtectEventPacketType[ProtectEventPacketType["ACTION"] = 1] = "ACTION";
15
+ ProtectEventPacketType[ProtectEventPacketType["DATA"] = 2] = "DATA";
16
16
  })(ProtectEventPacketType || (ProtectEventPacketType = {}));
17
17
  // Update realtime API payload types.
18
18
  var EventPayloadType;
@@ -28,7 +28,7 @@ var EventPayloadType;
28
28
  *
29
29
  * | Byte Offset | Description | Bits | Values |
30
30
  * |-------------|----------------|------|-----------------------------------------------------------------------|
31
- * | 0 | Packet Type | 8 | 1 - header frame, 2 - payload frame. |
31
+ * | 0 | Packet Type | 8 | 1 - action frame, 2 - data frame. |
32
32
  * | 1 | Payload Format | 8 | 1 - JSON object, 2 - UTF8-encoded string, 3 - Node Buffer. |
33
33
  * | 2 | Deflated | 8 | 0 - uncompressed, 1 - compressed / deflated (zlib-based compression). |
34
34
  * | 3 | Unknown | 8 | Always 0. Possibly reserved for future use by Ubiquiti? |
@@ -51,7 +51,7 @@ var ProtectEventPacketHeader;
51
51
  * @returns Promise resolving to a decoded event packet, or `null` if decoding fails.
52
52
  *
53
53
  * @remarks A UniFi Protect event packet is an encoded representation of state updates that occur in a UniFi Protect controller. This utility function takes an
54
- * encoded packet as an input, and decodes it into an event header and payload that can be acted upon. An example of it's use is in {@link ProtectApi} where, once
54
+ * encoded packet as an input, and decodes it into an event header and payload that can be acted upon. An example of its use is in {@link ProtectApi} where, once
55
55
  * successfully logged into the Protect controller, events are generated automatically and can be accessed by listening to `message` events emitted by
56
56
  * {@link ProtectApi}.
57
57
  */
@@ -59,7 +59,7 @@ export async function decodePacket(log, packet) {
59
59
  // What we need to do here is to split this packet into the header and payload, and decode them.
60
60
  let dataOffset;
61
61
  try {
62
- // The fourth byte holds our payload size. When you add the payload size to our header frame size, you get the location of the
62
+ // The payload size begins at byte offset 4 as a big-endian 32-bit integer. When you add the payload size to our header frame size, you get the location of the
63
63
  // data header frame.
64
64
  dataOffset = packet.readUInt32BE(ProtectEventPacketHeader.PAYLOAD_SIZE) + EVENT_PACKET_HEADER_SIZE;
65
65
  // Validate our packet size, just in case we have more or less data than we expect. If we do, we're done for now.
@@ -74,14 +74,14 @@ export async function decodePacket(log, packet) {
74
74
  // Decode the action and payload frames in parallel. Both frames are independent and may require zlib decompression, so inflating them concurrently maximizes
75
75
  // throughput on the libuv threadpool.
76
76
  try {
77
- const [headerFrame, payloadFrame] = await Promise.all([
78
- decodeFrame(log, packet.subarray(0, dataOffset), ProtectEventPacketType.HEADER),
79
- decodeFrame(log, packet.subarray(dataOffset), ProtectEventPacketType.PAYLOAD)
77
+ const [actionFrame, dataFrame] = await Promise.all([
78
+ decodeFrame(log, packet.subarray(0, dataOffset), ProtectEventPacketType.ACTION),
79
+ decodeFrame(log, packet.subarray(dataOffset), ProtectEventPacketType.DATA)
80
80
  ]);
81
- if (!headerFrame || !payloadFrame) {
81
+ if (!actionFrame || !dataFrame) {
82
82
  return null;
83
83
  }
84
- return ({ header: headerFrame, payload: payloadFrame });
84
+ return ({ header: actionFrame, payload: dataFrame });
85
85
  }
86
86
  catch (error) {
87
87
  log.error("Realtime events API: error decoding update packet: %s.", error);
@@ -101,8 +101,8 @@ async function decodeFrame(log, packet, packetType) {
101
101
  // Decompress the payload if the deflated flag is set, using async inflate to avoid blocking the event loop. For uncompressed payloads, we just slice past the header.
102
102
  const payload = packet.readUInt8(ProtectEventPacketHeader.DEFLATED) ?
103
103
  await inflateAsync(packet.subarray(EVENT_PACKET_HEADER_SIZE)) : packet.subarray(EVENT_PACKET_HEADER_SIZE);
104
- // If it's a header, it can only have one format.
105
- if (frameType === ProtectEventPacketType.HEADER) {
104
+ // If it's an action frame, it can only have one format.
105
+ if (frameType === ProtectEventPacketType.ACTION) {
106
106
  return (payloadFormat === EventPayloadType.JSON) ? JSON.parse(payload.toString()) : null;
107
107
  }
108
108
  // Process the payload format accordingly.
@@ -1 +1 @@
1
- {"version":3,"file":"protect-api-events.js","sourceRoot":"","sources":["../src/protect-api-events.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAgEH,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,6EAA6E;AAC7E,MAAM,YAAY,GAAG,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAE7C,yDAAyD;AACzD,MAAM,wBAAwB,GAAG,CAAC,CAAC;AAEnC,oCAAoC;AACpC,IAAK,sBAIJ;AAJD,WAAK,sBAAsB;IAEzB,uEAAU,CAAA;IACV,yEAAW,CAAA;AACb,CAAC,EAJI,sBAAsB,KAAtB,sBAAsB,QAI1B;AAED,qCAAqC;AACrC,IAAK,gBAKJ;AALD,WAAK,gBAAgB;IAEnB,uDAAQ,CAAA;IACR,2DAAU,CAAA;IACV,2DAAU,CAAA;AACZ,CAAC,EALI,gBAAgB,KAAhB,gBAAgB,QAKpB;AAED;;;;;;;;;;;;GAYG;AACH,IAAK,wBAOJ;AAPD,WAAK,wBAAwB;IAE3B,uEAAQ,CAAA;IACR,2FAAkB,CAAA;IAClB,+EAAY,CAAA;IACZ,6EAAW,CAAA;IACX,uFAAgB,CAAA;AAClB,CAAC,EAPI,wBAA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35
- * 3. Listen for `message` events emitted by {@link ProtectLivestream} which provides Buffers containing the raw fMP4 segment data as it's produced by Protect. You can
35
+ * 4. Listen for `message` events emitted by {@link ProtectLivestream} which provides Buffers containing the raw fMP4 segment data as it's produced by Protect. You can
36
36
  * alternatively listen individually for the initialization segment or regular fMP4 segments if you'd like to distinguish between the two types of segments.
37
37
  *
38
38
  * Those are the basics that gets us up and running.
@@ -59,12 +59,11 @@ export declare class ProtectLivestream extends EventEmitter {
59
59
  private _codec;
60
60
  private _stream;
61
61
  private api;
62
- private errorHandler;
63
62
  private heartbeat;
64
63
  private initSegmentPromise?;
65
64
  private lastMessage;
66
65
  private log;
67
- private messageHandler;
66
+ private sessionAbort;
68
67
  private ws;
69
68
  constructor(api: ProtectApi, log: ProtectLogging);
70
69
  /**
@@ -81,7 +80,7 @@ export declare class ProtectLivestream extends EventEmitter {
81
80
  * @event initsegment - Emitted with the initialization segment Buffer containing FTYP and MOOV boxes (stream mode disabled only).
82
81
  * @event message - Emitted with each complete fMP4 segment Buffer, both initialization and regular segments (stream mode disabled only).
83
82
  * @event segment - Emitted with each complete non-initialization segment Buffer containing MOOF/MDAT pairs (stream mode disabled only).
84
- * @event timestamps - Emitted with decode timestamp arrays when extendedVideoMetadata is enabled in options.
83
+ * @event timestamps - Emitted with decode timestamp arrays when emitTimestamps is enabled in options.
85
84
  *
86
85
  * @remarks Once a livestream session has started, the following events can be listened for (unless you've specified `useStream` in `options`, in which case only the
87
86
  * `close` event is available):
@@ -125,9 +124,13 @@ export declare class ProtectLivestream extends EventEmitter {
125
124
  /**
126
125
  * Retrieve the initialization segment that must be at the start of every fMP4 stream.
127
126
  *
127
+ * @remarks If the stream is stopped before the initialization segment is received, the returned promise rejects with an AbortError. Callers should handle this
128
+ * rejection or wrap the call with a timeout.
129
+ *
128
130
  * @returns Returns a promise that resolves once the initialization segment has been seen, or returning it immediately if it already has been.
129
131
  */
130
132
  getInitSegment(): Promise<Buffer>;
133
+ private awaitInitSegment;
131
134
  /**
132
135
  * The initialization segment that must be at the start of every fMP4 stream.
133
136
  *
@@ -137,7 +140,7 @@ export declare class ProtectLivestream extends EventEmitter {
137
140
  /**
138
141
  * The codecs in use for this livestream session.
139
142
  *
140
- * @returns Returns a string containing the codec information,if it exists, or `null` otherwise.
143
+ * @returns Returns a string containing the codec information, if it exists, or `null` otherwise.
141
144
  *
142
145
  * @remarks Codec information is provided as `codec,container` where codec is either `avc` (H.264) or `hev` (H.265). The container format is always `mp4`.
143
146
  *
@@ -2,45 +2,39 @@
2
2
  *
3
3
  * protect-api-livestream.ts: Our UniFi Protect livestream API implementation.
4
4
  */
5
- /* eslint-disable @stylistic/max-len */
6
5
  /**
7
6
  * Access a direct MP4 livestream for a UniFi Protect camera.
8
7
  *
9
- * The UniFi Protect livestream API is largely undocumented and has been reverse engineered mostly through
10
- * trial and error, as well as observing the Protect controller in action. It builds on the works of others in the
11
- * community - particularly https://github.com/XciD - who have experimented and successfully gotten parts of this API decoded.
12
- * As always, this work stands on the contributions of others and the work that's come before it, and I want to acknowledge those
13
- * that paved the way.
8
+ * The UniFi Protect livestream API is largely undocumented and has been reverse engineered mostly through trial and error, as well as observing the Protect
9
+ * controller in action. It builds on the works of others in the community - particularly https://github.com/XciD - who have experimented and successfully
10
+ * gotten parts of this API decoded. As always, this work stands on the contributions of others and the work that's come before it, and I want to acknowledge
11
+ * those that paved the way.
14
12
  *
15
- * Let's start by defining some terms. In the MP4 world, an MP4 file (or stream) is composed of multiple atoms or segments.
16
- * Think of these as packet types that contain specific pieces of information that are needed to put together a valid MP4 file.
17
- * For our purposes, we're primarily interested in four types of MP4 boxes:
13
+ * Let's start by defining some terms. In the MP4 world, an MP4 file (or stream) is composed of multiple atoms or segments. Think of these as packet types
14
+ * that contain specific pieces of information that are needed to put together a valid MP4 file. For our purposes, we're primarily interested in four types of
15
+ * MP4 boxes:
18
16
  *
19
- * | Box | Description |
20
- * |-------|-----------------------------------------------------------------------------------------------------------------------------------------------|
21
- * | FTYP | File type box. This contains codec and file information for the stream that follows it. It must be at the beginning of any stream, and preceded by the FTYP box. |
22
- * | MDAT | Media data box. This contains a segment of the actual audio and video data in the MP4 stream. It is always paired with an MOOF box, which contains the metadata describing this payload in an MDAT box. |
23
- * | MOOF | Movie fragment box. This defines the metadata for a specific segment of audio and video. It is always paired with an MDAT box, which contains the actual data. |
24
- * | MOOV | Movie metadata box. This contains all the metadata information about the stream that follows. It must be at the beginning of any stream, and preceded by the FTYP box. The Protect livestream API actually combines the FTYP and MOOV boxes, conveniently giving us a complete initialization segment. |
17
+ * - **FTYP** - File type box. Contains codec and file information. It must be at the very beginning of any stream.
18
+ * - **MOOV** - Movie metadata box. Contains all the metadata about the stream that follows. It must be preceded by the FTYP box. The Protect livestream API
19
+ * combines the FTYP and MOOV boxes, conveniently giving us a complete initialization segment.
20
+ * - **MOOF** - Movie fragment box. Defines the metadata for a specific segment of audio and video. Always paired with an MDAT box containing the actual data.
21
+ * - **MDAT** - Media data box. Contains a segment of the actual audio and video data. Always paired with an MOOF box containing the metadata.
25
22
  *
26
- * Every fMP4 stream begins with an initialization segment comprised of the FTYP and MOOV boxes. It defines the file type,
27
- * what the movie metadata is, and other characteristics. Think of it as the header for the entire stream.
23
+ * Every fMP4 stream begins with an initialization segment comprised of the FTYP and MOOV boxes. It defines the file type, what the movie metadata is, and
24
+ * other characteristics. Think of it as the header for the entire stream.
28
25
  *
29
- * After the header, every fMP4 stream has a series of segments (sometimes called fragments, hence the term fMP4),
30
- * that consist of a pair of moof / mdat boxes that includes all the audio and video for that segment. You end up with something
31
- * that looks like:
26
+ * After the header, every fMP4 stream has a series of segments (sometimes called fragments, hence the term fMP4), that consist of a pair of MOOF/MDAT boxes
27
+ * that includes all the audio and video for that segment. You end up with something that looks like:
32
28
  *
33
29
  * ```
34
30
  * |ftyp|moov|moof|mdat|moof|mdat...
35
31
  * ```
36
32
  *
37
- * The UniFi Protect livestream API provides a straightforward interface to generate bespoke fMP4 streams that
38
- * can be tailored depending on your needs. This implementation of the API allows you to access those streams, retrieve all the relevant boxes/atoms you need to
39
- * manipulate them for your application.
33
+ * The UniFi Protect livestream API provides a straightforward interface to generate bespoke fMP4 streams that can be tailored depending on your needs. This
34
+ * implementation of the API allows you to access those streams and retrieve all the relevant boxes/atoms you need to manipulate them for your application.
40
35
  *
41
36
  * @module ProtectLivestream
42
37
  */
43
- /* eslint-enable @stylistic/max-len */
44
38
  import { WebSocket } from "undici";
45
39
  import events, { EventEmitter } from "node:events";
46
40
  import { PROTECT_LIVESTREAM_HEARTBEAT_TIMEOUT } from "./settings.js";
@@ -59,6 +53,10 @@ var ProtectLiveFrame;
59
53
  ProtectLiveFrame[ProtectLiveFrame["MDAT"] = 254] = "MDAT";
60
54
  ProtectLiveFrame[ProtectLiveFrame["ENDSEGMENT"] = 255] = "ENDSEGMENT";
61
55
  })(ProtectLiveFrame || (ProtectLiveFrame = {}));
56
+ // Pre-computed set of valid livestream frame types for O(1) validation on the hot path.
57
+ const VALID_LIVE_FRAMES = new Set(Object.values(ProtectLiveFrame).filter((v) => typeof v === "number"));
58
+ // Reusable empty buffer to avoid allocating a new zero-length buffer each time partial packet data is consumed.
59
+ const EMPTY_BUFFER = Buffer.alloc(0);
62
60
  /**
63
61
  * This class provides a complete event-driven API to access the UniFi Protect Livestream API endpoint.
64
62
  *
@@ -69,7 +67,7 @@ var ProtectLiveFrame;
69
67
  *
70
68
  * 3. Start a livestream using {@link start}, stop it with {@link stop}, and listen for events.
71
69
  *
72
- * 3. Listen for `message` events emitted by {@link ProtectLivestream} which provides Buffers containing the raw fMP4 segment data as it's produced by Protect. You can
70
+ * 4. Listen for `message` events emitted by {@link ProtectLivestream} which provides Buffers containing the raw fMP4 segment data as it's produced by Protect. You can
73
71
  * alternatively listen individually for the initialization segment or regular fMP4 segments if you'd like to distinguish between the two types of segments.
74
72
  *
75
73
  * Those are the basics that gets us up and running.
@@ -96,12 +94,11 @@ export class ProtectLivestream extends EventEmitter {
96
94
  _codec;
97
95
  _stream;
98
96
  api;
99
- errorHandler;
100
97
  heartbeat;
101
98
  initSegmentPromise;
102
99
  lastMessage;
103
100
  log;
104
- messageHandler;
101
+ sessionAbort;
105
102
  ws;
106
103
  // Create a new instance.
107
104
  constructor(api, log) {
@@ -111,11 +108,10 @@ export class ProtectLivestream extends EventEmitter {
111
108
  this._initSegment = null;
112
109
  this._stream = null;
113
110
  this.api = api;
114
- this.errorHandler = null;
115
111
  this.heartbeat = null;
116
112
  this.lastMessage = 0;
117
113
  this.log = log;
118
- this.messageHandler = null;
114
+ this.sessionAbort = null;
119
115
  this.ws = null;
120
116
  }
121
117
  /**
@@ -132,7 +128,7 @@ export class ProtectLivestream extends EventEmitter {
132
128
  * @event initsegment - Emitted with the initialization segment Buffer containing FTYP and MOOV boxes (stream mode disabled only).
133
129
  * @event message - Emitted with each complete fMP4 segment Buffer, both initialization and regular segments (stream mode disabled only).
134
130
  * @event segment - Emitted with each complete non-initialization segment Buffer containing MOOF/MDAT pairs (stream mode disabled only).
135
- * @event timestamps - Emitted with decode timestamp arrays when extendedVideoMetadata is enabled in options.
131
+ * @event timestamps - Emitted with decode timestamp arrays when emitTimestamps is enabled in options.
136
132
  *
137
133
  * @remarks Once a livestream session has started, the following events can be listened for (unless you've specified `useStream` in `options`, in which case only the
138
134
  * `close` event is available):
@@ -155,8 +151,12 @@ export class ProtectLivestream extends EventEmitter {
155
151
  options.useStream ??= false;
156
152
  // Stop any existing stream.
157
153
  this.stop();
158
- // Clear out the initialization segment.
154
+ // Create a fresh abort controller for this session. Every resource tied to the session's lifetime receives this signal...when stop() aborts it, all listeners,
155
+ // promises, and event registrations are cleaned up automatically.
156
+ this.sessionAbort = new AbortController();
157
+ // Clear out the initialization segment and any cached promise from a prior session.
159
158
  this._initSegment = null;
159
+ this.initSegmentPromise = undefined;
160
160
  // Launch the livestream.
161
161
  return this.launchLivestream(cameraId, channel, options);
162
162
  }
@@ -164,15 +164,15 @@ export class ProtectLivestream extends EventEmitter {
164
164
  * Stop an fMP4 livestream session from the Protect controller.
165
165
  */
166
166
  stop() {
167
+ // Abort the session signal. This automatically removes all WebSocket event listeners registered with the signal and rejects any pending getInitSegment() promise.
168
+ this.sessionAbort?.abort();
169
+ this.sessionAbort = null;
167
170
  // Close the websocket.
168
171
  this.ws?.close();
169
- if (this.messageHandler) {
170
- this.ws?.removeEventListener("message", this.messageHandler);
171
- this.messageHandler = null;
172
- }
173
- if (this.errorHandler) {
174
- this.ws?.removeEventListener("error", this.errorHandler);
175
- this.errorHandler = null;
172
+ // Clear the heartbeat timer.
173
+ if (this.heartbeat) {
174
+ clearInterval(this.heartbeat);
175
+ this.heartbeat = null;
176
176
  }
177
177
  // If we've created a stream, end it gracefully.
178
178
  if (this._stream) {
@@ -242,33 +242,26 @@ export class ProtectLivestream extends EventEmitter {
242
242
  read: () => { }
243
243
  });
244
244
  }
245
+ // All WebSocket listeners use the session's abort signal so they are automatically removed when stop() aborts the session.
246
+ const { signal } = this.sessionAbort ?? new AbortController();
245
247
  // Start our heartbeat once we've opened the connection.
246
248
  this.ws.addEventListener("open", () => {
247
249
  this.lastMessage = Date.now();
248
250
  // Heartbeat the controller. We need this because if we don't heartbeat the controller, it can sometimes just decide not to give us a livestream to work with, or
249
251
  // lockup due to regressions in the controller firmware. This ensures we can never hang waiting on data from the API, especially in a livestream scenario.
250
252
  this.heartbeat = setInterval(() => {
251
- // Clear out our heartbeat if our websocket no longer exists.
252
- if (!this.ws) {
253
- // Clear out our heartbeat since we're closing.
254
- if (this.heartbeat) {
255
- clearInterval(this.heartbeat);
256
- this.heartbeat = null;
257
- }
258
- return;
259
- }
260
253
  if ((Date.now() - this.lastMessage) > PROTECT_LIVESTREAM_HEARTBEAT_TIMEOUT) {
261
254
  logError("the livestream API is not responding.");
262
- if ((this.ws.readyState === WebSocket.CLOSING) || (this.ws.readyState === WebSocket.OPEN)) {
255
+ if ((this.ws?.readyState === WebSocket.CLOSING) || (this.ws?.readyState === WebSocket.OPEN)) {
263
256
  this.ws.close();
264
257
  }
265
258
  }
266
259
  }, PROTECT_LIVESTREAM_HEARTBEAT_TIMEOUT);
267
260
  // Process packets coming to our websocket.
268
261
  this.processLivestream();
269
- }, { once: true });
262
+ }, { signal });
270
263
  // Catch any errors and inform the user, if needed.
271
- this.ws.addEventListener("error", this.errorHandler = (event) => {
264
+ this.ws.addEventListener("error", (event) => {
272
265
  const error = event.error;
273
266
  // Ignore timeout errors, but notify the user about anything else.
274
267
  if (!(error instanceof TypeError) && (error.code !== "ETIMEDOUT")) {
@@ -276,20 +269,16 @@ export class ProtectLivestream extends EventEmitter {
276
269
  logError(util.inspect(error, { colors: true, depth: null, sorted: true }));
277
270
  }
278
271
  this.stop();
279
- }, { once: true });
272
+ }, { signal });
280
273
  this.ws.addEventListener("close", () => {
281
- // Clear out our heartbeat since we're closing.
282
- if (this.heartbeat) {
283
- clearInterval(this.heartbeat);
284
- this.heartbeat = null;
285
- }
286
274
  this.stop();
287
275
  this.emit("close");
288
- }, { once: true });
276
+ }, { signal });
289
277
  }
290
278
  catch (error) {
291
279
  logError("error while connecting to the livestream websocket API: %s", error);
292
280
  this.stop();
281
+ return false;
293
282
  }
294
283
  return true;
295
284
  }
@@ -320,10 +309,12 @@ export class ProtectLivestream extends EventEmitter {
320
309
  video: []
321
310
  };
322
311
  // Keep any tail bytes that didn't form a full packet yet.
323
- let packetRemaining = Buffer.alloc(0);
324
- // Process data coming in from the websocket. The handler is async because Blob data requires an await to convert to an ArrayBuffer.
312
+ let packetRemaining = EMPTY_BUFFER;
313
+ // Process data coming in from the websocket. The handler is async because Blob data requires an await to convert to an ArrayBuffer. The session's abort signal
314
+ // ensures this listener is removed when stop() is called.
315
+ const { signal } = this.sessionAbort ?? new AbortController();
325
316
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
326
- this.ws.addEventListener("message", this.messageHandler = async (event) => {
317
+ this.ws.addEventListener("message", async (event) => {
327
318
  // Update our heartbeat.
328
319
  this.lastMessage = Date.now();
329
320
  // Normalize event.data into a Buffer so we can process it.
@@ -356,7 +347,7 @@ export class ProtectLivestream extends EventEmitter {
356
347
  // If we have anything left from the last packet we processed, prepend it to this packet.
357
348
  if (packetRemaining.length > 0) {
358
349
  packet = Buffer.concat([packetRemaining, packet]);
359
- packetRemaining = Buffer.alloc(0);
350
+ packetRemaining = EMPTY_BUFFER;
360
351
  }
361
352
  let offset = 0;
362
353
  for (;;) {
@@ -369,12 +360,12 @@ export class ProtectLivestream extends EventEmitter {
369
360
  // Read the one-byte packet header.
370
361
  const header = packet.readUInt8(offset);
371
362
  // Validate our header before we do anything else.
372
- if (!Object.values(ProtectLiveFrame).includes(header)) {
363
+ if (!VALID_LIVE_FRAMES.has(header)) {
373
364
  this.log.error("Invalid header found while decoding the livestream: %s", header);
374
365
  break;
375
366
  }
376
- // Protect encodes the length of the entire fMP4 segment in the first three bytes (big-endian) of the header.
377
- const length = ((packet.readUInt8(offset + 1) << 8) | packet.readUInt8(offset + 2)) << 8 | packet.readUInt8(offset + 3);
367
+ // Protect encodes the length of the entire fMP4 segment in the three bytes following the header byte, as a big-endian 24-bit unsigned integer.
368
+ const length = packet.readUIntBE(offset + 1, 3);
378
369
  // Once we know our length, if we don't have the complete packet, we save it and punt until we see more data come across.
379
370
  if (packet.length < offset + 4 + length) {
380
371
  packetRemaining = packet.subarray(offset);
@@ -441,8 +432,8 @@ export class ProtectLivestream extends EventEmitter {
441
432
  break;
442
433
  // We've got a timestamp packet. Protect sends over decode timestamps identical to what's in the tfdt box in the segment.
443
434
  case ProtectLiveFrame.TIMESTAMP:
444
- for (let offset = 0; offset < data.length; offset += 8) {
445
- timestamps.push(Number(data.readBigUInt64BE(offset)));
435
+ for (let tsOffset = 0; tsOffset < data.length; tsOffset += 8) {
436
+ timestamps.push(Number(data.readBigUInt64BE(tsOffset)));
446
437
  }
447
438
  this.emit("timestamps", timestamps);
448
439
  break;
@@ -465,11 +456,14 @@ export class ProtectLivestream extends EventEmitter {
465
456
  // Advance the offset past this entire packet (header + payload).
466
457
  offset = dataEnd;
467
458
  }
468
- });
459
+ }, { signal });
469
460
  }
470
461
  /**
471
462
  * Retrieve the initialization segment that must be at the start of every fMP4 stream.
472
463
  *
464
+ * @remarks If the stream is stopped before the initialization segment is received, the returned promise rejects with an AbortError. Callers should handle this
465
+ * rejection or wrap the call with a timeout.
466
+ *
473
467
  * @returns Returns a promise that resolves once the initialization segment has been seen, or returning it immediately if it already has been.
474
468
  */
475
469
  async getInitSegment() {
@@ -477,9 +471,19 @@ export class ProtectLivestream extends EventEmitter {
477
471
  if (this.initSegment) {
478
472
  return this.initSegment;
479
473
  }
480
- // Cache a promise that resolves when the initsegment event is emitted. We need to wait until the initialization segment is seen and then return it.
481
- // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style
482
- return this.initSegmentPromise ??= events.once(this, "initsegment").then(() => this.initSegment);
474
+ // Cache a promise that resolves when the initsegment event is emitted, or rejects with an AbortError when the session is aborted via stop().
475
+ return this.initSegmentPromise ??= this.awaitInitSegment();
476
+ }
477
+ // Wait for the initialization segment event, gated by the session's abort signal. The init segment is guaranteed to be non-null when the event fires because the
478
+ // event handler in processLivestream sets _initSegment before emitting.
479
+ async awaitInitSegment() {
480
+ // If there's no active session, reject immediately. Calling getInitSegment() on a stopped stream has no session to produce the event and no abort signal to
481
+ // settle the promise.
482
+ if (!this.sessionAbort) {
483
+ throw new Error("No active livestream session.");
484
+ }
485
+ const [initSegment] = await events.once(this, "initsegment", { signal: this.sessionAbort.signal });
486
+ return initSegment;
483
487
  }
484
488
  /**
485
489
  * The initialization segment that must be at the start of every fMP4 stream.
@@ -492,7 +496,7 @@ export class ProtectLivestream extends EventEmitter {
492
496
  /**
493
497
  * The codecs in use for this livestream session.
494
498
  *
495
- * @returns Returns a string containing the codec information,if it exists, or `null` otherwise.
499
+ * @returns Returns a string containing the codec information, if it exists, or `null` otherwise.
496
500
  *
497
501
  * @remarks Codec information is provided as `codec,container` where codec is either `avc` (H.264) or `hev` (H.265). The container format is always `mp4`.
498
502
  *