diff --git a/README.md b/README.md
index de6b52fac..2bf2d04e9 100644
--- a/README.md
+++ b/README.md
@@ -32,7 +32,7 @@ HAP-NodeJS is not an Apple certified HAP implementation, as this is only availab
npm install @homebridge/hap-nodejs
```
-HAP-NodeJS needs Node.js `^22.12.0 || ^24 || ^26`.
+HAP-NodeJS needs Node.js `^22.20.0 || ^24 || ^26`.
The package is an ES module. Importing it works as usual, including `import hap from '@homebridge/hap-nodejs'`.
CommonJS code can still `require('@homebridge/hap-nodejs')` on the Node.js versions above.
@@ -46,6 +46,12 @@ There is also a pretty detailed guide on [how to start developing with HAP-NodeJ
Or you may just have a look at our [examples][examples-repo] repository
(or some of the old [accessory examples][example-accessories]).
+The example camera in `src/accessories/ModernCamera_example.ts` streams and records ffmpeg's test pattern with the camera features Apple introduced with iOS 27.
+It needs ffmpeg with `libx265` and `libopus`: run `npm run build`, then `node dist/accessories/ModernCamera_example.js`, and add it with the setup code it prints.
+
+Two guides cover those camera features. [Upgrading a Camera Plugin to HAP-NodeJS 2.4](guides/UpgradingCameraPlugins.md) is for plugin authors: what changed in the library and how a camera takes the new features.
+[HomeKit Cameras in iOS 27](guides/HKSV3Protocol.md) describes the features themselves and how a home hub behaves around them.
+
The API documentation can be found [here](https://developers.homebridge.io/hap-nodejs/).
See the FAQ on how to enable [debug output][faq-debug] for HAP-NodeJS.
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 5e01343fc..fdfc23a9a 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -14,6 +14,16 @@ export default antfu(
'new-cap': 'off',
// HAP-NodeJS has no logger of its own; the console is where its warnings are meant to go
'no-console': 'off',
+ // The disposal stack globals arrive with Node 24 and the library shares its process with every plugin, which is why every site imports the internal stacks by
+ // name. The preset's own restrictions stay beside them, because this entry replaces its list.
+ 'no-restricted-globals': [
+ 'error',
+ { message: 'Use `globalThis` instead.', name: 'global' },
+ { message: 'Use `globalThis` instead.', name: 'self' },
+ { message: 'Import DisposableStack from src/lib/util/disposableStack.ts, because Node 22 has no such global.', name: 'DisposableStack' },
+ { message: 'Import AsyncDisposableStack from src/lib/util/asyncDisposableStack.ts, because Node 22 has no such global.', name: 'AsyncDisposableStack' },
+ { message: 'Import SuppressedError from src/lib/util/disposableStack.ts, because Node 22 has no such global.', name: 'SuppressedError' },
+ ],
'no-undef': 'error',
'perfectionist/sort-exports': 'error',
'perfectionist/sort-imports': [
@@ -85,6 +95,16 @@ export default antfu(
'perfectionist/sort-named-imports': 'off',
},
})
+ .append({
+ // A code sample in a guide shows a few lines of a plugin: the names around them are the reader's own, and its lines are laid out to be read.
+ files: ['guides/**/*.md/**'],
+ rules: {
+ 'antfu/reasonable-newline': 'off',
+ 'no-undef': 'off',
+ 'node/prefer-global/buffer': 'off',
+ 'unused-imports/no-unused-vars': 'off',
+ },
+ })
.append({
files: ['src/**/*.spec.ts'],
rules: {
@@ -139,3 +159,82 @@ export default antfu(
'test/valid-title': 'error',
},
})
+ .append({
+ // The number-based 64-bit helpers lose precision above 2^53, which is why none of these modules reaches them: the Camera Capabilities codecs carry every uint64 wire
+ // value as a bigint, the MP4 box readers carry decode times as bigints, the recording modules carry sequence numbers, key numbers and session identifiers
+ // as bigints, the camera session helpers hold the sessions that carry those values, the SRTP context keeps its packet index exact as Numbers and reaches
+ // none of these helpers, the multi-tier stream management carries every session value as a Number or a Buffer and reaches no number-based 64-bit helper,
+ // the WebRTC stream management hands SFrame key IDs to its delegate as the bigints the codecs decode, the DER writer takes every INTEGER as a bigint, the
+ // NTP conversion answers its 64-bit fixed-point time as a bigint, and the recording provisioning record keeps the Camera Key's number and its high-water
+ // marks as bigints.
+ files: [
+ 'src/lib/camera/capabilities/**/*.ts',
+ 'src/lib/camera/mp4/**/*.ts',
+ 'src/lib/camera/recording/**/*.ts',
+ 'src/lib/camera/session/**/*.ts',
+ 'src/lib/camera/srtp/**/*.ts',
+ 'src/lib/camera/MultiTierStreamManagement.ts',
+ 'src/lib/camera/WebRTCStreamManagement.ts',
+ 'src/lib/util/der.ts',
+ 'src/lib/util/ntp.ts',
+ 'src/lib/model/RecordingProvisioning.ts',
+ ],
+ rules: {
+ 'no-restricted-imports': [
+ 'error',
+ {
+ patterns: [
+ {
+ regex: '(?:^|/)util/tlv\\.js$',
+ importNames: ['readUInt64LE', 'readVariableUIntLE', 'writeVariableUIntLE'],
+ message: 'Read and write 64-bit integers as bigint through readBigUInt64LE and writeBigUInt64LE.',
+ },
+ {
+ regex: '(?:^|/)util/hapCrypto\\.js$',
+ importNames: ['writeUInt64LE'],
+ message: 'Write 64-bit integers as bigint through writeBigUInt64LE from tlv.js.',
+ },
+ {
+ regex: '(?:^|/)util/time\\.js$',
+ importNames: ['epochMillisFromMillisSince2001_01_01Buffer'],
+ message: 'Read 64-bit integers as bigint through readBigUInt64LE from tlv.js.',
+ },
+ {
+ regex: '(?:^|/)datastream/(?:index|DataStreamParser)\\.js$',
+ importNames: ['Int64'],
+ message: 'Carry 64-bit integers as bigint, which Int64 cannot hold exactly.',
+ },
+ ],
+ },
+ ],
+ },
+ })
+ .append({
+ // A constant set and the type derived from it share one name in the capability codecs, which this rule reads as a redeclaration.
+ files: ['src/lib/camera/capabilities/**/*.ts'],
+ rules: {
+ 'ts/no-redeclare': 'off',
+ },
+ })
+ .append({
+ files: ['package.json'],
+ rules: {
+ // npm reads `files` in order and a negated entry keeps a file out only when it comes after the entry it narrows, which is why negated entries come last.
+ 'jsonc/sort-array-values': [
+ 'error',
+ {
+ order: [
+ {
+ order: { type: 'asc' },
+ valuePattern: '^[^!]',
+ },
+ {
+ order: { type: 'asc' },
+ valuePattern: '^!',
+ },
+ ],
+ pathPattern: '^files$',
+ },
+ ],
+ },
+ })
diff --git a/guides/HKSV3Protocol.md b/guides/HKSV3Protocol.md
new file mode 100644
index 000000000..a7e636a21
--- /dev/null
+++ b/guides/HKSV3Protocol.md
@@ -0,0 +1,1036 @@
+# HomeKit Cameras in iOS 27: HKSV3 Recording and the New Live Views
+
+By [HJD](https://github.com/hjdhjd)
+
+## Part 1: The Story
+
+### What This Document Is, And Who It's For
+
+With iOS 27, Apple changed how HomeKit cameras stream and record. Apple also did something unusual and welcome: it published the _HomeKit Secure Video Open Source Compatibility Guide_, which describes the new camera services and the layout of every field in them.
+
+What the guide doesn't tell you is how the pieces behave once a real home hub is on the other end. Which request comes first? What does a hub do when it sees motion? What makes it keep a recording, and what makes it quietly walk away? Those answers decide whether a camera works or doesn't, and this document is my attempt to write them down.
+
+There are two parts:
+
+- **Part 1** is the story. If you want to understand what's going on between your camera, your home hub and iCloud, and you'd rather not read a field table to get there, this part is for you.
+- **Part 2** is the specification. It's written for people building a camera, a plugin or a library: every exchange, field, size and status code, each with a short note on how I know it.
+
+Everything here is implemented in [HAP-NodeJS](https://github.com/homebridge/HAP-NodeJS), the library behind [Homebridge](https://homebridge.io). This is not an Apple document, and nothing in it speaks for Apple.
+
+### What Changed With iOS 27
+
+Three things changed, and each one moves work from the home hub to the camera.
+
+- **Live video now comes in tiers.** A camera describes the streams it can offer, from a small one to a large one, in HEVC with Opus audio. Whoever is watching asks for the tier that suits its screen and its connection, instead of the camera guessing.
+- **Watching from away now uses WebRTC.** When you open a camera from outside your home, the camera makes its own connection out to a relay Apple runs, and your phone picks up the video there. The camera sends every tier at once and the viewer chooses among them...which is why a view from away can change quality without stopping.
+- **The camera uploads its own recordings.** This is the big one. The home hub still watches the video and decides what's worth keeping, but it no longer carries the recording to iCloud. The camera does that itself, encrypted, with credentials the hub hands it.
+
+Apple's guide doesn't give these features a name. Apple's own name for them is **HKSV3**, and it shows on the wire: the keys that protect a recording are addressed with the prefix `hksv3:`.
+
+There's more in the guide than those three things. A camera can describe more than one lens, for instance. In my testing the Home app shows such a camera as one camera with one live view, taken from whichever lens the camera listed first when it was paired. I'll leave the rest of that for Part 2.
+
+### The Big Picture
+
+Here's who talks to whom.
+
+```mermaid
+flowchart LR
+ subgraph Home["Your home network"]
+ Camera["Camera"]
+ Hub["Home hub
(Apple TV or HomePod)"]
+ Near["iPhone, iPad or Mac
at home"]
+ end
+ Relay["Apple's relay"]
+ Far["iPhone, iPad or Mac
away from home"]
+ Cloud["iCloud
(your recordings)"]
+
+ Hub -- "settings, credentials,
recording commands" --> Camera
+ Camera -- "video for analysis" --> Hub
+ Camera -- "live view (SRTP)" --> Near
+ Camera -- "live view (WebRTC),
every frame sealed" --> Relay
+ Relay --> Far
+ Camera -- "encrypted clips (HTTPS)" --> Cloud
+```
+
+The home hub is still the brain. It holds the long-lived connection to the camera, it writes the camera's settings, and it decides what gets recorded. What's new is how much the camera now does for itself: it sends live video straight to a viewer at home, it reaches out to Apple's relay for a viewer who's away, and it delivers its own recordings to iCloud.
+
+### How A Recording Gets From A Camera To iCloud
+
+It starts long before anything moves in front of the camera.
+
+**First, the hub gives the camera what it needs to upload.** Within seconds of you turning on recording, a home hub asks the camera to create a key pair and a certificate request. The hub answers with three things: a certificate that proves who the camera is, good for 60 days; a 32-byte secret called the Camera Key; and a web address in iCloud called the publishing point, which is where this camera's recordings go. When the certificate is close to running out, the camera raises its hand and the hub hands it a fresh set of all three.
+
+**Then, something moves.** The camera reports motion, and a hub connects within about 150 milliseconds and asks for video. The camera sends it in short pieces called fragments...four seconds each in my testing...beginning a few seconds _before_ the motion. That way the hub sees what led up to it. Think of it as a DVR that's always holding the last few seconds, just in case.
+
+**The hub watches, and gives a verdict on every fragment.** For each one it tells the camera either "should record" or "should not record". This is the hub doing what Apple's home hubs have always done for HomeKit Secure Video: deciding, by what you've asked it to record, whether there's a person, an animal, a vehicle or a package worth your attention. If every fragment comes back "should not record", that's the end of it, and nothing is kept.
+
+**When the hub sees something worth keeping, it tells the camera to start uploading.** The command names a moment in time, usually the start of the fragment just before the interesting one. From there the camera sends the recording to its publishing point as an ordinary HTTP Live Streaming clip: a playlist, then the video and audio in pieces, then a closing playlist. Every piece of video and audio is encrypted before it leaves, under a key derived from the Camera Key. iCloud stores it without being able to read it.
+
+**When the hub loses interest, it tells the camera to stop and finish the clip.** The camera sends the closing playlist, and a moment later the clip is in your Home app's timeline. If the action just keeps going, the hub cuts the recording into clips of five minutes each and carries on.
+
+Two things about this surprised me, and both are worth knowing.
+
+- **A recording only exists if the camera uploads it.** The hub watching the video is not enough. In every test where the upload failed, no clip ever appeared in the Home app, no matter what the hub had decided.
+- **Once a clip is uploaded, it doesn't need the camera anymore.** A recorded clip plays while the camera is switched off. It keeps playing after the hub has replaced the camera's key, too, because each clip says which key it was sealed under.
+
+### How A Live View Works
+
+A live view takes one of two paths, depending on where you are.
+
+**At home, your device talks straight to the camera.** It reads what the camera offers, tells the camera where to send the video and which keys to protect it with, and asks for a tier. The video and audio then flow directly between the two over encrypted RTP, with nothing in between. If the camera has a speaker, the Home app shows a talk button, and your voice travels back to the camera the same way.
+
+**Away from home, a hub sets things up and then gets out of the way.** The hub asks the camera for an offer. The camera answers with a description of everything it will send, one video stream for each tier plus audio, along with a key. The other end of that connection turns out to be a relay Apple runs, not the hub and not your phone. Once the connection is up, the camera sends all of its tiers at once, and every frame is sealed with that key before it's sent. Your phone picks a tier and can change its mind at any moment. Talking back works here as well: your voice arrives at the camera sealed the same way.
+
+In both cases the viewer will occasionally ask the camera for a keyframe, which is a complete picture it can start decoding from. It asks when a view begins, and again whenever it loses part of the picture. How quickly a camera answers that request is most of what makes a live view feel instant or sluggish, and Part 2 spends real time on it.
+
+### How I Figured This Out
+
+Apple's guide is the foundation for everything here, and I'm grateful for it. Where the guide states something, I take it as given and say so.
+
+Everything else comes from testing against real home hubs running iOS 27, in my own home. I built a test camera whose every behavior could be changed one piece at a time, and then changed one piece at a time...a lot of times. When a hub accepted something, I wrote down what it accepted. When it refused something, I wrote down exactly how, because a refusal often teaches more than a success does. One malformed offer for a view from away was turned down 185 times out of 185, which settles the question rather nicely.
+
+I leaned on three kinds of evidence: what the hubs wrote to the camera and when, what iCloud answered to each upload, and what the Home app actually showed at the end. That last one matters more than it sounds. A clip that uploads perfectly and then plays as a black picture is not a working clip.
+
+It also helped to recognize what Apple built on. Very little of this is exotic. The recordings are HTTP Live Streaming over CMAF, the same family of formats that carries most video on the internet. The encryption is AES-GCM with keys derived through HKDF. Views from away are WebRTC, with each frame sealed using SFrame, which is a published standard. Where a piece of the protocol follows a standard, Part 2 names it, because knowing what something is based on is usually the fastest way to get it right.
+
+A word on how sure I am. **Unless Part 2 says otherwise, every statement in it is something I observed.** Where I'm reading between the lines of what I observed, the statement is marked _inferred_. Where something that matters hasn't been tried, it's marked _untested_, and those are gathered at the end so nobody has to hunt for them.
+
+I'm sure there's more to learn here, and that someone will find a corner I missed. When you do, I'd love to hear about it.
+
+## Part 2: The Specification
+
+### 1. Conventions
+
+A few words and habits hold for everything below.
+
+**Who's who.**
+
+- The **camera** is the accessory. Everything in this document is written from its side of the wire.
+- A **hub** is a home hub: an Apple TV or a HomePod. A home can have several, and any of them may be the one talking to the camera at a given moment.
+- A **viewer** is the device showing a live view or playing a clip.
+- A view is **at home** when the viewing device holds its own connection to the camera, and **from away** when a hub sets the view up for it. Being on your home Wi-Fi is not quite the same thing as being at home: a device with no connection of its own to the camera views through a hub, exactly as it would from a cellular network.
+- The **relay** is the server of Apple's that sits at the far end of a view from away.
+- The **publishing point** is the iCloud address a camera uploads its recordings to.
+
+**Words for video.**
+
+- A **tier** is one encoding of a sensor's picture, at one size, frame rate and bitrate. A camera offers several.
+- A **keyframe** is a picture that decodes without any other picture.
+- A **recording** is the video a hub pulls from the camera to analyze. It arrives in **fragments**.
+- A **clip** is what the camera uploads, and what you later see in the Home app's timeline. It's uploaded in **segments**. A fragment and a segment can hold the very same bytes...the two words just say which path they're on.
+
+**How sure I am.** Unless a statement is marked, I observed it. _Inferred_ means I'm reading between the lines of something I observed. _Untested_ means nobody tried it, and it matters enough to say so. Three more words appear where a test settled a question: something is **required** when I watched things fail without it, **accepted** when the far end took it, and **not required** when things worked without it.
+
+When I describe the form of something...an offer, a playlist, a box in a file...that's the form I tested. I haven't tried every variation of every form that works, and I don't list the ones I skipped. The open points in section 12 are the questions whose answers would change what you build.
+
+Where two tests disagreed, I give you both, with what was different about them.
+
+**Numbers.** Timings are what I measured in my home, on my network, against my hubs. They're there to give you a feel for the pace of things, and none of them is a promise. Sizes are in bytes. A **64-bit NTP timestamp** is the number of seconds since 1900 in its upper 32 bits and the fraction of a second in its lower 32.
+
+**Names.** Services, characteristics and fields carry the names Apple's guide gives them. Requests on the data stream carry the names the HomeKit Accessory Protocol specification gives them, and I'll call that specification HAP from here on. I don't repeat the guide's field tables. Where a field's meaning isn't in the guide, appendix A has it.
+
+**Examples** use made-up addresses, keys and identifiers. The tier sizes and bitrates in them are the guide's own.
+
+**Notes that begin "In HAP-NodeJS"** describe a choice this library made. They're one way that works, and not a requirement of the protocol.
+
+### 2. What A Camera Publishes
+
+#### The Services
+
+A camera that wants the iOS 27 features publishes the services below. Apple's guide defines the first ten, and HAP defines the rest.
+
+| Service | What It's For |
+| --------------------------------------- | --------------------------------------------------------------------------------------------------------- |
+| Camera Capabilities | Announces an iOS 27 camera, and lists each video sensor with its tiers. Its Version reads `17.99`. |
+| Camera Global Operating Mode | The switches for the camera as a whole: HomeKit Camera Active, Streaming Enabled and the indicator light. |
+| Motion Sensor | Motion Detected, with the new Motion Enabled and Contributing Sensors beside it. |
+| Camera Motion Zones | The zones a user draws for motion. |
+| Camera Multi-Tier RTP Stream Management | A live view at home. One for each sensor. |
+| Camera WebRTC Stream Management | A live view from away. One for each sensor. |
+| Camera Recording Management | Two switches: Active and Recording Audio Active. |
+| Camera Buffer Management | The hub's verdicts and upload commands, and the publishing point. |
+| Camera Key Management | The Camera Key. |
+| Camera Client Certificate Management | The certificate request, the certificate and its status. |
+| Data Stream Transport Management | The HomeKit Data Stream that recordings and snapshots travel over. |
+| Microphone | The camera's sound. |
+| Speaker | Optional. Publishing one is what makes the Home app show a talk button. |
+| Doorbell | Optional. See section 10. |
+
+Two things about this list are easy to miss.
+
+- **No legacy stream is needed.** A camera can leave out HAP's older Camera RTP Stream Management entirely. I ran cameras with none, on a fresh pairing and as a new accessory behind an already paired bridge, and between them they got everything: provisioning, views at home and from away, talkback both ways, snapshots, recordings and notifications.
+- **Camera Recording Management is slimmer than HAP's.** It carries Active and Recording Audio Active and nothing else. A hub arms recording by writing Active alone. It never writes a recording configuration, which leaves the choice of recording format to the camera.
+
+#### Which Stream A Viewer Takes
+
+A viewer chooses its stream service from the accessory database. It reads the whole database, and then writes Setup Endpoints on the one stream service it has chosen.
+
+If a camera publishes HAP's legacy stream services beside the new ones, **the instance IDs decide**. A viewer takes the multi-tier stream only when the new stream services carry lower instance IDs than the legacy ones. This is required, and it holds on a fresh pairing and a standing one alike. The same camera, published twice on fresh pairings, was given four legacy views and no multi-tier view with its new services numbered above the legacy streams, and three multi-tier sessions and no legacy view with them numbered below.
+
+- The order the services are listed in doesn't matter. Only the numbers do.
+- The new services don't have to sit below the camera's other, older services. The Motion Sensor and the Microphone can keep their low numbers.
+- A camera numbered for the legacy streams is served the legacy stream from away too, by a hub, and is never asked for a WebRTC offer.
+- A viewer chooses again after a configuration number change, and a pairing survives the renumbering.
+
+This has a consequence for anyone upgrading a camera in place. Instance IDs are handed out once and only ever climb. A camera that was paired with legacy streams and later gains the new services holds them at higher numbers...and goes right on being shown through its legacy stream. Renumbering the legacy streams above the new services does move the view. One camera I did that to drew no recording at five motions later that day, though, and I can't say the renumbering wasn't why. I wouldn't renumber a paired camera.
+
+**In HAP-NodeJS** a camera is one form or the other, never both. A camera stated in the new form publishes no legacy stream service at all, and the question doesn't come up.
+
+#### Linked Services
+
+Each sensor's multi-tier stream service and WebRTC stream service must each be linked to the other, as HAP's linked services. This is required for a view from away. With the links in place a hub wrote WebRTC Solicit Offer for a viewer on cellular. Four minutes earlier, without them and with nothing else different, the same hub read the camera's tiers and stopped, and the viewer got no picture. Links to Data Stream Transport Management are not required.
+
+#### Tiers
+
+- **Three tiers are not required by the far end.** The guide asks for at least three concurrent encodings of each sensor. Cameras offering one tier, and two, were viewed at home, viewed from away and recorded just the same.
+- **A size the guide doesn't list is accepted.** A tier at a size outside the guide's table was shown at home, asked for through a hub, and recorded.
+- **HEVC is required.** A viewer at home accepts an H.264 tier, starts its stream, asks for a keyframe about four times a second and never shows a picture. None of the H.264 encodings I tried played, from two different encoders. From away, the viewer showed a spinner.
+- **The audio tier is Opus**, one channel, in 20 millisecond packets, reported at 48 kHz.
+- **A bitrate a little over the advertised peak plays.** A tier sent about 15 percent over its advertised peak played smoothly at home. A stream sent at about three times its advertised peak lost packets at home, though it played from away. The guide says its maximums should not be exceeded, and I'd take it at its word.
+- **Raise the configuration number when the tiers change.** Once it rises, every device fetches the database again within about six seconds. I never tested whether a device notices a change without it.
+
+#### More Than One Sensor
+
+The guide lets Camera Capabilities list several sensors, each with a type, an intent, and stream services of its own. Here's what the Home app does with a second one today: nothing.
+
+- A camera of two sensors is shown as one camera with one live view, and that view is the sensor whose stream services carry the lowest instance IDs. On a fresh pairing that's the sensor listed first.
+- A sensor's type and intent decide nothing. A Generic sensor listed first was shown ahead of a Primary one listed second. A second sensor with the Package intent was treated no differently, on a plain camera and on a video doorbell.
+- The second sensor's stream services are written to for one thing only: a hub's Streaming Enabled.
+- On a paired camera the view follows the instance IDs. Reordering Camera Capabilities, or raising the configuration number, moves nothing.
+- The camera is provisioned once, with one certificate, one Camera Key and one publishing point. Nothing in provisioning names a sensor.
+
+So list your main view first, and give it the lowest numbers. A camera that lists a package view ahead of its main view shows the package view alone.
+
+A clip may say which sensor it came from, with one line in its multivariant playlist (appendix A). Clips with the line and without it were accepted and looked the same in the Home app.
+
+#### Behind A Bridge
+
+A camera behind a bridge is provisioned, viewed, commanded and recorded as a camera published by itself is. The one visible difference is in provisioning: the certificate request such a camera answers with names its bridge as the subject, and a hub issues the certificate all the same.
+
+#### Things That Turned Out Not To Matter
+
+- A control point doesn't need a Status in its value before anything has been written to it. Cameras whose RTP Streaming Control and WebRTC control points read empty were viewed normally.
+- Manually Disabled on Camera Global Operating Mode is optional. Where a camera has it, a hub subscribes to it.
+- A camera doesn't need a new Firmware Revision for a hub to take up its new services. Hubs provisioned, commanded and recorded cameras whose revision never changed.
+
+### 3. The Settings A Hub Writes
+
+A hub writes a camera's settings far more often than you'd guess, and almost always with the values the camera already holds.
+
+#### When A Camera Is First Paired
+
+On the fresh pairing I read this on, a hub wrote one round of settings within two seconds of pairing, three times over:
+
+- Camera Operating Mode Indicator, on.
+- Streaming Enabled, true, on Camera Global Operating Mode, on the multi-tier stream service and on the WebRTC stream service.
+- HomeKit Camera Active, on.
+- Camera Recording Management's Active, off.
+
+Most fresh pairings also open with Camera Client Certificate and Camera Recording Publishing Point each written with an empty value, one to four seconds after pairing, and sometimes again about ten seconds in. An empty value means "you have none".
+
+#### When Recording Is Allowed
+
+When the user picks a recording option in the Home app, a hub writes Camera Recording Management's Active on. Provisioning, in section 6, comes with it.
+
+#### The Round A Hub Repeats
+
+A hub repeats a routine on the connection it holds open. It renews its subscriptions, and writes HomeKit Camera Active and every Streaming Enabled on.
+
+- On a camera whose recording is off, the round comes about every half minute, and it also writes Camera Recording Management's Active off and clears the certificate and the publishing point.
+- On a camera whose recording is on, the round comes every 35 to 50 seconds and clears nothing.
+
+The values don't change, which leaves the camera with no notification to send. The practical lesson: a write of the value you already hold should cost nothing and restart nothing.
+
+#### After A Restart
+
+At its first connection after a camera restarts, a hub writes the camera's settings again within about a second, each at the value it already reads: HomeKit Camera Active, Streaming Enabled, Motion Enabled and Camera Recording Management's Active. These are the values the camera reports, handed back to it.
+
+#### When A Camera Is Turned Off
+
+Turning a camera off in the Home app makes a hub write HomeKit Camera Active off and every Streaming Enabled off, and clear the certificate and the publishing point. The Home app then asks the camera for no stream at all.
+
+The guide adds a rule of its own here: a stream service's Status Active must read false whenever streaming is switched off on that service or on the camera, HomeKit Camera Active is off, or the camera is manually disabled, and a camera must reject a request to start a stream while it does.
+
+### 4. A Live View At Home
+
+At home the viewer and the camera talk to each other directly, over the Camera Multi-Tier RTP Stream Management service.
+
+#### The Exchange
+
+```mermaid
+sequenceDiagram
+ participant V as Viewer
+ participant C as Camera
+ V->>C: Read the accessory database
+ V->>C: Write Setup Endpoints
+ C-->>V: Where to send, and the SRTP keys
+ V->>C: Write RTP Streaming Control, Start
+ C->>V: Video and audio (SRTP)
+ V->>C: RTCP, keyframe requests, talkback
+ V->>C: Write RTP Streaming Control, End
+```
+
+- The viewer writes Setup Endpoints within 50 to 70 milliseconds of reading the database.
+- Start names a video tier and the audio tier by their identifiers, with an SSRC for each.
+- The media is SRTP under `AES_CM_128_HMAC_SHA1_80`, which the guide requires.
+- The guide requires at least five sessions at once, and says outright that several viewers can share one encoding. There's no one-to-one tie between an encoder and a session.
+- A full camera view takes the top tier with the audio tier. Right after pairing I also saw three short sessions, of a few seconds each, on the smallest tier. _Inferred_: the Home app's own setup opens them.
+- The viewer sends RTCP to both of the ports the camera answered with.
+
+#### The Packets
+
+What a viewer at home plays:
+
+- **HEVC** as RFC 7798 lays it out. A keyframe's video, sequence and picture parameter sets travel together in one aggregation packet. A NAL unit too large for a packet is sent as fragmentation units. A unit that fits is sent as a single NAL unit packet. The marker bit is set on the last packet of each frame.
+- **Opus**, one 20 millisecond frame to a packet, timestamps 960 apart on a 48 kHz clock.
+- The payload types are the ones the camera advertises.
+
+A viewer at home does not smooth out uneven delivery. Frames handed over three at a time, every 100 milliseconds or so, all arrived and all played, and the picture moved visibly less smoothly than the same frames sent one at a time. Send each frame when it's due.
+
+#### How A View Starts
+
+A viewer can show nothing until it has a keyframe, and it says so: it asks for one 50 to 80 milliseconds after its Start, and again every second until one arrives. On a stream whose keyframes come five seconds apart, that was four to six requests and a spinner for a couple of seconds.
+
+There are two ways to do better.
+
+- **Make a keyframe when asked.** With a keyframe produced on request, views on a five-second stream started within a second or two and played smoothly.
+- **Keep the recent video, and start the viewer from the latest keyframe you hold.** A view handed a keyframe as its very first picture usually asks for nothing at all, though now and then one asks in its first tenth of a second anyway.
+
+The second way has a catch, and it cost me a few days: **the timestamps have to be right.**
+
+- Pictures sent with the timestamps they were first given, which by then are a few seconds old, play jumpily...and the view stays jumpy for its whole length, long after the camera has caught up to live. _Inferred_: the viewer ends up playing behind what it receives.
+- The same pictures stamped with the live clock as each one is sent play properly.
+- A keyframe must carry a timestamp above every timestamp that viewer has already been sent. A keyframe stamped with the same timestamp as the last live picture was not taken, and the viewer went on asking. Stamped one millisecond later, 90 ticks of the video clock, it was taken every time.
+
+How fast you hand the buffered stretch over is yours to choose. At twice the stream's speed the viewer sees a fast-forward. At fifty times it sees nothing but a view that starts at once.
+
+**In HAP-NodeJS** every running tier keeps its video back to the latest keyframe. A view opens from that keyframe, stamped past everything already sent, at up to fifty times the stream's speed, and a plugin is never asked to make a keyframe.
+
+#### When A Packet Is Lost
+
+A viewer at home that loses a video packet freezes on its last good picture until it can decode a keyframe.
+
+- It usually asks for one within a tenth of a second of the loss. I measured 15 to 341 milliseconds across most views. Twice, on a stream far heavier than it advertised, a request came a full four seconds later.
+- It keeps asking, anywhere from a few times a second to once a second, until a keyframe arrives.
+- If nothing answers, the freeze lasts until the stream's next keyframe.
+
+A keyframe made on request ends the freeze as soon as the encoder delivers it. A keyframe from a buffer ends it immediately, at the price of the viewer seeing the stretch since that keyframe again, briefly.
+
+#### Talkback At Home
+
+A camera that publishes a Speaker gets a talk button in the Home app. A camera with a Microphone and no Speaker doesn't.
+
+- The viewer's voice arrives as RTP on the session's own audio port, the one the camera answered with in Setup Endpoints. No second session opens for it.
+- It's SRTP under the **viewer's** keys, the audio key and salt the viewer supplied in Setup Endpoints, and not under the camera's own.
+- It's the camera's own advertised audio tier coming back: Opus, one channel, 20 millisecond frames on a 48 kHz clock, on the camera's audio payload type, from the one SSRC the viewer named for its audio. A camera needs no second audio format for talkback.
+- **Mask the marker bit before you test the payload type.** The marker is set on the packet that opens each stretch of talk, not only the first packet of the session. A camera that compares the whole second byte of the RTP header drops exactly the packets that begin a sentence.
+- A viewer that isn't holding the talk button sends nothing.
+
+### 5. A Live View From Away
+
+From away, a hub arranges the view and then steps aside. The camera's connection goes to a relay of Apple's, over WebRTC, through the Camera WebRTC Stream Management service.
+
+Apple's guide defines the characteristics and their fields. It never mentions DTLS, an ICE role, RTCP, a single SDP attribute, the SFrame cipher suite or talkback. Everything in this section beyond the field layouts comes from testing.
+
+One piece of background first, and it's the one thing in this section that comes from my own analysis rather than from a test. _Inferred_: a view from away appears to reuse the machinery behind Apple's group calls. That would explain three things that otherwise look odd: the relay in the middle, the 16-bit stream IDs, and a viewer's voice arriving on two streams that no SDP announces. You don't need to know this to build a camera. It did help me stop being surprised.
+
+#### The Exchange
+
+```mermaid
+sequenceDiagram
+ participant H as Hub
+ participant C as Camera
+ participant R as Apple's relay
+ H->>C: Write WebRTC Solicit Offer (empty)
+ C-->>H: SDP offer, SFrame key and key ID
+ H->>C: Write WebRTC Provide Answer (the relay's SDP)
+ C->>R: ICE, then DTLS
+ C->>R: Every tier and the sound, each frame sealed
+ H->>C: Write WebRTC Update Session (a viewer's key)
+ R->>C: Keyframe requests, the viewer's voice
+ H->>C: Write WebRTC Reoffer (a viewer's audio section)
+ H->>C: Write WebRTC Update Session (keys removed)
+ H->>C: Write WebRTC Streaming Control, End
+```
+
+- A hub writes Solicit Offer only for a view through a hub. The value it writes is empty: no Options field, and so no request for SFrame. Every solicit I've seen was like this.
+- The far end of the connection is neither the hub nor the viewer's device. It's a relay of Apple's that speaks ICE-lite and offers one public address in Apple's 17.0.0.0/8 block, on a UDP port and on TCP port 80. The relay, its port and its DTLS fingerprint change from view to view.
+- The answer usually comes back within a quarter of a second of the solicit. Once it took most of a second.
+- The hub ends the session with Streaming Control. A session that's being watched lasts as long as the view does. I've watched for more than seven minutes.
+
+#### The Offer
+
+The camera is the offerer. Here's the form that plays, and for each part, what the far end did when I got it wrong.
+
+| Part | The Form That Plays | What Else I Tried |
+| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Sections | One bundle: a video section for each tier, largest first, then one audio section. | One video section stating every tier as a layer is answered and plays, but the viewer is given one stream and can never change tier. |
+| Session lines | `a=group:BUNDLE` naming every section, `a=setup:actpass`, `a=rtcp-mux`. | |
+| Each video section | `m=video 9 UDP/TLS/RTP/SAVPF `, send-only, `a=rtpmap: H265/90000`, the feedback lines `nack`, `nack pli` and `ccm fir`, and no format parameters. | H.265 format parameters were echoed back in the answer and changed nothing. |
+| Its SSRC | Exactly one `a=ssrc` line, naming an SSRC that belongs to that section alone. | A video section that names no SSRC was ended unanswered, 185 times out of 185. |
+| Its tier | `a=rid: send max-width=;max-height=;max-fps=;max-br=`, with `a=simulcast:send `. | A rid line with no restrictions is answered, and the hub then ends the session within eight seconds. A single-stream video section, with no rid line and no header extensions, is ended unanswered within a second. _Inferred_: it's the missing rid line. |
+| Header extensions | Every section lists `sdes:mid` and `sdes:rtp-stream-id`. | |
+| The audio section | `m=audio 9 UDP/TLS/RTP/SAVPF `, send-only, one `a=ssrc` line, `a=rtpmap: opus/48000`, and `a=fmtp: minptime=20;useinbandfec=0`. | `opus/48000/2` with no format parameters was answered and then ended inside about a second, 59 times out of 59. AAC in place of Opus was ended unanswered, 142 times out of 142. AAC listed after Opus was answered with Opus alone. |
+| Candidates | Host candidates, written in the SDP. The Additional Candidates list is empty. | |
+
+A few things the table can't hold:
+
+- **The payload types and the tiers are the ones the camera advertises** in WebRTC Supported Video Stream Tiers and WebRTC Supported Audio Stream Tiers. My camera used 99 and 110. Those aren't fixed numbers.
+- **The rid restrictions follow RFC 8851**, and `max-br` matters more than it looks. It's the bitrate a viewer budgets against when it picks a tier.
+- **A camera can offer fewer tiers.** Offers of one video section and of two were answered, section for section, and played.
+- **Every candidate goes in the offer.** The protocol has no way to send one later. Finish gathering before you answer the solicit. I never needed a STUN or TURN server: the camera reaches out to a public address.
+- **Make the SSRCs of one offer differ in their low sixteen bits.** _Inferred_: a viewer knows each stream by a 16-bit stream ID, which is the low sixteen bits of its SSRC. I've never let two collide.
+- **Answer quickly.** Gather your candidates before a solicit arrives, and the offer can go back in a millisecond or two.
+
+#### The Key That Goes Back With The Offer
+
+The response to Solicit Offer carries an SFrame Configuration: a key of 32 random bytes and a 64-bit key ID, both fresh for every session. Everything the camera sends is sealed under that key.
+
+- **Return a key with every offer, whatever the solicit says.** No solicit has ever asked for SFrame, and no video sent without it was ever shown, in any form I tried. The response is the viewer's only way to learn the camera's key.
+- A hub keeps a session whose response carries no key. The viewer just never shows a picture.
+- My key IDs carry `0x8000` in their low sixteen bits, as the hub's own do. Nothing I found requires it.
+
+#### The Answer, And Connecting
+
+The answer arrives as a Provide Answer write. It keeps every section in one bundle, adds a lip-sync group and `a=rtcp-rsize`, returns each video section receive-only with `a=rid: recv` and `a=simulcast:recv `, keeps the `sdes:rtp-stream-id` extension, drops `sdes:mid`, and carries two candidates for the relay, one UDP and one TCP.
+
+- **The camera is the ICE controlling agent and the DTLS server.** The relay sets `a=setup:active`.
+- **Be listening for DTLS before ICE finishes.** The relay's ClientHello arrives within a millisecond of ICE connecting. A camera that isn't ready yet loses it and waits a full second for the retry. Hold on to that first record and hand it to your DTLS server the moment you have one.
+- The transport is DTLS 1.2 with `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`, and the SRTP profile is `AEAD_AES_128_GCM`.
+- **A viewing remembers its first offer.** The far end forms its answer from the first offer a viewing makes, and gives that same answer to every later session of the viewing...even when a later offer is different. A viewing that opened on a bad offer stays broken for good offers too. A gap of 95 seconds without a solicit began a new viewing, and a gap of 24 seconds did not. If you're experimenting with offers, wait a couple of minutes between tries, or you'll be testing your first one again.
+
+#### The Keys A Hub Writes
+
+After the answer, a hub writes WebRTC Update Session with the keys the camera needs to open what a viewer sends: 32-byte keys under 64-bit key IDs, each with `0x8000` in its low sixteen bits.
+
+- Each viewer has a key ID of its own. A viewer's packets name their key by that ID.
+- The first key usually arrives 0.2 to 0.5 seconds after the answer. It has also arrived 10, 17 and 40 seconds into a session.
+- A viewer's first packets can reach the camera before the key they name has been written. That's not a fault. Drop them, or hold them within a small bound, and open what follows.
+- The camera's own key is never among the keys a hub writes.
+- A hub removes a session's keys shortly before it ends the session, typically a fifth of a second before. Once the gap was two seconds, and once it was forty. **A session is over when the hub ends it, and never when its keys are removed.**
+- Hold every key by its ID, wipe it when the hub removes it and when the session ends, and keep its bytes out of your logs.
+
+#### Sending The Picture
+
+- **Send every tier you offered, all the time.** Each tier goes out on the SSRC its section names. The viewer chooses among them, and the camera is never told which one is on screen.
+- **One frame is one SFrame ciphertext.** The plaintext is the frame's NAL units, each preceded by its length as four bytes, big-endian, with the parameter sets ahead of a keyframe's picture. Video uses the cipher suite with the ten-byte tag. Video sealed with the four-byte tag showed nothing.
+- **The ciphertext is cut across RTP packets**, and each piece gets one byte in front of it: `0x80` on the first packet of a frame, `0x00` in the middle, `0x40` on the last, and `0xC0` when one packet holds the whole thing. The marker bit goes on the last packet. Every packet of a frame carries the frame's timestamp, on the codec's 90 kHz clock.
+- **No packet carries a stream ID.** The offer lists the `sdes:rtp-stream-id` extension, and the camera must not actually put it on a packet. With it there, a viewer refused every video packet and the session died at about a minute. Without it, nothing was refused.
+- **Every tier shares one RTP clock.** One moment in time carries one timestamp on every tier. When I stamped each tier from its own source's start, a viewer played the first tier it took and threw away every frame of the next one as too old. With the tiers on one clock it moved among them freely.
+- **Never reuse a counter.** Each stream counts its ciphertexts from zero and keeps counting for the life of the session's key, through a source that restarts, a keyframe request and a Reoffer. A counter used twice under one key breaks the encryption.
+- Each stream sends RTCP sender reports for the clock its packets carry.
+
+#### Sending The Sound
+
+The camera's sound is Opus, one channel, 20 milliseconds to a packet, 960 ticks apart on a 48 kHz clock. Each packet's payload is one whole SFrame ciphertext with `0xC0` in front of it, sealed with the four-byte tag. The sound plays beside the picture and goes on playing if the picture freezes. A viewer that isn't taking the video plays no sound either.
+
+#### How SFrame Is Built
+
+The construction is RFC 9605's, with three differences. One construction serves every stream in both directions.
+
+- **Each stream has its own secret**, derived from the session key and the stream's SSRC. It stands where the RFC has its base key.
+- **The two cipher suites are outside the RFC's registry.** Both are AES-256 in counter mode with an HMAC-SHA-512 tag, a 32-byte encryption key and a 64-byte authentication key. Suite 6 has a ten-byte tag and is for video. Suite 8 has a four-byte tag and is for audio. The suite's number is part of the key derivation, which means changing suites changes the keys.
+- **The byte in front of each RTP payload** is the SFrame RTP header of `draft-ietf-avtcore-rtp-sframe-01`: its first bit marks the first packet of a ciphertext, and its second bit the last.
+
+Here it is exactly. `BE32`, `BE64` and `BE16` write a number big-endian in that many bits, and `||` joins bytes. Every derivation is HKDF in full, extract and then expand. The two `Secret` labels end in a space, and the stream label doesn't.
+
+```text
+stream secret = HKDF-SHA-512(key: session key, salt: BE32(SSRC), info: "SFrame 1.0 RTP Stream", 64 bytes)
+D = HKDF-SHA-512(key: stream secret, salt: empty, info: "SFrame 1.0 Secret key " || BE64(key ID) || BE16(suite), 96 bytes)
+Kenc, Kmac = D[0..32], D[32..96]
+S = HKDF-SHA-512(key: stream secret, salt: empty, info: "SFrame 1.0 Secret salt " || BE64(key ID) || BE16(suite), 12 bytes)
+N = S XOR (00 00 00 00 || BE64(counter))
+C = AES-256-CTR(Kenc, counter block: N || 00 00 00 00, plaintext)
+tag = HMAC-SHA-512(Kmac, BE64(len(H)) || BE64(len(C)) || BE64(tag length) || N || H || C), cut to the tag length
+ciphertext = H || C || tag
+```
+
+`H` is the SFrame header, exactly as RFC 9605 defines it. The far end writes an eight-byte key ID, and carries its counter inside the first byte for as long as it fits. No SFrame metadata is sent. The tag covers the lengths, the nonce, the header and the encrypted frame, in the order of RFC 9605 section 4.5.1. It doesn't cover the RTP header or the byte in front of the payload.
+
+The **session key** is the camera's own key for what it sends, and a viewer's key from Update Session for what that viewer sends. The **SSRC** is the one the stream was set up with: the SSRC the offer names for a section the camera sends, and the SSRC a viewer's voice arrives on.
+
+An implementation of this passes RFC 9605's own test vectors for the RFC's suites, opened everything the far end sent, and sealed everything a viewer played.
+
+#### How A Viewer Picks A Tier
+
+The viewer chooses, by its own estimate of its connection. The camera sends everything and is told almost nothing.
+
+- **A viewer budgets by the bitrate you state**, not by what arrives. It takes a tier when that tier's `max-br` plus the sound's 35,200 bits a second fits its budget.
+- The budget moves in fixed steps. A tier stating 1,700,000 was passed over at a budget of 1,681,000 and taken at the next step, 1,949,000. A tier stating 768,000 was passed over at 802,000 and taken at 930,000.
+- **A view climbs.** It starts on the smallest tier and reaches the largest about six seconds in. It steps down when its connection sags, and back up when it recovers.
+- **Low Data Mode caps the budget at 1,078,000.** Beyond its smallest tier, such a viewer takes nothing that states more than about a megabit, however good its connection really is.
+- Viewers on cellular took a tier stating 1,700,000 and, on another camera, never asked for a larger one. A viewer on the home network, viewing through a hub, did ask for that larger tier.
+- _Inferred_: where the Home app plays a view smaller than full size, it holds that view to the smaller tiers, and the full camera view may take any. An iPhone's tile isn't such a view. Watched from away, it asked the camera for nothing until it was tapped.
+
+So state each tier's bitrate honestly. Understating one to coax a viewer onto it just hands that viewer a stream its connection can't carry.
+
+#### Keyframe Requests
+
+A keyframe request from away is an RTCP Full Intra Request. The stream it wants is named by the SSRC in its one entry. Its media source field reads zero, and the SSRC it's sent from routes nothing.
+
+- **A request names a tier to refresh. It doesn't tell you what's on screen.** A viewer asks a tier for a keyframe before it switches to it, and that request is the only sign of a move a camera ever gets. Answer a request for any tier you send.
+- A viewer asks each tier in turn as a view opens: the smallest within about a second of its key arriving, the middle one a second or two in, and the largest five to six seconds in.
+- After a lost packet a viewer asks 0.3 to 1.2 seconds later, slower than at home. It asks again, a few times a second, until that tier's next keyframe.
+- Requests come in bursts, and a request can be lost on the way. A viewer that asked once, and whose request never reached the camera, did not ask again for four seconds.
+- No request to resend a lost packet has ever reached the camera. A lost packet costs the viewer its whole frame, since a frame is one ciphertext.
+
+Everything in section 4 about timestamps holds here too. A keyframe answered from a buffer must be stamped past everything already sent.
+
+#### A Second Viewer, And The Reoffer
+
+After the first seconds of a view a hub writes WebRTC Reoffer. The controller is the offerer this time, and the camera answers inside the write's response.
+
+- Every Reoffer I've seen left the camera's sections alone and added or switched an audio section belonging to a viewer: send-only at first, later inactive, and sometimes back again.
+- A Reoffer changes neither the camera's key nor how it seals.
+- **Two devices watching the same camera share one session.** The second joins the first's session through a Reoffer that adds an audio section of its own, and the hub writes a second key ID for it. There's no second solicit.
+- A device that closes the camera and opens it again comes back as a new viewer, under a new key ID.
+- In every view I watched, a Reoffer arrived when a picture was showing and none arrived when it wasn't. It's the best sign of success the camera has.
+
+Answer every Reoffer, whenever it comes, and apply what it negotiates.
+
+#### Talkback From Away
+
+A viewer's voice simply starts arriving. No SDP names it.
+
+- It comes as **two Opus streams**, each on an SSRC of its own, both counting time on one 48 kHz clock. Payload type 119 is the dependable one: wideband, one 20 millisecond frame to a packet, about 24 kbit/s. Payload type 97 is the better one: super-wideband, two 20 millisecond frames to a packet, about 48 kbit/s. They're the same voice, encoded twice.
+- Each packet is one SFrame ciphertext with `0xC0` in front, sealed with the four-byte tag under that viewer's key from Update Session.
+- **Find the voice by its payload type and by whether it opens**, never by looking for its SSRC in an SDP. Neither SSRC is named anywhere, and a Reoffer can assign payload type 97 to retransmission on some other section.
+- **Viewers send voice packets with nobody talking.** An iPhone and an iPad send about a third of a second of both streams as a view opens: 15 or 16 packets on 119 and 8 on 97. A Mac sent them on 119 for half a minute, and in one session on both streams for a full minute. A stream's first packet is not the start of its talk.
+- **Read talk from the Opus voice flag**, not from packet sizes. A silent packet on 119 can be as large as a spoken one. The flag drops out for a packet or three in the middle of speech. Don't end a sentence on one unvoiced packet.
+- A viewer keeps sending through a pause in talk, and stops sending when talk is switched off. The first packet after a stop carries the marker bit, and its timestamp has moved ahead by the time that wasn't sent.
+- For a second or more after talk is switched on, packets say voice and hold no speech.
+- The better stream trails the dependable one by about 25 milliseconds. A second device joining a view sent its talk on the dependable stream alone.
+- Voice packets arrive in clumps, and a few in a hundred arrive more than a tenth of a second late. A camera that plays them needs a little buffering.
+
+You may also see RTCP feedback of format 9. It's RFC 7728's PAUSED indication for the viewer's own voice stream, and it asks nothing of the camera. I only saw it on offers that had no audio section.
+
+**In HAP-NodeJS** a plugin is handed each viewer's voice as one continuous Opus stream. The library starts on whichever stream speaks first, moves to the better one when it carries the talk, and falls back when it stops. A plugin that would rather have the dependable stream alone can say so.
+
+#### Reading The Signs
+
+A camera is never told whether a picture is on screen. These are the signs that went with each outcome in my testing. None of them is a viewer's own word for what it shows.
+
+| What The Camera Sees | What It Meant |
+| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
+| A Reoffer in the first few seconds, and few keyframe requests | A picture is showing. |
+| A handful of keyframe requests naming another tier | The viewer wants that tier refreshed, most often because it's about to move to it. |
+| A keyframe request every five seconds | Nothing is showing. Nothing arrives, or what arrives can't be opened. |
+| Two to four keyframe requests a second | Frames arrive and can't be shown whole. Packets are being lost, or the codec isn't one the viewer plays. |
+| No Reoffer and no keyframe request | The viewer isn't taking the video at all. |
+| The session's keys removed | The end is coming, usually in a fifth of a second. |
+
+#### How A Session Ends
+
+- A hub ends a session that shows no picture after about a minute.
+- A stream that stopped for 5, 15 and 25 seconds came back each time, and the picture with it. About 36 seconds after a stream stopped, the hub removed the session's keys, and a stream that came back after that was not shown.
+- A view with three packets in a hundred lost stayed open, and choppy. Views whose loss climbed to ten and then thirty in a hundred were ended about half a minute after it first rose.
+- While a view stays open, the hub solicits again after a session ends, usually within a second.
+
+#### When A Camera Refuses
+
+A camera that can't serve a view answers Solicit Offer with a Status of Error. What the hub does next varied more than anything else I measured. After one refusal a hub wrote no second solicit for 70 seconds. In other views it asked again about once a second. In one it asked 9,885 times in under nine minutes, a median of 35 milliseconds apart. Plan for the fast one: a refusal has to be cheap, and has to release everything it took. The viewer sees a still picture, or the camera crossed out.
+
+### 6. Recording: Provisioning
+
+Before a camera can upload anything, a hub hands it three things: a client certificate, the Camera Key and the publishing point.
+
+#### The Exchange
+
+```mermaid
+sequenceDiagram
+ participant H as Hub
+ participant C as Camera
+ H->>C: Write Camera Client CSR (a 32-byte nonce)
+ C-->>H: Certificate request, and the nonce's signature
+ H->>C: Write Camera Client Certificate
+ H->>C: Write Camera Key
+ H->>C: Write Camera Recording Publishing Point
+ H->>C: Write Camera Recording Management, Active on
+```
+
+The four provisioning writes land inside two seconds, one write each. Active follows six or seven seconds later.
+
+- **The certificate request** is on an EC P-256 key, signed with ECDSA and SHA-256. A subject of one common name is enough, and what it says isn't checked.
+- **The nonce's signature** is the raw `r` and `s` values, 64 bytes, and not a DER-encoded signature. The request and the signature go back in the response to the write.
+- **The certificate** arrives with its issuing authority, and is valid for 60 days.
+- **The Camera Key** is 32 bytes, with a key number beside it. The guide types the number as 64 bits. Every one I've been handed fits in 48, and they follow no order. Don't treat the number as a counter.
+- **The publishing point** is an HTTPS address that ends in a slash, with a list of server authority certificates.
+
+#### When It Happens
+
+- A camera paired with recording already allowed is provisioned within seconds of pairing.
+- A camera whose user allows recording later is provisioned when they do. One camera paired with recording not allowed was left unprovisioned until recording was allowed.
+- One observation may differ. A camera in the new form alone was provisioned about 35 seconds after pairing, and its recording switch was written on seven seconds after that. Seven seconds is the usual gap between provisioning and the switch. That may simply have been the moment recording was allowed...or a hub may provision such a camera before anyone allows anything. I can't tell the two apart from what I recorded.
+- Either way, the provisioning arrives ahead of the switch. A camera sees its four writes first, and Active six or seven seconds later.
+- A camera that was already recording the older way, and gains the new services on its standing pairing, is provisioned by itself within three seconds of advertising again. Nobody has to touch the Home app.
+
+#### Renewal
+
+**Camera Client Certificate Status is how a camera asks for new credentials.** When its Needs Update reads true, a hub provisions the camera again, and it does so whole: a new certificate, a new Camera Key and a new publishing point, in the same four writes.
+
+- A hub acts on Needs Update when it finds it set as it connects, and when it's notified of it on a connection it already holds.
+- An empty value doesn't bring one. A camera that answered an empty certificate, an empty key ID or an empty publishing point, with its status reading clear, was left exactly as it was for the minutes I watched. A camera that has lost any of the three gets them back by raising Needs Update.
+- The new publishing point is on the same host as the old one, with a different path.
+- Removing the pairing clears the key ID, the certificate and the publishing point.
+
+**In HAP-NodeJS** a camera raises Needs Update a week before its certificate runs out, and whenever it holds less than the full set.
+
+#### A New Key, Unasked
+
+A hub also replaces a camera's Camera Key by itself, outside any renewal. It writes Camera Key alone, with a new key and a new key number, and leaves the certificate and the publishing point as they are. I've seen it twice on one camera: about 25 hours after the camera was provisioned, and again about 37 hours after that. It keeps no fixed schedule.
+
+Use the newest key for the next clip. **Clips sealed under a replaced key go on playing**, after one replacement and after two, because each clip names the key it was sealed under.
+
+#### When The Service Says No
+
+Once, a camera that had kept its credentials through a short spell in the legacy form had its next upload refused with status 401. A hub provisioned it again within three seconds, in the middle of the event, and the following clip was accepted. The start of that event, its first two fragments, reached no clip. I don't know how the hub learned of the refusal, and I don't know whether the refusal came from the spell or from the credentials' age. Both are in section 12.
+
+### 7. Recording: What A Hub Does At Motion
+
+```mermaid
+sequenceDiagram
+ participant C as Camera
+ participant H as Hub
+ participant P as Publishing point
+ C->>H: Motion Detected
+ H->>C: Open a data stream, ask for a recording
+ C->>H: Initialization segment, then fragments
+ H->>C: Buffer Activity Command, once for each fragment
+ H->>C: Buffer Upload Command, Start
+ C->>P: Playlists, initialization segment, segments
+ H->>C: Close the recording
+ H->>C: Buffer Upload Command, Stop
+ C->>P: Closing playlist
+```
+
+#### The Request
+
+A hub connects within about 150 milliseconds of Motion Detected rising. It reads Camera Recording Management's Active, subscribes to Motion Detected, Contributing Sensors, Active and Manually Disabled, writes Setup Data Stream Transport, and opens a HomeKit Data Stream. Over that stream it sends the request HAP already defines for recordings: `dataSend.open` with the type `ipcamera.recording`, the target `controller` and the reason `record`. From motion to that request is usually 50 to 250 milliseconds.
+
+- **Motion only brings the hub. It doesn't decide anything.** With Motion Detected raised and nothing moving in the picture, a hub pulled five fragments, judged every one not worth recording, and kept nothing. The verdict turned at the very fragment in which a person walked into view.
+- A hub asks even when the Motion Sensor's Status Active reads false.
+- A camera with no Data Stream Transport Management is connected to at motion, subscribed to, and left alone about five seconds later.
+
+#### The Recording A Hub Pulls
+
+The recording is fragmented MP4, sent as HAP's data stream recordings always have been: an initialization segment, then fragments, in chunks, until the hub closes the stream itself with the reason NORMAL.
+
+- The initialization segment is an `ftyp` box and a `moov` box.
+- Each fragment is a `prft` box, a `moof` box and an `mdat` box.
+- A fragment opens on a keyframe. Four-second fragments are what HAP asks for, and five-second fragments from a camera whose keyframes come five seconds apart were taken as well.
+- The recording starts before the motion does. The first fragment is the camera's prebuffer, and the first two fragments usually leave together.
+- H.264 under the `avc1` sample entry and HEVC under `hvc1` are both judged, with AAC-LC or Opus sound.
+
+**The `prft` box is required**, and it's the single most important thing in this section that isn't written down anywhere. It's the producer reference time box of the ISO base media file format, and it tells the hub what time on the clock a fragment began. With it in front of every fragment, a hub analyzes each fragment and tells the camera what it thinks. Without it, a hub pulls the same recording to the same normal close, says nothing, and nothing is kept. Appendix A has its layout.
+
+A hub takes the clock time of the **first** fragment from its box, and counts forward from there by each fragment's duration. It doesn't use the times in the later boxes.
+
+One recording was refused outright. Its samples had been nudged by a tick to keep their decode times apart, which left some composition offsets below zero, and more than one hub closed it at once with the reason UNEXPECTED_FAILURE. The same picture and sound, cut cleanly by duration, was taken. I didn't work out which detail the hubs objected to. Give every sample its true time.
+
+#### The Verdicts
+
+For every fragment it analyzes, a hub writes Buffer Activity Command:
+
+- **Start**, a 64-bit NTP timestamp. The first one equals the first fragment's `prft` time to the millisecond, and each later one adds the previous fragment's duration exactly.
+- **Duration**, the fragment's own, in milliseconds.
+- **Activity**: 1 for Should Record, 2 for Should Not Record.
+
+A verdict follows its fragment by 0.26 to 0.92 seconds, most often about 0.3, and always arrives before the next fragment is sent.
+
+#### The Upload Commands
+
+At the first fragment it judges Should Record, a hub writes **Buffer Upload Command** with Command 1, Start: a Session ID, and a Start timestamp.
+
+- The Start timestamp names the beginning of the fragment **before** the one that earned the verdict, which is how the clip comes to include the lead-up. When the very first fragment of a recording is the one judged Should Record, it names that fragment.
+- Start and Stop are the same 64-bit NTP timestamps the verdicts carry. The guide doesn't state their unit.
+- The camera answers with a Clip ID. Nothing I tried depends on its value. The hub's own Session ID, handed back, works fine.
+- The Start arrives 5 to 11 milliseconds after its verdict, typically two to four seconds after the motion.
+
+When the hub is done it writes Command 3, Stop, for the same Session ID, with a Stop timestamp and the Stop Action Finalize. The Stop timestamp names the end of the last fragment judged Should Record.
+
+So a clip is always a run of whole fragments of the recording the hub just pulled, and a camera finds them by counting fragment durations from its first fragment's `prft` time.
+
+- **Keep your fragments until the commands settle.** A hub closes the recording a few milliseconds _before_ it writes its last verdict, and the Stop comes 5 to 38 milliseconds after the close. A verdict, and any Start it draws, can arrive after the recording it's about has ended.
+- **One recording can hold several clips.** Verdicts of record, record, record, don't, record, record, record drew a Stop when the fourth fragment was judged, and a new Start under a new Session ID when the fifth was.
+- **A long recording is cut into clips of 300 seconds.** At exactly 300 seconds a hub writes Stop for the running clip, and 12 milliseconds later a Start under a new Session ID whose timestamp is that same instant.
+- A recording judged Should Not Record from end to end draws no upload command at all.
+- If the camera ends the recording stream itself, the hub writes its upload command at once and the clip can still be finalized.
+- After Stop, a hub asks nothing more about the clip.
+
+I've never seen a hub write the StartAndStop command or the Pause stop action, and no hub has ever read the event queue: none subscribed to Buffer Event Sequence Number or wrote Buffer Event Command.
+
+**A recording a hub pulled, judged and commanded leaves no clip unless the camera uploads one.** The pulled recording is the hub's analysis feed, and it supplies the picture you see in a notification and beside an event in the timeline. The clip itself is the upload.
+
+#### Declining A Recording
+
+A camera that won't serve a recording should say so in its answer to the `dataSend.open`, with one of HAP's protocol errors.
+
+- **Not Allowed**: every hub in the home asks once for that motion, one after another, and none asks twice.
+- **Busy**: one hub asks once, and no other hub asks.
+- Either way no stream is left open, and the hubs ask again at the next motion. Four refusals in a row changed nothing about the fifth.
+- Don't answer the open with success and then send an empty end of stream. A hub neither acknowledges that nor closes it, and the stream hangs until the camera gives up on it.
+
+The Home app showed nothing in its timeline for a declined motion. I checked that on the form I've just told you not to use, and not on the two refusals.
+
+### 8. Recording: The Clip Upload
+
+A clip goes to the publishing point as HTTP Live Streaming over CMAF: playlists and media, each object its own request.
+
+#### The Connection
+
+- **HTTP/2 only.** A request over HTTP/1.1 is answered 426.
+- **Mutual TLS**, with the client certificate the hub issued and the key the camera made for its certificate request.
+- The ordinary public root certificates verify the service. The server authority list the hub hands over completes a handshake too.
+- **The method is `PUT`.** The same object sent by `POST` is answered 404 and never reaches the service.
+- **The `User-Agent` must read `HKSV/3.0 (; ; )`**, as in `HKSV/3.0 ExampleCam/1.2.0 (Example; Model One; 4.5.6)`. A plain one is answered 400. The service doesn't hold those fields to the camera it provisioned: a made-up vendor and a vendor of `Unknown` were both accepted.
+
+#### The Objects
+
+Every clip lives in a folder of its own beneath the publishing point, `session_/`. Here's a whole clip, in the order it's sent.
+
+| Order | Path Under `session_/` | What It Is | Content Type |
+| ----- | ------------------------------ | ---------------------------------------------------------------------------- | ------------------------------- |
+| 1 | `index.m3u8` | The multivariant playlist. | `application/vnd.apple.mpegurl` |
+| 2 | `high/index.m3u8` | The media playlist, listing no segments yet. | `application/vnd.apple.mpegurl` |
+| 3 | `high/high.init` | The initialization segment. | `video/mp4` |
+| 4 | `high/segment_1001.m4s` and on | The media segments, in order. | `video/iso.segment` |
+| 5 | `high/index.m3u8` | The media playlist again, listing every segment and ending `#EXT-X-ENDLIST`. | `application/vnd.apple.mpegurl` |
+
+Each of these is answered 201.
+
+- **The picture and the sound can share one track file**, as above, or go as a video track and an audio track with a playlist each. Both play.
+- The names aren't fixed. Tracks called `video` and `audio`, and segments numbered from 1, were accepted. So were segments without the `x-extinf-duration` header my uploads carry, and playlists without `#EXT-X-PLAYLIST-TYPE:EVENT`.
+- A segment may be the very bytes the camera served the hub: a `prft`, a `moof` and an `mdat`. Segments that open with `styp` and `sidx` boxes are accepted as well.
+- **A camera can upload while the hub is still pulling.** Send the playlists and the initialization segment at the Start, each segment as it's produced, and the closing playlist after the Stop. There's no need to hold a clip until it's whole.
+
+The playlists are in appendix A.
+
+#### Encryption
+
+Every media segment is sealed, whole, before it's sent. The initialization segment is not.
+
+- **A sealed segment** is a 16-byte IV, then the AES-256-GCM ciphertext of the entire segment, then the 16-byte tag. There's no additional authenticated data. Each segment gets a fresh random IV.
+- **The key is not the Camera Key itself.** It's a content key derived from it: HKDF-SHA-256 with the Camera Key as the input, an empty salt, the info `HomeKit 1.0 CMAF Content`, and 32 bytes out.
+- **The playlists say which key.** Each media playlist carries `#EXT-X-KEY:METHOD=AES-256-GCM,URI="hksv3:.key"` straight after its `#EXT-X-MAP` line, in the opening playlist and the closing one. The multivariant playlist carries the same attributes on an `#EXT-X-SESSION-KEY` line.
+- **The identifier** is the Camera Key's key number shifted left 16 bits, with `0x4000` set in the low bits, written in hexadecimal with no prefix.
+- No key is ever uploaded. The Home app supplies the key itself, by the identifier the playlist names.
+
+This is the part of the protocol that took longest to find, because the service is no help: it answers 201 to media it can't possibly parse. A clip sealed under the wrong key, or naming its key with the wrong address, uploads perfectly and then refuses to play. Three things told me this form is right. The Home app's own player asks for a key at exactly the address a playlist names. A clip built this way plays, picture and sound, where every other form I tried showed a struck-through play button, a black picture or nothing at all. And it plays in every shape I've sent since: one track file or two, H.264 or HEVC, AAC or Opus, commanded by a hub or not, and from more than one camera's key.
+
+The service also accepts a clip with no encryption at all, and the Home app plays it. Please don't. HomeKit Secure Video promises recordings only your own devices can read, and the hub hands you a key for a reason. **In HAP-NodeJS** there is no unencrypted upload: a camera without a usable key declines the hub's Start and uploads nothing.
+
+#### What The Service Answers
+
+| Status | What It Means |
+| ------ | ---------------------------------------------------------------------------------------------------------------------- |
+| 201 | Taken. |
+| 208 | The folder already holds this object. Harmless while the folder is open. |
+| 400 | Refused: a plain `User-Agent`, an empty playlist, or media sent into a folder that's already closed. |
+| 401 | The credentials were refused. A `GET` is answered this way too. |
+| 404 | The request never reached the service: the wrong method, or the publishing point's own address with no session folder. |
+| 413 | The segment is too large. |
+| 426 | The request came over HTTP/1.1. |
+| 503 | A fault on the service's side. Try the object again. |
+
+#### Folders
+
+- **A folder's number belongs to the camera, and it must keep climbing**, through a renewal and a new publishing point too. A camera that started again at `session_1/` with fresh credentials had its clip refused: 208 for the multivariant playlist it had sent days before, and 400 for the first media playlist.
+- **The closing playlist closes the folder.** After it, the folder takes no more media.
+- While a folder is open, an object sent twice is answered 201 and then 208. The opening media playlist is the exception: it's replaced, and answered 201 both times.
+- **A folder can be picked up again.** After a 503 on one object, the rest of the clip was accepted in the same folder half an hour later.
+- **An object cut off mid-flight leaves nothing behind.** A segment whose connection dropped halfway was sent again on a new connection a second later, sealed afresh under a new IV, and answered 201. The clip plays.
+
+#### Sizes
+
+- **A media segment larger than about 10 MB is refused with 413.** I measured the limit between 9.10 MB, accepted, and 11.92 MB, refused. For scale, four seconds at the guide's highest 4K bitrate is about 2.5 MB.
+- HEVC clips at 1920 by 1080 and at 3840 by 2160 are accepted and play. So is a camera's own stream passed straight through, untouched, at a size the guide doesn't list.
+- Opus sound plays, and so does AAC-LC. A `CODECS` attribute naming Opus is taken.
+
+#### What The Home App Does With A Clip
+
+- **A clip is placed in the timeline at the moment its first object arrives.** Nothing moves it: not the times in its `prft` boxes, not an `#EXT-X-PROGRAM-DATE-TIME` line, not the timestamps of the hub's command. A clip sent ten minutes after its command stood ten minutes late.
+- The Home app ties a hub's event to an uploaded recording that starts within 5.0 seconds of where it expects one. Since a clip is dated by its arrival, it sits later than the hub's own reckoning of where the recording began, and one event whose expected start fell eight seconds before the upload arrived was dropped. Start uploading the moment the Start comes.
+- Clips that overlap in time show as one clip.
+- **A clip needs nothing from the camera to play.** It plays while the camera is switched off.
+- The timeline shows the clips of whichever recording path the camera's current services belong to. A camera that moves from HAP's older recording to HKSV3 seems to lose its old clips, and gets them back if it returns. They're hidden, not deleted.
+- **Before you doubt an upload, restart things.** More than once the Home app showed a fresh clip's event and played nothing until the app was restarted. Once a single phone showed a clip as a black picture, while another device played it, until that phone was restarted.
+
+**In HAP-NodeJS** a clip's upload is given 15 seconds after its recording ends to finish. A process that exits sooner loses the end of the clip.
+
+### 9. Snapshots
+
+A camera that publishes the new services is asked for its snapshots over the HomeKit Data Stream, and only there. HAP's older `/resource` request is never used for such a camera. Neither Apple's guide nor HAP describes this exchange.
+
+**The request** is `dataSend.open` with the type `ipcamera.snapshot`, the target `controller` and the reason `snapshot`. Its metadata carries `imageWidth` and `imageHeight`, and usually a `reason`.
+
+**The reply** is shaped like one chunk of a recording:
+
+- Answer the open with status 0.
+- Send one data event whose packet carries the picture, a JPEG, with `dataSequenceNumber` 1, `dataChunkSequenceNumber` 1, `isLastDataChunk` true and `dataTotalSize`, and with `endOfStream` true.
+- The asker acknowledges the stream, and the Home app shows the picture.
+
+What to expect:
+
+- Two sizes are asked for: 1280 by 720 while a viewer at home has the camera on screen, about every ten seconds, and 640 by 360 for a viewer who's away. A hub fetches snapshots on behalf of a viewer who is away.
+- On an iPhone, a camera's tile in the Home app is drawn from snapshots, not from a live stream.
+- The reply I tested carried no `dataType` field.
+- A doorbell press brings a burst: eleven snapshots inside five seconds.
+- **There's no fallback.** A request that goes unanswered is closed about five seconds later, and no snapshot shows. A camera that lists the new services and doesn't serve snapshots this way shows none at all.
+- The picture in a motion notification is not a snapshot. It's a frame of the recording the hub pulled.
+
+### 10. Doorbells
+
+A doorbell is a camera with HAP's Doorbell service on the same accessory. A press is a single press on Programmable Switch Event, which viewers subscribe to.
+
+- **A press brings a recording by itself.** With no motion raised, a hub opened a data stream and asked for a recording 50 milliseconds after a press, commanded an upload, and kept the clip. The new services carry no list of recording triggers, and none is needed.
+- A press brings the alert's snapshots at once, as section 9 describes.
+- A doorbell records on motion exactly as a camera does.
+- A doorbell with two sensors is shown as a plain camera with two sensors is: one view, the first sensor's.
+
+### 11. Refusals And Failures In One Place
+
+What the far end does when a camera says no, or gets something wrong.
+
+| What The Camera Does | What Comes Back |
+| ------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Refuses Setup Endpoints with a Status of Error, its Status Active reading false | At home the Home app shows the camera as in use, and asks again about every three seconds while the camera is on screen. |
+| Refuses WebRTC Solicit Offer with a Status of Error | From away the Home app shows the last picture, frozen, or the camera crossed out. The hub asks again, at anything from not at all to dozens of times a second. |
+| Answers its stream services' reads and writes with HAP status -70402 | The Home app shows No Response, at home and from away, and asks far less often. |
+| Offers a video section with no SSRC, a single-stream video section with no rid line and no header extensions, or AAC in place of Opus | The session is ended unanswered, within a second. |
+| Offers a rid line with no restrictions, or Opus written `opus/48000/2` with no format parameters | The offer is answered, and the hub ends the session within seconds. |
+| Sends video without SFrame, or under the four-byte tag | The session is kept, nothing is shown, and the hub ends it at about a minute. |
+| Puts a stream ID on its RTP packets | The viewer refuses every video packet. The hub ends the session at about a minute. |
+| Stamps each tier on a clock of its own | The viewer plays the first tier it takes, and discards every frame of the next. |
+| Advertises an H.264 tier | Sessions start, keyframe requests come several times a second, and no picture is ever shown. |
+| Sends a keyframe stamped the same as the last picture it sent | The viewer doesn't take it, and keeps asking until the stream's next keyframe. |
+| Serves a recording without `prft` boxes | The hub pulls it to a normal close, writes no verdict and no command, and nothing is kept. |
+| Refuses a recording with Not Allowed | Every hub in the home asks once for that motion. |
+| Refuses a recording with Busy | One hub asks once. |
+| Answers a recording's open with success, then an empty end of stream | The hub neither acknowledges nor closes it. |
+| Declines a snapshot, or doesn't answer one | The stream is closed, and no snapshot shows. |
+| Uploads nothing after a Start | No clip appears, whatever the hub decided. |
+| Uploads over HTTP/1.1, by `POST`, or with a plain `User-Agent` | 426, 404 and 400. |
+| Reuses a session folder's number | 208 for the multivariant playlist, and 400 for the media. |
+| Uploads a segment larger than about 10 MB | 413 for that segment. |
+| Uploads a clip sealed under the wrong key, or naming its key at the wrong address | 201 for every object, and a clip that stands in the timeline and won't play. |
+
+### 12. Open Points
+
+These are the questions whose answers would change what you build, or explain something your users will see. For every one of them, a working camera was confirmed without the answer.
+
+**Provisioning and credentials**
+
+- _Untested_: how long a publishing point stays good, and what else can spoil it. Uploads were accepted 34 and 99 hours after an address was written. Once, though, a camera's kept credentials were refused with a 401 after a short spell in the legacy form, and I don't know why, or how the hub knew to provision it again.
+- _Untested_: what happens to a clip that's still uploading when a hub provisions the camera again. The worst case is the end of one clip.
+- _Untested_: whether the session folder count starts over when a camera is unpaired and paired again. Keep counting through an unpairing if you can.
+- _Untested_: a pairing that has never held a certificate, given the new services without a change of Firmware Revision. Every camera I upgraded this way had been provisioned at least once before. _Inferred_: it's provisioned like any other.
+
+**Recording**
+
+- _Untested_: what a hub's analysis counts as worth keeping. A person walking into view turns the verdict, and so does a moving shape. One still, dark picture was also judged worth recording, and I can't say why.
+- _Untested_: the exact segment size limit, somewhere between 9.10 and 11.92 MB.
+- _Untested_: why some clips open late. Two clips of a camera's own stream, passed through at more than twice the guide's highest bitrate for its size, opened at their second segment, though they play whole when you seek back. One ordinary 60-second clip opened 24 seconds in. Clips at the guide's bitrates otherwise open at their start.
+- _Untested_: the StartAndStop command and the Pause stop action, which no hub has written.
+- _Untested_: whether a doorbell press over a perfectly still picture makes a hub keep a clip. Mine had something moving in view.
+
+**Live views**
+
+- _Untested_: a Solicit Offer that carries Options, asking for SFrame or refusing it. The guide defines the field and no hub has sent it. _Inferred_: seal, and return a key, regardless.
+- _Untested_: any network but mine. Every view from away left one home network, where host candidates were enough.
+- _Untested_: six WebRTC sessions at once, which the guide requires. Two devices watching together share one session, and I never had more than a few.
+- _Untested_: a request to resend a lost packet. None has ever arrived.
+- _Untested_: whether any Apple device shows a second sensor. None I tried does.
+- _Untested_: motion zones. I publish the service, and I haven't tested what a hub writes to it.
+- _Untested_: the Privacy Mode Active answer to a Solicit Offer, which the guide defines. I've only refused with Error.
+- _Untested_: how talkback from away sounds when a camera plays it as it arrives. Everything I listened to had been laid end to end first.
+
+## Appendices
+
+### A. Field Layouts
+
+#### The `prft` Box
+
+The producer reference time box that goes in front of every fragment of a recording. All numbers are big-endian.
+
+| Bytes | Field | Value |
+| -------- | ------------------ | ----------------------------------------------------------------- |
+| 0 to 3 | Size | 32 |
+| 4 to 7 | Type | `prft` |
+| 8 | Version | 1 |
+| 9 to 11 | Flags | 24 |
+| 12 to 15 | Reference track ID | The video track's ID. |
+| 16 to 23 | NTP timestamp | The clock time the fragment begins, as a 64-bit NTP timestamp. |
+| 24 to 31 | Media time | The fragment's first decode time, in the video track's timescale. |
+
+#### Timestamps In The Hub's Commands
+
+Start in Buffer Activity Command, and Start and Stop in Buffer Upload Command, are 64-bit NTP timestamps: seconds since 1900 in the upper 32 bits, and the fraction of a second in the lower 32. Duration in Buffer Activity Command is in milliseconds.
+
+#### A Sealed Media Segment
+
+| Bytes | Field |
+| ----------------- | ----------------------------------------------------------------------------------- |
+| 0 to 15 | IV, random, fresh for each segment. |
+| 16 to the last 17 | AES-256-GCM ciphertext of the whole segment, with no additional authenticated data. |
+| The last 16 | Authentication tag. |
+
+```text
+content key = HKDF-SHA-256(key: Camera Key, salt: empty, info: "HomeKit 1.0 CMAF Content", 32 bytes)
+key identifier = (key number << 16) | 0x4000, written in hexadecimal
+key address = "hksv3:" || key identifier || ".key"
+```
+
+#### The Playlists
+
+A multivariant playlist, for one track file that holds picture and sound:
+
+```text
+#EXTM3U
+#EXT-X-VERSION:7
+#EXT-X-INDEPENDENT-SEGMENTS
+#EXT-X-SESSION-KEY:METHOD=AES-256-GCM,URI="hksv3:3a94c1f07be24000.key"
+
+#EXT-X-STREAM-INF:BANDWIDTH=1800000,AVERAGE-BANDWIDTH=1700000,RESOLUTION=1920x1080,CODECS="hvc1.1.6.L120.b0,Opus"
+high/index.m3u8
+```
+
+Its media playlist, as it reads when the clip closes. The opening one is the same down to the `#EXT-X-KEY` line, and stops there.
+
+```text
+#EXTM3U
+#EXT-X-VERSION:7
+#EXT-X-TARGETDURATION:4
+#EXT-X-MEDIA-SEQUENCE:1001
+#EXT-X-PLAYLIST-TYPE:EVENT
+#EXT-X-INDEPENDENT-SEGMENTS
+#EXT-X-MAP:URI="high.init"
+#EXT-X-KEY:METHOD=AES-256-GCM,URI="hksv3:3a94c1f07be24000.key"
+#EXTINF:4.000000,
+segment_1001.m4s
+#EXTINF:4.000000,
+segment_1002.m4s
+#EXT-X-ENDLIST
+```
+
+A clip may name the sensor it came from with one more line in the multivariant playlist, after `#EXT-X-INDEPENDENT-SEGMENTS`:
+
+```text
+#EXT-X-SESSION-DATA:DATA-ID="com.apple.homekit.sensor-id",VALUE=""
+```
+
+#### The Byte In Front Of An SFrame Payload
+
+| Value | Meaning |
+| ------ | ---------------------------------------------- |
+| `0x80` | The first packet of a ciphertext. |
+| `0x00` | A middle packet. |
+| `0x40` | The last packet. |
+| `0xC0` | The only packet: the whole ciphertext is here. |
+
+#### Key IDs
+
+| Key | Form |
+| ---------------------------------------- | ------------------------------------------------------------------------------------ |
+| A clip's content key | The Camera Key's key number, shifted left 16 bits, with `0x4000` in the low sixteen. |
+| A viewer's receive key, written by a hub | 64 bits, with `0x8000` in the low sixteen. |
+| The camera's own SFrame key | 64 bits of the camera's choosing. Mine carry `0x8000` in the low sixteen. |
+
+### B. A Worked Offer
+
+An offer for a camera of three tiers, with made-up addresses, credentials and SSRCs. Lines every WebRTC stack writes for itself are left as they'd ordinarily appear.
+
+```text
+v=0
+o=- 4611731400430051336 2 IN IP4 127.0.0.1
+s=-
+t=0 0
+a=group:BUNDLE 0 1 2 3
+m=video 9 UDP/TLS/RTP/SAVPF 99
+c=IN IP4 0.0.0.0
+a=mid:0
+a=sendonly
+a=rtcp-mux
+a=setup:actpass
+a=ice-ufrag:Zq3x
+a=ice-pwd:u1Hc9mWq0fTn2RkV7yLbXe4d
+a=fingerprint:sha-256 4A:1F:...:9C
+a=rtpmap:99 H265/90000
+a=rtcp-fb:99 nack
+a=rtcp-fb:99 nack pli
+a=rtcp-fb:99 ccm fir
+a=extmap:1 urn:ietf:params:rtp-hdrext:sdes:mid
+a=extmap:2 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id
+a=rid:1 send max-width=1920;max-height=1080;max-fps=30;max-br=1700000
+a=simulcast:send 1
+a=ssrc:2890137601 cname:camera
+a=candidate:1 1 udp 2130706431 192.0.2.10 50112 typ host
+m=video 9 UDP/TLS/RTP/SAVPF 99
+a=mid:1
+a=sendonly
+a=rtpmap:99 H265/90000
+a=rid:2 send max-width=1280;max-height=720;max-fps=30;max-br=768000
+a=simulcast:send 2
+a=ssrc:1177460482 cname:camera
+m=video 9 UDP/TLS/RTP/SAVPF 99
+a=mid:2
+a=sendonly
+a=rtpmap:99 H265/90000
+a=rid:3 send max-width=640;max-height=360;max-fps=15;max-br=180000
+a=simulcast:send 3
+a=ssrc:3406022915 cname:camera
+m=audio 9 UDP/TLS/RTP/SAVPF 110
+a=mid:3
+a=sendonly
+a=rtpmap:110 opus/48000
+a=fmtp:110 minptime=20;useinbandfec=0
+a=ssrc:902114308 cname:camera
+```
+
+The second and third video sections and the audio section repeat the transport, feedback and extension lines of the first. They're left out here to keep the example readable. Notice that the four SSRCs differ in their low sixteen bits.
+
+The answer that comes back keeps the four sections. What's worth recognizing in it:
+
+```text
+a=group:BUNDLE 0 1 2 3
+a=ice-lite
+m=video 9 UDP/TLS/RTP/SAVPF 99
+a=recvonly
+a=setup:active
+a=rtcp-mux
+a=rtcp-rsize
+a=rtpmap:99 H265/90000
+a=fmtp:99
+a=rid:1 recv
+a=simulcast:recv 1
+a=end-of-candidates
+```
+
+Ahead of `a=end-of-candidates` come two host candidates for the relay, on one address in Apple's 17.0.0.0/8 block: one on a UDP port that changes from view to view, and one on TCP port 80.
+
+### C. Timings I Observed
+
+All from my home, my network and my hubs. They show the pace of things and promise nothing.
+
+| From | To | Time |
+| ------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------- |
+| Pairing | The hub's first round of settings | Within 2 seconds |
+| The first provisioning write | The fourth | Within 2 seconds |
+| Provisioning | Recording switched on | 6 to 7 seconds |
+| Motion Detected | The hub's connection | About 150 milliseconds |
+| Motion Detected | The hub's request for a recording | Usually 50 to 250 milliseconds |
+| A fragment sent | Its verdict | 0.26 to 0.92 seconds, most often about 0.3 |
+| A Should Record verdict | The Start command | 5 to 11 milliseconds |
+| Motion Detected | The Start command | Typically 2 to 4 seconds |
+| The hub closing a recording | The Stop command | 5 to 38 milliseconds |
+| A clip's Start | A forced cut to a new clip | 300 seconds |
+| A viewer at home reading the database | Its Setup Endpoints write | 50 to 70 milliseconds |
+| A view's Start at home | Its first keyframe request, when it isn't handed a keyframe first | 50 to 80 milliseconds |
+| A lost packet at home | A keyframe request | Usually within 0.1 seconds |
+| Solicit Offer | The answer | Usually 0.12 to 0.25 seconds |
+| The answer | The viewer's first key | Usually 0.2 to 0.5 seconds. As long as 40 |
+| A viewer's key | Keyframe requests on the smallest, middle and largest tier | Within about 1 second, 1 to 2 seconds, and 5 to 6 seconds |
+| A lost packet from away | A keyframe request | 0.3 to 1.2 seconds |
+| A session's keys removed | The session ended | Usually 0.2 seconds |
+| A session with no picture | The hub ending it | About a minute |
+| An unanswered snapshot request | Its stream closed | About 5 seconds |
+| A certificate issued | Its expiry | 60 days |
diff --git a/guides/UpgradingCameraPlugins.md b/guides/UpgradingCameraPlugins.md
new file mode 100644
index 000000000..3c24a9b3c
--- /dev/null
+++ b/guides/UpgradingCameraPlugins.md
@@ -0,0 +1,316 @@
+# Upgrading a Camera Plugin to HAP-NodeJS 2.4
+
+HAP-NodeJS 2.4 adds the camera features Apple introduced with iOS 27, which Apple calls HKSV3 internally: live video in tiers, views from away over WebRTC, and recordings the camera uploads itself. What those are, and how a home hub behaves around them, is written up in [HomeKit Cameras in iOS 27](HKSV3Protocol.md). This guide is the other half: what changed in the library, and what a plugin author does about it.
+
+Two terms come up throughout. A camera in the **modern form** is a camera set up for iOS 27 and later, with those features. A camera in the **legacy form** is a camera set up the way it always has been. A plugin chooses the form for each camera.
+
+## The Short Version
+
+Moving a camera to the modern form means writing less code, not more. The library now does most of the work a camera plugin used to carry.
+
+**What you provide:**
+
+- **A description of the camera**: the video sizes and bitrates it offers.
+- **A video stream for each of those**: fragmented MP4, with HEVC video and Opus audio, handed to the library as it arrives. `ffmpeg` writes it with two options.
+- **A snapshot function** that answers a JPEG.
+- **Motion**, reported with one call.
+- **Optionally, somewhere to send a visitor's voice**, if the camera has a speaker.
+
+**What you no longer write:**
+
+- **Stream negotiation.** No `prepareStream`, no ports, no SRTP keys, no session for each viewer. The library runs every session, at home and from away.
+- **A process for each viewer.** Each of the camera's streams runs once, however many people are watching it.
+- **Recording.** No recording delegate, no prebuffer of your own, no fragments to cut. The library keeps the recent video, hands a hub what it asks for, and encrypts and uploads each clip.
+- **Mute, session limits and requests for a fresh picture.** The library handles each.
+- **Shutdown code.** You register what you start, and the library releases it when it's no longer needed.
+
+Most of a camera plugin's streaming and recording code goes away. What's left is the part only you can do: getting video out of your camera.
+
+And nothing forces the move. A camera in the legacy form keeps working as it does today.
+
+## Who Needs To Do What
+
+- **Your plugin has no camera.** Check the Node.js version below. Two other items in [What Changed For Every Plugin](#what-changed-for-every-plugin) can reach you, and both are rare: a `Characteristic` subclass that declares a name the class now uses, and a `DataStreamServer` used after it's destroyed.
+- **Your plugin has a camera and you want it to keep working as it does.** Read [What Changed For Every Plugin](#what-changed-for-every-plugin). It's a short list, and most plugins will find nothing in it that touches them.
+- **You want the iOS 27 features.** Read the whole guide. A camera takes the modern form by stating a new block of options, and that camera then streams and records through the library.
+
+## What Changed For Every Plugin
+
+### Requirements
+
+- **Node.js `^22.20.0 || ^24 || ^26`.** The floor was `^22.12.0`. Node 22.12 through 22.19 are now outside the supported range.
+- **A new dependency, `werift`.** It's the WebRTC stack behind views from away. It installs with the library for everyone and is loaded only when a camera in the new form is built. A plugin without one never loads it.
+
+### Changes You Can Meet At Compile Time
+
+No name the library exported in 2.3.1 was removed or renamed. A few declared shapes changed, and TypeScript will tell you if one of them reaches your code.
+
+- **`CameraControllerOptions` is now a union** of two forms, `CameraControllerLegacyOptions` and `CameraControllerCapabilitiesOptions`. Building a controller from an object literal compiles as before. What stops compiling is an interface that `extends` it, a class that `implements` it, and a read of a member through a value typed as the union, such as `options.streamingOptions.video`. Type such a value as `CameraControllerLegacyOptions` and it compiles again.
+- **`RTPStreamManagement.setupEndpointsResponse` is gone.** The answer to Setup Endpoints is now served to the connection that asked and is never stored.
+- **`RecordingManagement.options` is optional**, and so are five fields of `RecordingManagementState`: `recordingActive`, `recordingAudioActive`, `eventSnapshotsActive`, `homeKitCameraActive` and `periodicSnapshotsActive`. A read of one into a plain `boolean`, or of `recordingManagement.options.prebufferLength`, needs a check first.
+- **`CameraRecordingDelegate.handleRecordingStreamRequest` returns `AsyncIterable`**, where it returned `AsyncGenerator`. A delegate you implement is unaffected. Code that calls `.next()` or `.return()` on the result is.
+- **`CameraControllerEvents` has more members.** A `switch` that proves it covers every event needs the new ones.
+- **`CameraController` has new members**: `recordingAllowed`, `streamingAllowed`, `latestKeyframe`, `updateMotionDetected`, `updateSourceState` and `handleAccessoryContext`. A subclass that declares one of those names, `motionSensorRequired`, or a name the class now keeps privately, such as `snapshot` or `streaming`, stops compiling.
+- **`CharacteristicProps` gains `transient` and `sensitive`, and `Characteristic` gains `releaseTransientAnswers`.** A subclass that declares that name stops compiling.
+
+### Changes To A Camera At Run Time
+
+These apply to a camera set up exactly as it was in 2.3.1.
+
+- **A controller with no `delegate` or no `streamingOptions` throws when it's constructed**, and so does a `recording` given without its `options`. In 2.3.1 and earlier these were assigned unchecked. TypeScript already refused them. This reaches JavaScript callers alone.
+- **`microphone-change` and `speaker-change` no longer go through `emit`.** Listeners added with `on` hear them as before, each called in turn and guarded: one that throws doesn't stop the next. A subclass that overrides `emit`, or a test that spies on it, no longer sees these two events.
+- **A recording delegate can hear `updateRecordingActive` at more moments**: when the camera finishes restoring its saved state with a value that differs from the stored one, before the first recording if it hasn't been told yet, and when the value changes by something other than a write. The configuration is still handed over before it.
+- **Setup Endpoints keeps no value.** `characteristic.value` reads nothing for it, and a serialized accessory stores `null` there. A hub's write and read are served as before.
+- **A snapshot handler whose promise rejects fails its snapshot at once.** In 2.3.1 and earlier the rejection went unhandled and the request waited out its 25 seconds. The warning at 8 seconds and the failure at 25 are unchanged.
+
+One more applies wherever a HomeKit Data Stream is used, a remote with Siri as much as a camera:
+
+- **A destroyed `DataStreamServer` stays destroyed.** A later `prepareSession` is answered with the error `The data stream server was destroyed.`, which is also the error now given to a session that was waiting when the server was destroyed.
+
+## The Two Forms Of A Camera
+
+A camera is now set up in one of two forms, and the options you hand `CameraController` decide which.
+
+- **The legacy form** is the camera you already have: a streaming delegate that negotiates SRTP, and for HomeKit Secure Video a recording delegate that hands a hub fragments. Nothing about it is deprecated.
+- **The modern form** is a camera that states a `cameraCapabilities` block. It offers its video in tiers, answers views from away over WebRTC, and uploads its own recordings. It's for a home on iOS 27 or later.
+
+A camera is one or the other, never both. The two forms publish different services, and a controller picks its stream by what it finds. A camera that published both would be shown through whichever stream services carry the lower instance IDs, which is rarely the one you'd choose. The types refuse a mix, and so does the constructor.
+
+Two things decide whether a camera can take the modern form:
+
+- **It hands you HEVC video and Opus audio.** The modern form advertises nothing else. A camera that can only produce H.264 stays in the legacy form.
+- **Its home is on iOS 27 or later.** The services behind the modern form are an iOS 27 feature.
+
+## Moving A Camera To The Modern Form
+
+### What Replaces What
+
+| In the legacy form | In the modern form |
+| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
+| `delegate.prepareStream` and `handleStreamRequest` | `cameraCapabilities.streaming.delegate.tierDemandStarted`. The library owns the sessions, ports, keys and SRTP. |
+| `delegate.handleSnapshotRequest(request, callback)` | `cameraCapabilities.snapshot(request, signal)`, which answers a promise. |
+| `streamingOptions`, with its resolutions, codecs and crypto suites | `cameraCapabilities.videoSensors`, each with its `tiers` and `audio`. |
+| `cameraStreamCount` | `streaming.maxSessions`, 5 by default, and `webrtc.maxSessions`, 6 by default. |
+| `recording.options` and `recording.delegate` | `cameraCapabilities.recording`, with `prebuffer` and `shouldRecord`. The library builds every recording and uploads every clip. |
+| `sensors.motion`, optional | `sensors.motion`, required unless the camera is a doorbell, since a hub starts a recording at motion. |
+| Muting your own streams on `microphone-change` and `speaker-change` | Nothing. The library applies mute itself. |
+| `controller.streamManagements` and `controller.recordingManagement.options` | Empty and `undefined`. A modern camera has no legacy stream or recording options to read. |
+
+### State The Camera
+
+A camera describes each of its video sensors once: its size, its tiers and its sound. Everything else the library fills in.
+
+The new types, `TierStream` and `MultiTierStreamingDelegate` among them, come from `@homebridge/hap-nodejs` with `import type`. Homebridge doesn't re-export them. Values, such as `CameraSensorIntent`, are reached through `api.hap` as always.
+
+```ts
+const camera = new hap.CameraController({
+ cameraCapabilities: {
+ snapshot: async (request, signal): Promise => await device.snapshot(request, { signal }),
+ streaming: { delegate },
+ videoSensors: [{
+ audio: { bitrate: 24 },
+ dimensions: { height: 2160, width: 3840 },
+ intent: hap.CameraSensorIntent.MAIN,
+ tiers: [
+ { bitrate: 4500, frameRate: 30, height: 2160, id: 1, quality: hap.CameraVideoQuality.HIGH, recorded: true, width: 3840 },
+ { bitrate: 768, frameRate: 30, height: 720, id: 2, quality: hap.CameraVideoQuality.MEDIUM, width: 1280 },
+ { bitrate: 180, frameRate: 15, height: 360, id: 3, quality: hap.CameraVideoQuality.LOW, width: 640 },
+ ],
+ uuid: hap.uuid.generate(device.mac),
+ }],
+ },
+ sensors: { motion: true },
+})
+```
+
+- **A sensor's `uuid`** must be a UUID and must stay the same across restarts. Derive it from something that identifies the device.
+- **A tier** is one encoding of the sensor's picture: `id`, `width`, `height`, `frameRate`, `bitrate` in kbps and `quality`. Apple's guide asks for three, and its highest bitrates are 5000 kbps for 4K, 3000 for 2K, 1800 for 1080p, 800 for 720p and 190 for 360p and 240p. `peakBitrate` defaults to that maximum, or to the tier's `bitrate` when the tier is above it or its size isn't listed.
+- **`recorded: true`** marks the one tier the camera records. With none marked, it's the first sensor's best tier.
+- **A tier runs on demand or all the time, and the choice is yours.** By default the library asks for a tier's stream when its first viewer arrives and ends it when the last one leaves, and the stream runs only while someone is watching. Mark a tier `keepRunning: true` and the library keeps it running whenever streaming is allowed. A view of it then opens at once, from pictures the library already holds, at the cost of a stream that never stops. The recorded tier is kept running whenever recording is allowed, whatever its mark.
+- **Start with tiers on demand.** Leave `keepRunning` off at first. See how quickly views open at home and from away, and only then decide whether any tier is worth keeping on all the time. A tier that never stops puts load on the camera or its controller and on the network around the clock, and on your processor too if you encode it yourself. Most cameras don't need that for every tier.
+- **The order of `videoSensors` matters.** The first is the one a controller shows and the one snapshots are asked for.
+- **The library copies your sensors and tiers.** Changing them afterwards changes nothing. Your delegate and your functions are kept as they are.
+
+A mistake in the block throws a `TypeError` from the constructor, whose sentence names the sensor and, for most mistakes, the member or tier at fault. A sensor's `intent` and a tier's `quality` must each be a member of its set: a value outside it, or one a JavaScript caller leaves out, is refused the same way. Falling below one of Apple's minimums, such as fewer than three tiers, is only a debug event unless you set `strict: true`, which turns the first one into a throw.
+
+### The New Sets Are Constant Objects
+
+`CameraSensorIntent`, `CameraVideoQuality` and `CameraZoneApplicationMethod` aren't enums. Each is a plain object of names and numbers, with a type of the same name. You use one as you'd use an enum, `hap.CameraVideoQuality.HIGH` as a value and `CameraVideoQuality` as a type, and four things differ:
+
+- **No name from a number.** `hap.CameraVideoQuality[2]` is `undefined`, where an enum answers `'HIGH'`. TypeScript refuses the lookup. Plain JavaScript reads `undefined` and says nothing.
+- **Walking the set gives one direction.** `Object.values` lists the numbers alone and `Object.keys` the names alone, where a numeric enum lists both in each.
+- **A computed number needs a member or a cast.** `const quality: CameraVideoQuality = n` compiles against an enum and is refused here.
+- **Two sets with the same numbers aren't told apart.** Another set's member with the same number is accepted where one of these is expected. Between two enums the compiler refuses that.
+
+One rarer case: a member used as a type is written `typeof hap.CameraSensorIntent.MAIN`.
+
+This is the form every set of named constants takes from 2.4 on. A constant object is plain JavaScript, with nothing generated for it at build time, and its type is exactly the set of its values. The enums the library has already released stay enums through 2.x, because changing their kind would break the plugins that use them. The project intends to move them to this form in the next major version.
+
+### Feed Each Tier
+
+`tierDemandStarted` is called when a tier gains its first consumer, whether that's a viewer or the library holding the tier for recording. You start the tier's video, from an encoder or straight from the camera, and write its bytes to the stream you're handed.
+
+```ts
+const delegate: MultiTierStreamingDelegate = {
+ tierDemandStarted: (stream: TierStream): void => {
+ const encoder = stream.use(spawn('ffmpeg', argsFor(stream.tier)))
+
+ encoder.on('error', (error: Error) => stream.fail(error.message))
+ encoder.on('exit', (code, signal) => stream.fail(`The encoder ended with ${signal ?? `code ${code}`}.`))
+ encoder.stdout.on('data', (chunk: Buffer) => stream.write(chunk))
+ },
+}
+```
+
+- **The stream is fragmented MP4**: an initialization segment, then fragments in the `default_base_moof` layout. The picture is the first video track, HEVC under `hvc1` or `hev1`. The sound is the first Opus track. From ffmpeg that's `-movflags empty_moov+default_base_moof` with `-frag_duration`. Fragments without `default_base_moof` fail the tier.
+- **Short fragments mean a short delay.** The library sends a fragment once its last byte arrives, which makes the fragment's length the delay a viewer sees. One frame per fragment is the shortest.
+- **Register what you start.** `stream.use(value)` takes anything with `[Symbol.dispose]` or `[Symbol.asyncDispose]`, a child process among them, and `stream.defer(fn)` takes a function. The library releases every registration once, when the tier loses its last consumer, and whenever the camera goes out of service. You write no shutdown code.
+- **A start may be asynchronous.** It's handed an abort `signal` as its second argument. Return a promise and hand that signal to what you await. A start that hasn't settled in 30 seconds is withdrawn. A rejection refuses the demand.
+- **`stream.discontinuity()`** marks a restart of your source, at a reconnect. **`stream.fail(reason)`** ends the tier for everyone on it and raises one problem.
+- **Report an encoder that dies.** Fail the tier when your encoder exits, as the example does. An exit you report ends the tier at once. The library also catches an encoder that stops writing without exiting: a stream that hands over no picture for 10 seconds, or no first picture within 30 seconds of your start settling, fails the tier as `stream.fail` does, whoever is on it. Sound alone doesn't count. The library raises one problem for that silence, and it asks again for a tier it keeps running. A view that was open on the tier can keep showing its last picture until it's closed, and the next view starts fresh. A failure reported after the library has ended the stream does nothing, which makes the exit its own shutdown causes harmless. A signal that stops your process can reach your encoder too, and its exit can then come before the library has ended the stream: once your own stop has begun, don't fail the tier for an exit, as the example does.
+- **`stream.tier.sound`** says whether this tier's stream must carry sound. Read it at each start.
+- **Stay within the tier's bitrates.** A heavier stream is accepted, never refused, but a view of it can start rough.
+
+### ffmpeg Recipes
+
+If ffmpeg produces a tier's stream, its arguments are three parts put together: what happens to the video, what happens to the sound, and an output part that never changes. Every part below was run with the ffmpeg that `ffmpeg-for-homebridge` ships, and its output read by the library's own stream reader.
+
+**The output part** is the same for every tier:
+
+```sh
+-f mp4 -movflags empty_moov+default_base_moof -frag_duration 33333 pipe:1
+```
+
+- **`-frag_duration` is the length of one frame in microseconds**: 33333 at 30 frames per second, 66666 at 15.
+- **Don't use `frag_every_frame` on a tier that carries sound.** ffmpeg then writes pairs of sound samples at one time, the first with no length, and the library fails the tier. `-frag_duration` gives the same one-frame delay without that.
+
+**The video part** is one of two:
+
+- **The camera gives HEVC.** Copy it: `-map 0:v:0 -c:v copy`. Nothing is encoded, and the keyframes are the camera's own. ffmpeg can't move them.
+- **The camera gives anything else.** Encode it to HEVC:
+
+```sh
+-map 0:v:0 -c:v libx265 -preset ultrafast -tune zerolatency -forced-idr 1 -x265-params keyint=30:min-keyint=30:scenecut=0:log-level=error -b:v 768k -maxrate 800k -bufsize 800k
+```
+
+- **Set `keyint` and `min-keyint` to the tier's frame rate** for a keyframe every second, and the three rates from the tier's `bitrate` and `peakBitrate`.
+- **For a smaller tier, scale after the `-map`**: `-vf fps=15,scale=640:360`.
+
+**The sound part** is one of three:
+
+- **No sound**: `-an`.
+- **The camera gives Opus.** Copy it: `-map 0:a:0 -c:a copy`.
+- **The camera gives anything else.** Encode it to Opus: `-map 0:a:0 -c:a libopus -application lowdelay -frame_duration 20 -ar 48000 -ac 1 -b:a 24000`. AAC copied through isn't read as sound. The library reads Opus alone.
+
+Three whole commands, with `` standing for however you read your camera.
+
+A camera that gives HEVC and Opus, both copied:
+
+```sh
+ffmpeg \
+ -map 0:v:0 -c:v copy \
+ -map 0:a:0 -c:a copy \
+ -f mp4 -movflags empty_moov+default_base_moof -frag_duration 33333 pipe:1
+```
+
+A camera that gives H.264 and AAC, encoded for a 1280 by 720 tier at 30 frames per second:
+
+```sh
+ffmpeg \
+ -map 0:v:0 -c:v libx265 -preset ultrafast -tune zerolatency -forced-idr 1 \
+ -x265-params keyint=30:min-keyint=30:scenecut=0:log-level=error -b:v 768k -maxrate 800k -bufsize 800k \
+ -map 0:a:0 -c:a libopus -application lowdelay -frame_duration 20 -ar 48000 -ac 1 -b:a 24000 \
+ -f mp4 -movflags empty_moov+default_base_moof -frag_duration 33333 pipe:1
+```
+
+The same camera's 640 by 360 tier at 15 frames per second:
+
+```sh
+ffmpeg \
+ -map 0:v:0 -vf fps=15,scale=640:360 -c:v libx265 -preset ultrafast -tune zerolatency -forced-idr 1 \
+ -x265-params keyint=15:min-keyint=15:scenecut=0:log-level=error -b:v 180k -maxrate 190k -bufsize 190k \
+ -map 0:a:0 -c:a libopus -application lowdelay -frame_duration 20 -ar 48000 -ac 1 -b:a 24000 \
+ -f mp4 -movflags empty_moov+default_base_moof -frag_duration 66666 pipe:1
+```
+
+- **Keyframes come from the encoder, or from the camera.** The encoded recipes ask for one every second. With copied video, set the interval on the camera itself.
+- **A fragment can hold no picture, or two.** A source that counts time in milliseconds doesn't line up with `-frag_duration` exactly, and a tier with sound has fragments that hold sound alone. The library reads all of these.
+
+### Sound And Talkback
+
+- **Sound is Opus**, one channel in 20 millisecond packets unless you state otherwise. With `audio.source` left at `'tier'`, every tier's stream carries its own Opus track. With `'shared'`, one tier carries the sound for the whole sensor, which saves encoding it several times.
+- **The Microphone is always published.** The Speaker is published exactly when your delegate has a `talkbackStarted` method. Give a camera that method only if it has a speaker.
+- **`talkbackStarted(talker)`** is called once for each talker in a view, and answers a sink with a `write(packet)` method. Each packet is a plain RTP packet carrying Opus. From away a packet can hold 40 milliseconds where one at home holds 20, and packets can arrive in clumps: read each packet's length from the packet and pace by its timestamp. Answer `undefined` to decline that talker. The call must answer at once: a promise is treated as a decline.
+
+```ts
+if (device.hasSpeaker) {
+ delegate.talkbackStarted = (talker: Talker): TalkbackSink => talker.use(new TalkbackDecoder(talker.sensorUUID))
+}
+```
+
+- **Mute is the library's job.** A muted Microphone sends no live sound and a muted Speaker gets no talkback, without any code of yours.
+
+### Snapshots
+
+`snapshot(request, signal)` answers a promise of a JPEG at the size asked. The library refuses a snapshot itself, without calling you, while the user has the camera switched off or the camera is out of service. The `signal` aborts at 25 seconds, when whoever asked has gone, and when the camera is removed.
+
+The request carries `keyframe` when a running tier has one: an MP4 holding a single HEVC picture, with its `age`. Decoding it is often faster than asking the camera for a picture.
+
+### Recording
+
+In the modern form you build no recording and no clip. While the user allows recording, the library keeps the recorded tier running, holds its recent video, hands a hub what it asks for, and uploads the clip when the hub says to keep it.
+
+- **`prebuffer`** is how far back each recording reaches, in milliseconds: 5000 by default, 30000 at most.
+- **`shouldRecord(start)`** lets you decline a recording. It's asked once, and must answer `true` or `false` on the spot.
+- **The recorded tier's stream is what gets uploaded.** It has to be what Apple's guide accepts: HEVC at up to 3840 by 2160 and 24 or 30 frames per second, with Opus audio. The guide asks for recorded sound captured at 16 or 24 kHz. Opus counts time at 48 kHz whatever rate the sound was captured at, and that's what the library advertises. Keep the stream within the guide's bitrates. Apple's service refuses a segment that's too large, and in testing the cap was 10 MB. The library cuts segments at keyframes to stay under that, and can only do it if the stream has keyframes often enough.
+- **`recording-started` and `recording-ended`** tell you of each recording.
+
+### Motion
+
+- **Report motion with `camera.updateMotionDetected(detected, sensorUUIDs)`.** The second argument says which sensors saw it, and may be left out.
+- **The user's Motion Enabled setting is honored for you.** While it's off, motion you report is held back: it's never stored and never sent to a hub. Clearing motion always goes through, and the library clears any standing motion itself when the setting turns off.
+- **Motion zones are opt-in.** Give a sensor a `motionZones(zones, reason, signal)` function and the library publishes that sensor's zones service. You're handed the zones a user draws, and handed them again when the camera restores its saved state and when it's reset.
+
+### Tell The Library When The Camera Goes Away
+
+`camera.updateSourceState(state)` tells the library what your source is doing.
+
+- **`'away'`**: the camera is unreachable. Every view and recording ends, and requests are refused without calling you.
+- **`'recovering'`**: you're reconnecting. Every running tier is held for up to 30 seconds from your call, whoever is on it, and the tiers the library keeps running, the recorded tier and each `keepRunning` tier, report no stall meanwhile. The tier's next picture ends the wait, and a tier that hands over none by then fails.
+- **`'available'`**: the camera is back.
+
+### Hear From The Library
+
+- **Events** on the controller: `operating-mode-change`, `streaming-enabled-change`, `recording-started`, `recording-ended`, `live-view-started` and `live-view-ended`, beside the two mute events. `operating-mode-change` carries each of the user's camera settings as it changes, with the field, its value and why it changed, and it's the event to read the camera's whole state at, typed `OperatingModeState`. A listener that throws is reported and doesn't stop the next.
+- **Manually Disabled.** If you add Manually Disabled to a modern camera, a hub can now switch it with a timed write. While it's set, nothing streams or records, and `operating-mode-change` reports the field `manuallyDisabled`.
+- **Problems.** `hap.onCameraProblem(accessoryUUID, listener)` hands you every problem a camera raises, each with a `kind`, a `level` and a `sentence`: a failed tier, a stalled stream, a failed upload, and a failure in your own code among them. It answers a disposable. While nothing is subscribed, the library prints each problem itself. Subscribe, and you decide how they're logged. Subscribe before you configure the controller, or you'll miss a problem raised while the camera restores its saved state.
+- **Debug output** is under names that begin `HAP-NodeJS:Camera:`, plus `HAP-NodeJS:RecordingProvisioning` and `HAP-NodeJS:HKSV`, read from `DEBUG` when the library loads.
+
+One caution. `HAP-NodeJS:Camera:WebRTC:werift` turns on the WebRTC stack's own output, which carries network addresses and session keys. It's off unless you name it exactly, and it shouldn't be pasted into a public issue.
+
+The accessory's own debug lines print `` for the camera's key material, including Setup Endpoints, and print other TLV8 values by size.
+
+## A Plugin That Serves Both Forms
+
+Most plugins will serve both: the modern form where a camera and the user's home can take it, and the legacy form everywhere else. That's one branch, at the point you construct the controller.
+
+```ts
+const controller = wantsModernForm(device)
+ ? new hap.CameraController({ cameraCapabilities: capabilitiesFor(device), sensors: { motion: true } })
+ : new hap.CameraController(legacyOptionsFor(device))
+```
+
+- **Check the library before you take the branch.** Homebridge pins HAP-NodeJS at one version, and your plugin will run on libraries with and without the modern form. Read the version from `api.hap.HAPLibraryVersion()` and take the modern form only at the first version that carries it, 2.4.0 or the beta you're testing against.
+- **Fall back if the constructor throws.** Wrap the modern construction, and on a throw build the legacy camera instead. A mistake the constructor catches then never takes a user's cameras away.
+- **Say so when the modern form is in use.** Users look for that line to see whether it worked.
+- **To change a camera's form, construct it in the other form at the next start.** The library adds and removes the services to match and tells HomeKit the configuration changed. A camera's settings aren't read again while it runs.
+- **A modern camera run on a library before 2.4 is half-working until the library moves forward again.** Nothing crashes and no setting is reset, but the older library lists the camera's new services with no code behind them: motion can read inactive, snapshots can go unanswered and a live view can fail to start. Going forward to 2.4 again restores it, and a camera that never used the modern form isn't affected.
+
+[homebridge-unifi-protect](https://github.com/hjdhjd/homebridge-unifi-protect) serves both forms this way, and is a working example to read.
+
+## A Checklist
+
+- Node.js is 22.20 or a later 22, or 24, or 26.
+- Your plugin compiles against 2.4.
+- For each camera you move: it produces HEVC and Opus, it states its sensors and tiers, its delegate feeds fragmented MP4, it has a motion sensor unless it's a doorbell, and it answers snapshots through the new function.
+- Your plugin checks the library's version, falls back to the legacy form on a throw, and logs when the modern form is in use.
diff --git a/package-lock.json b/package-lock.json
index 69d466781..e32415a3a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -14,7 +14,8 @@
"dbus-native": "^0.16.3",
"debug": "^4.4.3",
"fast-srp-hap": "2.0.5",
- "source-map-support": "^0.5.21"
+ "source-map-support": "^0.5.21",
+ "werift": "0.28.0"
},
"devDependencies": {
"@antfu/eslint-config": "^10.0.0",
@@ -36,7 +37,7 @@
"vitest": "^5.1.1"
},
"engines": {
- "node": "^22.12.0 || ^24 || ^26"
+ "node": "^22.20.0 || ^24 || ^26"
}
},
"node_modules/@antfu/eslint-config": {
@@ -1048,6 +1049,24 @@
"node": "^20.19.0 || ^22.13.0 || >=24"
}
},
+ "node_modules/@eslint/config-array/node_modules/minimatch": {
+ "version": "11.0.9",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
+ "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "peer": true,
+ "dependencies": {
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
"node_modules/@eslint/config-helpers": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz",
@@ -2156,6 +2175,21 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/dom-mediacapture-transform": {
+ "version": "0.1.12",
+ "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",
+ "integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/dom-webcodecs": "*"
+ }
+ },
+ "node_modules/@types/dom-webcodecs": {
+ "version": "0.1.13",
+ "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",
+ "integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",
+ "license": "MIT"
+ },
"node_modules/@types/escape-html": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@types/escape-html/-/escape-html-1.0.4.tgz",
@@ -2826,7 +2860,6 @@
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
- "dev": true,
"funding": [
{
"type": "github",
@@ -2958,6 +2991,30 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
+ "node_modules/buffer": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
+ "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.2.1"
+ }
+ },
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
@@ -4206,6 +4263,24 @@
"node": ">= 4"
}
},
+ "node_modules/eslint/node_modules/minimatch": {
+ "version": "11.0.9",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
+ "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "peer": true,
+ "dependencies": {
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
"node_modules/espree": {
"version": "10.4.0",
"resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",
@@ -4545,6 +4620,23 @@
"node": ">=10.13.0"
}
},
+ "node_modules/glob/node_modules/minimatch": {
+ "version": "11.0.9",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
+ "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
"node_modules/globals": {
"version": "17.14.0",
"resolved": "https://registry.npmjs.org/globals/-/globals-17.14.0.tgz",
@@ -4634,6 +4726,26 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
"node_modules/ignore": {
"version": "7.0.16",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.16.tgz",
@@ -5608,6 +5720,24 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/mediabunny": {
+ "version": "1.66.2",
+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.66.2.tgz",
+ "integrity": "sha512-NTzRrBhAyRVi8qpJ9AH6XPyxiDVkfugxYY+gu3Z5zi+Nw2R/7nTAnXJEt2Ucy8wTIve1/UYGnCFf50x2LpvMDQ==",
+ "license": "MPL-2.0",
+ "workspaces": [
+ ".",
+ "packages/*"
+ ],
+ "dependencies": {
+ "@types/dom-mediacapture-transform": "^0.1.11",
+ "@types/dom-webcodecs": "0.1.13"
+ },
+ "funding": {
+ "type": "individual",
+ "url": "https://github.com/sponsors/Vanilagy"
+ }
+ },
"node_modules/micromark": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz",
@@ -7776,6 +7906,20 @@
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0"
}
},
+ "node_modules/werift": {
+ "version": "0.28.0",
+ "resolved": "https://registry.npmjs.org/werift/-/werift-0.28.0.tgz",
+ "integrity": "sha512-Ro4r5OOtcLgx4VbrXGRS80sNZHptLIyJ2o/EGOj6dyRksTbiTLbtP/u2psDIpsXUOYl3vW+aK3YBPsKPl9SxJw==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer": "^6.0.3",
+ "mediabunny": "^1.62.1",
+ "multicast-dns": "^7.2.5"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+ },
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
diff --git a/package.json b/package.json
index 6772b15aa..fbe54d4aa 100644
--- a/package.json
+++ b/package.json
@@ -31,17 +31,19 @@
"files": [
"LICENSE",
"README.md",
- "dist"
+ "dist",
+ "!dist/accessories/ModernCamera_example.*"
],
"engines": {
- "node": "^22.12.0 || ^24 || ^26"
+ "node": "^22.20.0 || ^24 || ^26"
},
"scripts": {
"check": "npm install && npm outdated",
"clean": "rimraf dist && rimraf coverage",
"lint": "eslint .",
"build": "rimraf dist && tsc",
- "generate-definitions": "tsx src/lib/definitions/generate-definitions.ts && eslint --fix src/lib/definitions src/lib/Characteristic.ts src/lib/Service.ts",
+ "generate-definitions": "tsx src/lib/definitions/generate-definitions.ts",
+ "postgenerate-definitions": "eslint src/lib/definitions src/lib/Characteristic.ts src/lib/Service.ts",
"prepublishOnly": "npm run build",
"postpublish": "npm run clean",
"test": "vitest run",
@@ -58,7 +60,8 @@
"dbus-native": "^0.16.3",
"debug": "^4.4.3",
"fast-srp-hap": "2.0.5",
- "source-map-support": "^0.5.21"
+ "source-map-support": "^0.5.21",
+ "werift": "0.28.0"
},
"devDependencies": {
"@antfu/eslint-config": "^10.0.0",
diff --git a/src/accessories/ModernCamera_example.ts b/src/accessories/ModernCamera_example.ts
new file mode 100644
index 000000000..4c6501525
--- /dev/null
+++ b/src/accessories/ModernCamera_example.ts
@@ -0,0 +1,184 @@
+/* A camera in the modern form, stated through the camera capabilities block, which carries the camera features Apple introduced with iOS 27: a video
+ * sensor whose tiers serve live view at home and from away, recording from the camera buffer, snapshots, and a motion sensor raised by a switch on the
+ * accessory. Its picture and sound are ffmpeg's test pattern and tone, encoded as each tier is asked for, which is why it needs ffmpeg on the PATH with the
+ * libx265 and libopus encoders, and a home on iOS 27 or later to add it to.
+ *
+ * Run `npm run build`, then `node dist/accessories/ModernCamera_example.js`, and add the camera in the Home app with the setup code it prints. An interrupt
+ * unpublishes it and the process ends by itself. The pairing is kept in `persist` under the directory it runs from, and a later run from there reuses it...
+ * removing `persist` lets the camera be added afresh.
+ *
+ * It leaves out what a camera adds only where it needs it: talkback, a doorbell, a second sensor, motion zones, shared sound, a tier marked `keepRunning`,
+ * and `strict`.
+ */
+import type { CameraSnapshotRequest, TierStream } from '../index.js'
+
+import { Buffer } from 'node:buffer'
+import { spawn, spawnSync } from 'node:child_process'
+import { once } from 'node:events'
+import process from 'node:process'
+
+import { Accessory, CameraController, CameraSensorIntent, CameraVideoQuality, Categories, Characteristic, onCameraProblem, Service, uuid } from '../index.js'
+
+// The setup code the camera is added with, which the program prints once it is published.
+const PINCODE = '031-45-154'
+
+// The arguments of one tier's encoder: ffmpeg's test pattern at the tier's size and frame rate and its tone, encoded to HEVC with a keyframe each second
+// and to Opus, and written as fragmented MP4 one frame to a fragment, which keeps the delay a viewer sees to one frame.
+function encoderArguments(tier: TierStream['tier']): string[] {
+ const fragment = Math.round(1000000 / tier.frameRate)
+ const rate = tier.frameRate
+
+ return [
+ `-hide_banner -loglevel error -re -f lavfi -i testsrc2=size=${tier.width}x${tier.height}:rate=${rate}`,
+ '-re -f lavfi -i sine=frequency=440:sample_rate=48000',
+ `-map 0:v:0 -c:v libx265 -preset ultrafast -tune zerolatency -forced-idr 1 -x265-params keyint=${rate}:min-keyint=${rate}:scenecut=0:log-level=error`,
+ `-b:v ${tier.bitrate}k -maxrate ${tier.peakBitrate}k -bufsize ${tier.peakBitrate}k`,
+ '-map 1:a:0 -c:a libopus -application lowdelay -frame_duration 20 -ar 48000 -ac 1 -b:a 24000',
+ `-f mp4 -movflags empty_moov+default_base_moof -frag_duration ${fragment} pipe:1`,
+ ].join(' ').split(' ')
+}
+
+// Whether the program's own stop has begun, from which on an encoder's exit is the stop's doing and fails no tier.
+let stopping = false
+
+// A tier's encoder runs from its demand's start to its end: the library kills the registered process where the demand ends, whichever way it ends. An
+// encoder that cannot start or that ends by itself fails its tier, and the exit the library's own kill brings reaches a stream already ended, which ignores it.
+// An interrupt typed at a terminal reaches the encoder as well as the program, and the encoder's exit can come before the library has ended its stream,
+// which is why an exit fails no tier once the program's own stop has begun.
+function tierDemandStarted(stream: TierStream): void {
+ const encoder = stream.use(spawn('ffmpeg', encoderArguments(stream.tier), {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ }))
+
+ encoder.on('error', (error: Error) => stream.fail(error.message))
+ encoder.on('exit', (code, signal) => {
+ if (!stopping) {
+ stream.fail(`The tier's encoder ended with ${signal ?? `code ${code}`}.`)
+ }
+ })
+ encoder.stdout.on('data', (chunk: Buffer) => stream.write(chunk))
+ // The encoder's own errors are printed as they come, until the program's stop has begun: an encoder the interrupt has reached is ending as the
+ // library's kill arrives, and it reports that second signal as a run of errors.
+ encoder.stderr.on('data', (chunk: Buffer) => {
+ if (!stopping) {
+ process.stderr.write(chunk)
+ }
+ })
+}
+
+// A snapshot is the newest keyframe decoded to a JPEG at the asked size where the library hands one, and the test pattern at that size where it does not.
+async function snapshot({ height, keyframe, width }: CameraSnapshotRequest, signal: AbortSignal): Promise {
+ const input = keyframe
+ ? `-i pipe:0 -frames:v 1 -s ${width}x${height}`
+ : `-f lavfi -i testsrc2=size=${width}x${height} -frames:v 1`
+ // The child is started with the signal, and an abort ends it with an error, which the wait on its close takes as its rejection.
+ const ffmpeg = spawn('ffmpeg', `-hide_banner -loglevel error ${input} -f mjpeg pipe:1`.split(' '), {
+ signal,
+ stdio: ['pipe', 'pipe', 'inherit'],
+ })
+ const chunks: Buffer[] = []
+
+ ffmpeg.stdout.on('data', (chunk: Buffer) => chunks.push(chunk))
+ // An abort can fail a write still going to the child's input, and an error there ends the process unless a listener hears it.
+ ffmpeg.stdin.on('error', () => undefined)
+ ffmpeg.stdin.end(keyframe?.movie)
+
+ const [code] = await once(ffmpeg, 'close')
+ const picture = Buffer.concat(chunks)
+
+ if ((code !== 0) || (picture.length === 0)) {
+ throw new Error(`The snapshot's ffmpeg exited with code ${code} without a picture.`)
+ }
+
+ return picture
+}
+
+async function main(): Promise {
+ // ffmpeg and the encoders the tiers need are checked before anything is built, which means a missing one ends the program with nothing published and
+ // nothing stored.
+ const listing = spawnSync('ffmpeg', ['-hide_banner', '-encoders'])
+
+ if ((listing.status !== 0) || !['libx265', 'libopus'].every(encoder => listing.stdout.includes(encoder))) {
+ console.error('The example camera needs ffmpeg on the PATH with the libx265 and libopus encoders.')
+ process.exitCode = 1
+
+ return
+ }
+
+ const accessory = new Accessory('Modern Camera', uuid.generate('hap-nodejs:accessories:modern-camera'))
+
+ // The subscription comes before the controller is configured, which means it hears a problem the camera's restore of its saved state raises.
+ onCameraProblem(accessory.UUID, (problem) => {
+ if (problem.level === 'error') {
+ console.error(problem.sentence)
+ } else {
+ console.warn(problem.sentence)
+ }
+ })
+
+ const camera = new CameraController({
+ cameraCapabilities: {
+ snapshot,
+ streaming: {
+ delegate: { tierDemandStarted },
+ },
+ videoSensors: [
+ {
+ audio: { bitrate: 24 },
+ dimensions: { height: 1080, width: 1920 },
+ intent: CameraSensorIntent.MAIN,
+ tiers: [
+ {
+ bitrate: 1700,
+ frameRate: 30,
+ height: 1080,
+ id: 1,
+ quality: CameraVideoQuality.HIGH,
+ width: 1920,
+ },
+ {
+ bitrate: 768,
+ frameRate: 30,
+ height: 720,
+ id: 2,
+ quality: CameraVideoQuality.MEDIUM,
+ width: 1280,
+ },
+ {
+ bitrate: 180,
+ frameRate: 15,
+ height: 360,
+ id: 3,
+ quality: CameraVideoQuality.LOW,
+ width: 640,
+ },
+ ],
+ uuid: uuid.generate('hap-nodejs:accessories:modern-camera:sensor'),
+ },
+ ],
+ },
+ sensors: { motion: true },
+ })
+
+ accessory.configureController(camera)
+
+ // The switch stands in for a camera's own motion detection: turning it on reports motion, which a home hub records while the camera's recording is on,
+ // and turning it off clears it.
+ accessory.addService(Service.Switch, 'Motion Trigger')
+ .getCharacteristic(Characteristic.On)
+ .onSet(value => camera.updateMotionDetected(value === true))
+
+ // Unpublishing keeps the pairing, where destroying the accessory would remove it, and the process ends once the camera's servers and encoders have closed.
+ // The handler is registered for one interrupt, which means a second one ends the process straight away. It marks the stop as begun before it
+ // unpublishes, since the interrupt may have reached the encoders too.
+ process.once('SIGINT', () => {
+ stopping = true
+ void accessory.unpublish()
+ })
+
+ await accessory.publish({ category: Categories.CAMERA, pincode: PINCODE, username: 'C2:5E:7A:31:94:D8' })
+ console.log(`${accessory.displayName} is published. Add it in the Home app with the setup code ${PINCODE}.`)
+}
+
+// A failure of the start is left unhandled, which ends the process with its stack.
+void main()
diff --git a/src/hap.ts b/src/hap.ts
index 5269522ad..24de3517e 100644
--- a/src/hap.ts
+++ b/src/hap.ts
@@ -1,10 +1,9 @@
-import { readFileSync } from 'node:fs'
-
import createDebug from 'debug'
// only used as types, for the documentation namespace at the end of this file. The definitions themselves are loaded by the import of definitions/index.js below
import * as Characteristics from './lib/definitions/CharacteristicDefinitions.js'
import * as Services from './lib/definitions/ServiceDefinitions.js'
+import { libraryVersion } from './lib/util/libraryVersion.js'
import 'source-map-support/register.js' // registering node-source-map-support for typescript stack traces
import './lib/definitions/index.js'
@@ -37,7 +36,22 @@ export * from './lib/util/eventedhttp.js'
export * from './lib/util/hapStatusError.js'
export * from './lib/util/once.js'
export * from './lib/util/time.js'
-export * from './lib/util/tlv.js'
+// The TLV module's helpers are named one by one: the 64-bit helpers the camera's fields read stay the library's own.
+export type { TLVEncodable } from './lib/util/tlv.js'
+export {
+ decode,
+ decodeList,
+ decodeWithLists,
+ encode,
+ readUInt16,
+ readUInt32,
+ readUInt64LE,
+ readVariableUIntLE,
+ writeFloat32LE,
+ writeUInt16,
+ writeUInt32,
+ writeVariableUIntLE,
+} from './lib/util/tlv.js'
/**
* @group Utils
@@ -47,8 +61,6 @@ export * from './types.js'
const debug = createDebug('HAP-NodeJS:Init')
-let libraryVersion: string | undefined
-
/**
* This method can be used to retrieve the current running library version of the HAP-NodeJS framework.
* @returns The SemVer version string.
@@ -56,9 +68,7 @@ let libraryVersion: string | undefined
* @group Utils
*/
export function HAPLibraryVersion(): string {
- // the version cannot change while the process runs, so the file is read only once
- libraryVersion ??= JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf-8')).version as string
- return libraryVersion
+ return libraryVersion()
}
function printInit() {
diff --git a/src/lib/Accessory.spec.ts b/src/lib/Accessory.spec.ts
index 1651fd535..d0045b8d1 100644
--- a/src/lib/Accessory.spec.ts
+++ b/src/lib/Accessory.spec.ts
@@ -19,15 +19,30 @@ import type {
CharacteristicGetCallback,
CharacteristicSetCallback,
} from './Characteristic.js'
-import type { Controller, ControllerIdentifier, ControllerServiceMap } from './controller/index.js'
+import type { Controller, ControllerAccessoryContext, ControllerIdentifier, ControllerServiceMap } from './controller/index.js'
import type { IdentifyCallback } from './HAPServer.js'
import type { PairingInformation } from './model/AccessoryInfo.js'
import { Buffer } from 'node:buffer'
import crypto from 'node:crypto'
+import { format } from 'node:util'
+import createDebug from 'debug'
+import tweetnacl from 'tweetnacl'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ capabilitiesCameraOptions,
+ createCameraControllerOptions,
+ FIRST_VIDEO_SENSOR,
+ idleStreaming,
+ MOCK_IMAGE,
+ snapshotFunction,
+} from '../test-utils/cameraFixtures.js'
+import { buildEmitterConnection } from '../test-utils/connectionFixtures.js'
+import { HAPHTTPClient } from '../test-utils/HAPHTTPClient.js'
+import { PairVerifyClient } from '../test-utils/PairVerifyClient.js'
+import { deferred, until } from '../test-utils/settle.js'
import {
ResourceRequestType,
} from '../types.js'
@@ -42,13 +57,15 @@ import {
Perms,
Units,
} from './Characteristic.js'
-import { createCameraControllerOptions, MOCK_IMAGE } from './controller/CameraController.spec.js'
import { CameraController } from './controller/index.js'
import { HAPHTTPCode, HAPServer, HAPStatus, TLVErrorCode } from './HAPServer.js'
import { AccessoryInfo, PermissionTypes } from './model/AccessoryInfo.js'
+import { ControllerStorage } from './model/ControllerStorage.js'
+import { HAPStorage } from './model/HAPStorage.js'
import { IdentifierCache } from './model/IdentifierCache.js'
+import { RecordingProvisioning } from './model/RecordingProvisioning.js'
import { Service } from './Service.js'
-import { EventedHTTPServer, HAPConnection } from './util/eventedhttp.js'
+import { EventedHTTPServer, HAPConnection, HAPConnectionEvent } from './util/eventedhttp.js'
import { HapStatusError } from './util/hapStatusError.js'
import { awaitEventOnce, PromiseTimeout } from './util/promise-utils.js'
import * as uuid from './util/uuid.js'
@@ -521,6 +538,653 @@ describe('Accessory', () => {
})
})
+ // The rows that follow publish under usernames of their own, every one cleaned after its row with whatever the row published.
+ const usernames: string[] = []
+ const published: Accessory[] = []
+
+ afterEach(async () => {
+ for (const target of published.splice(0)) {
+ await target.unpublish()
+ await target.destroy()
+ }
+
+ for (const username of usernames.splice(0)) {
+ Accessory.cleanupAccessoryData(username)
+ }
+ })
+
+ function username(last: number): string {
+ const name = `AB:CD:EF:00:33:${last.toString(16).padStart(2, '0').toUpperCase()}`
+
+ usernames.push(name)
+ return name
+ }
+
+ // Publishes an accessory through the advertiser the suite mocks, and nothing is announced.
+ async function publish(target: Accessory, name: string): Promise {
+ if (!published.includes(target)) {
+ published.push(target)
+ }
+
+ await target.publish({
+ advertiser: MDNSAdvertiser.BONJOUR,
+ category: Categories.CAMERA,
+ pincode: '031-45-154',
+ username: name,
+ })
+ }
+
+ describe('a controller\'s accessory context', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ // A camera whose every handed context is recorded as its UUID, whether it reads published and its username, the method itself still running.
+ function recordedCamera(): { camera: CameraController, contexts: { accessoryUUID: string, published: boolean, username?: string }[] } {
+ const camera = new CameraController(createCameraControllerOptions())
+ const contexts: { accessoryUUID: string, published: boolean, username?: string }[] = []
+ const handle = camera.handleAccessoryContext.bind(camera)
+
+ vi.spyOn(camera, 'handleAccessoryContext').mockImplementation((context) => {
+ contexts.push({ accessoryUUID: context.accessoryUUID, published: context.published, username: context.username })
+ handle(context)
+ })
+
+ return { camera, contexts }
+ }
+
+ function heldContext(camera: CameraController): unknown {
+ // @ts-expect-error: private access
+ return camera.accessoryContext
+ }
+
+ it('hands a published accessory\'s camera a context with its username and UUID once the restore has run', async () => {
+ const name = username(1)
+ const target = new Accessory('Camera', uuid.generate('context published'))
+ const source = new CameraController(createCameraControllerOptions())
+ source.constructServices()
+ source.configureServices()
+ HAPStorage.storage().setItemSync(ControllerStorage.persistKey(name), {
+ accessories: {
+ [target.UUID]: [
+ {
+ type: 'camera',
+ controllerData: {
+ data: source.serialize(),
+ },
+ },
+ ],
+ },
+ })
+ source.handleControllerRemoved()
+ const { camera, contexts } = recordedCamera()
+ const restore = camera.deserialize.bind(camera)
+ const handedBeforeRestore: number[] = []
+ vi.spyOn(camera, 'deserialize').mockImplementation((state) => {
+ handedBeforeRestore.push(contexts.length)
+ restore(state)
+ })
+ target.configureController(camera)
+
+ await publish(target, name)
+
+ expect(contexts).toEqual([
+ { accessoryUUID: target.UUID, published: false, username: undefined },
+ { accessoryUUID: target.UUID, published: false, username: name },
+ { accessoryUUID: target.UUID, published: true, username: name },
+ ])
+ expect(handedBeforeRestore).toEqual([1])
+ expect(heldContext(camera)).toEqual({
+ accessoryInformation: target.getService(Service.AccessoryInformation),
+ accessoryUUID: target.UUID,
+ published: true,
+ username: name,
+ })
+ })
+
+ it('hands an unpublished accessory\'s camera a context without a username', () => {
+ const target = new Accessory('Camera', uuid.generate('context unpublished'))
+ const { camera, contexts } = recordedCamera()
+
+ target.configureController(camera)
+
+ expect(contexts).toEqual([
+ { accessoryUUID: target.UUID, published: false, username: undefined },
+ ])
+ })
+
+ it('hands a bridged camera its bridge\'s username, and none once it leaves the bridge', async () => {
+ const name = username(2)
+ const bridge = new Bridge('Bridge', uuid.generate('context bridge'))
+ await publish(bridge, name)
+ const target = new Accessory('Camera', uuid.generate('context bridged'))
+ const { camera, contexts } = recordedCamera()
+ target.configureController(camera)
+
+ bridge.addBridgedAccessory(target)
+ bridge.removeBridgedAccessory(target)
+
+ expect(contexts).toEqual([
+ { accessoryUUID: target.UUID, published: false, username: undefined },
+ { accessoryUUID: target.UUID, published: true, username: name },
+ { accessoryUUID: target.UUID, published: false, username: undefined },
+ ])
+ })
+
+ it('hands a camera the new username when its accessory is published again under another', async () => {
+ const first = username(3)
+ const second = username(4)
+ const target = new Accessory('Camera', uuid.generate('context renamed'))
+ const { camera, contexts } = recordedCamera()
+ target.configureController(camera)
+ await publish(target, first)
+ await target.unpublish()
+
+ await publish(target, second)
+
+ expect(contexts.map(context => context.username)).toEqual([
+ undefined,
+ first,
+ first,
+ first,
+ second,
+ second,
+ ])
+ expect((heldContext(camera) as { username: string }).username).toBe(second)
+ })
+
+ it('hands a controller that is not serializable no context', async () => {
+ const target = new Accessory('Switch', uuid.generate('context plain'))
+ const controller = Object.assign(new TestController(), {
+ handleAccessoryContext: vi.fn(),
+ })
+ target.configureController(controller)
+
+ await publish(target, username(5))
+
+ expect(controller.handleAccessoryContext).not.toHaveBeenCalled()
+ })
+
+ it('hands a camera the same context again at a second publish, alone and behind a bridge, holding one equal to the first and loading or writing no '
+ + 'record', async () => {
+ const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync')
+ const load = vi.spyOn(RecordingProvisioning, 'load')
+ const name = username(6)
+ const target = new Accessory('Camera', uuid.generate('context repeated'))
+ const { camera, contexts } = recordedCamera()
+ target.configureController(camera)
+ await publish(target, name)
+ const held = heldContext(camera)
+
+ await target.unpublish()
+ await publish(target, name)
+
+ const bridgeName = username(7)
+ const bridge = new Bridge('Bridge', uuid.generate('context repeated bridge'))
+ const bridged = new Accessory('Camera', uuid.generate('context repeated bridged'))
+ const behind = recordedCamera()
+ bridged.configureController(behind.camera)
+ bridge.addBridgedAccessory(bridged)
+ await publish(bridge, bridgeName)
+ const heldBehind = heldContext(behind.camera)
+
+ await bridge.unpublish()
+ await publish(bridge, bridgeName)
+
+ expect(contexts.map(context => context.username)).toEqual([
+ undefined,
+ name,
+ name,
+ name,
+ name,
+ name,
+ ])
+ expect(heldContext(camera)).toEqual(held)
+ expect(heldContext(camera)).not.toBe(held)
+ expect(behind.contexts.map(context => context.username)).toEqual([
+ undefined,
+ undefined,
+ bridgeName,
+ bridgeName,
+ bridgeName,
+ bridgeName,
+ bridgeName,
+ ])
+ expect(heldContext(behind.camera)).toEqual(heldBehind)
+ expect(heldContext(behind.camera)).not.toBe(heldBehind)
+ expect(setItemSync.mock.calls.filter(([key]) => key.startsWith('RecordingProvisioning.'))).toEqual([])
+ expect(load).not.toHaveBeenCalled()
+ })
+
+ it('hands a standalone accessory\'s camera a context reading not published at its configure and after its first publish\'s restore, published at '
+ + 'the publish\'s end and not published at its unpublish', async () => {
+ const name = username(8)
+ const target = new Accessory('Camera', uuid.generate('context published standalone'))
+ const { camera, contexts } = recordedCamera()
+
+ target.configureController(camera)
+ await publish(target, name)
+ await target.unpublish()
+
+ expect(contexts).toEqual([
+ { accessoryUUID: target.UUID, published: false, username: undefined },
+ { accessoryUUID: target.UUID, published: false, username: name },
+ { accessoryUUID: target.UUID, published: true, username: name },
+ { accessoryUUID: target.UUID, published: false, username: name },
+ ])
+ })
+
+ it('hands a bridged camera a context reading published at its link to a published bridge, not published at its unlink and at the bridge\'s '
+ + 'unpublish, and published at the end of the bridge\'s publish', async () => {
+ const name = username(9)
+ const bridge = new Bridge('Bridge', uuid.generate('context published bridge'))
+ const target = new Accessory('Camera', uuid.generate('context published bridged'))
+ const { camera, contexts } = recordedCamera()
+
+ await publish(bridge, name)
+ target.configureController(camera)
+ bridge.addBridgedAccessory(target)
+ bridge.removeBridgedAccessory(target)
+ bridge.addBridgedAccessory(target)
+ await bridge.unpublish()
+ await publish(bridge, name)
+
+ // The configure, the link, the unlink, the link again, the bridge's unpublish, and the bridge's publish after its restore and at its end.
+ expect(contexts).toEqual([
+ { accessoryUUID: target.UUID, published: false, username: undefined },
+ { accessoryUUID: target.UUID, published: true, username: name },
+ { accessoryUUID: target.UUID, published: false, username: undefined },
+ { accessoryUUID: target.UUID, published: true, username: name },
+ { accessoryUUID: target.UUID, published: false, username: name },
+ { accessoryUUID: target.UUID, published: false, username: name },
+ { accessoryUUID: target.UUID, published: true, username: name },
+ ])
+ })
+
+ it('hands a context reading not published at a destroy to its own camera and to each bridged camera, a bridged accessory\'s own destroy among '
+ + 'them', async () => {
+ const name = username(10)
+ const bridgeName = username(11)
+ const target = new Accessory('Camera', uuid.generate('context destroyed'))
+ const bridge = new Bridge('Bridge', uuid.generate('context destroyed bridge'))
+ const bridged = new Accessory('Camera', uuid.generate('context destroyed bridged'))
+ const leaving = new Accessory('Camera', uuid.generate('context destroyed leaving'))
+ const own = recordedCamera()
+ const behind = recordedCamera()
+ const left = recordedCamera()
+ target.configureController(own.camera)
+ bridged.configureController(behind.camera)
+ leaving.configureController(left.camera)
+ bridge.addBridgedAccessory(bridged)
+ bridge.addBridgedAccessory(leaving)
+ await publish(target, name)
+ await publish(bridge, bridgeName)
+ const ownHanded = own.contexts.length
+ const behindHanded = behind.contexts.length
+ const leftHanded = left.contexts.length
+
+ await leaving.destroy()
+ const leftAtOwnDestroy = left.contexts.slice(leftHanded)
+ await target.destroy()
+ await bridge.destroy()
+
+ // A destroy unpublishes first, and then hands its own context once its data is removed, a bridged accessory's own reading its bridge's username.
+ expect(leftAtOwnDestroy).toEqual([
+ { accessoryUUID: leaving.UUID, published: false, username: bridgeName },
+ ])
+ expect(own.contexts.slice(ownHanded)).toEqual([
+ { accessoryUUID: target.UUID, published: false, username: name },
+ { accessoryUUID: target.UUID, published: false, username: undefined },
+ ])
+ expect(behind.contexts.slice(behindHanded)).toEqual([
+ { accessoryUUID: bridged.UUID, published: false, username: bridgeName },
+ { accessoryUUID: bridged.UUID, published: false, username: undefined },
+ ])
+ })
+
+ it('hands a camera being removed a context reading not published, after its untrack and before its factory reset', async () => {
+ const name = username(12)
+ const target = new Accessory('Camera', uuid.generate('context removed'))
+ const { camera, contexts } = recordedCamera()
+ target.configureController(camera)
+ await publish(target, name)
+ const untrack = vi.spyOn(ControllerStorage.prototype, 'untrackController')
+ const reset = vi.spyOn(camera, 'handleFactoryReset')
+ const handle = vi.mocked(camera.handleAccessoryContext)
+ const handed = contexts.length
+
+ target.removeController(camera)
+
+ expect(contexts.slice(handed)).toEqual([
+ { accessoryUUID: target.UUID, published: false, username: name },
+ ])
+ expect(untrack.mock.invocationCallOrder[0]).toBeLessThan(handle.mock.invocationCallOrder[handed])
+ expect(handle.mock.invocationCallOrder[handed]).toBeLessThan(reset.mock.invocationCallOrder[0])
+ })
+
+ it('replaces the context a camera holds with one differing in whether it reads published alone, its clip path loading and writing no provisioning '
+ + 'record', async () => {
+ const name = username(13)
+ const target = new Accessory('Camera', uuid.generate('context published alone'))
+ const camera = new CameraController(capabilitiesCameraOptions({
+ streaming: idleStreaming(),
+ videoSensors: [FIRST_VIDEO_SENSOR],
+ }))
+ target.configureController(camera)
+ await publish(target, name)
+ const held = heldContext(camera) as ControllerAccessoryContext
+ const load = vi.spyOn(RecordingProvisioning, 'load')
+ const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync')
+ const removeItemSync = vi.spyOn(HAPStorage.storage(), 'removeItemSync')
+ const moved = { ...held, published: !held.published }
+
+ camera.handleAccessoryContext(moved)
+
+ expect(heldContext(camera)).toBe(moved)
+ // @ts-expect-error: private access
+ expect(camera.cmafRecordingManagement.identity).toEqual({ accessoryUUID: target.UUID, username: name })
+ expect(load).not.toHaveBeenCalled()
+ expect(setItemSync.mock.calls.filter(([key]) => key.startsWith('RecordingProvisioning.'))).toEqual([])
+ expect(removeItemSync.mock.calls.filter(([key]) => key.startsWith('RecordingProvisioning.'))).toEqual([])
+ })
+
+ it('logs a controller\'s failure to take its accessory\'s context and goes on with the hand and its caller, a bridge\'s unpublish destroying its '
+ + 'advertiser and telling every later controller, and a publish, an unlink and the controller\'s own removal each running to its end', async () => {
+ const name = username(14)
+ const bridge = new Bridge('Bridge', uuid.generate('context guarded bridge'))
+ const failing = new Accessory('Failing Camera', uuid.generate('context guarded failing'))
+ const later = new Accessory('Camera', uuid.generate('context guarded later'))
+ const own = recordedCamera()
+ const after = recordedCamera()
+ const thrower = new CameraController(createCameraControllerOptions())
+ const handle = thrower.handleAccessoryContext.bind(thrower)
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ // The first line of each logged failure: the accessory's name, the sentence and the thrown error's own first line.
+ const failures = (): string[] => error.mock.calls.map(([line]) => String(line).split('\n')[0])
+ const FAILED = '[Failing Camera] A controller failed to take its accessory\'s context: Error: A listener of the plugin\'s failed.'
+ let throwing = false
+
+ // Once armed, the controller throws out of its handler, as a listener a plugin attached to a characteristic the handler writes would.
+ vi.spyOn(thrower, 'handleAccessoryContext').mockImplementation((context) => {
+ if (throwing) {
+ throw new Error('A listener of the plugin\'s failed.')
+ }
+
+ handle(context)
+ })
+
+ bridge.configureController(own.camera)
+ failing.configureController(thrower)
+ later.configureController(after.camera)
+ bridge.addBridgedAccessory(failing)
+ bridge.addBridgedAccessory(later)
+ await publish(bridge, name)
+
+ const destroy = vi.spyOn(bridge._advertiser!, 'destroy')
+ const ownHanded = own.contexts.length
+ const laterHanded = after.contexts.length
+
+ throwing = true
+
+ await expect(bridge.unpublish()).resolves.toBeUndefined()
+ expect(destroy).toHaveBeenCalledOnce()
+ expect(own.contexts.slice(ownHanded)).toEqual([
+ { accessoryUUID: bridge.UUID, published: false, username: name },
+ ])
+ expect(after.contexts.slice(laterHanded)).toEqual([
+ { accessoryUUID: later.UUID, published: false, username: name },
+ ])
+ expect(failures()).toEqual([FAILED])
+
+ error.mockClear()
+ await publish(bridge, name)
+
+ // A publish hands its context once its controller storage has restored what it holds and again at its end, and the controller fails at each.
+ expect(after.contexts.at(-1)).toEqual({ accessoryUUID: later.UUID, published: true, username: name })
+ expect(failures()).toEqual([FAILED, FAILED])
+
+ error.mockClear()
+ bridge.removeBridgedAccessory(failing)
+
+ expect(bridge.bridgedAccessories).toEqual([later])
+ expect(failures()).toEqual([FAILED])
+
+ const reset = vi.spyOn(thrower, 'handleFactoryReset')
+ const removed = vi.spyOn(thrower, 'handleControllerRemoved')
+
+ error.mockClear()
+ failing.removeController(thrower)
+
+ // The removal's own factory reset runs before handleControllerRemoved, which resets the camera again itself.
+ expect(removed).toHaveBeenCalledOnce()
+ expect(reset.mock.invocationCallOrder[0]).toBeLessThan(removed.mock.invocationCallOrder[0])
+ expect(failures()).toEqual([FAILED])
+ })
+ })
+
+ describe('the recording provisioning record', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ const CAMERA_KEY = {
+ key: Buffer.alloc(32, 0x5A),
+ keyNumber: 1n,
+ }
+ const PUBLISHING_POINT = {
+ serverCACertificates: [
+ {
+ certificate: Buffer.from('3082a1', 'hex'),
+ },
+ ],
+ url: 'https://ingest.example/v1/token/',
+ }
+
+ // A camera's entry with a hub's Camera Key and publishing point beside its marks.
+ function provisioned(name: string, accessoryUUID: string): void {
+ RecordingProvisioning.save(name, accessoryUUID, {
+ cameraKey: CAMERA_KEY,
+ clipMark: 9n,
+ publishingPoint: PUBLISHING_POINT,
+ sequenceMark: 5n,
+ })
+ }
+
+ it('clears the camera\'s entry to its marks at the last pairing\'s removal before the camera resets', () => {
+ vi.spyOn(EventedHTTPServer, 'destroyExistingConnectionsAfterUnpair').mockImplementation(() => undefined)
+ const name = username(16)
+ const target = new Accessory('Camera', uuid.generate('record unpaired'))
+ const camera = new CameraController(createCameraControllerOptions())
+ target.configureController(camera)
+ const pairings = AccessoryInfo.create(name)
+ pairings.addPairedClient(clientUsername0, clientPublicKey0, PermissionTypes.ADMIN)
+ pairings.save = vi.fn()
+ target._accessoryInfo = pairings
+ provisioned(name, target.UUID)
+ const readAtReset: unknown[] = []
+ const reset = camera.handleFactoryReset.bind(camera)
+ vi.spyOn(camera, 'handleFactoryReset').mockImplementation(() => {
+ readAtReset.push(RecordingProvisioning.load(name, target.UUID))
+ reset()
+ })
+
+ // @ts-expect-error: private access
+ target.handleRemovePairing(connection, clientUsername0, callback)
+
+ expect(callback).toHaveBeenCalledWith(0)
+ expect(readAtReset).toEqual([
+ { clipMark: 9n, sequenceMark: 5n },
+ ])
+ expect(RecordingProvisioning.load(name, target.UUID)).toStrictEqual({ clipMark: 9n, sequenceMark: 5n })
+ })
+
+ it('clears every bridged camera\'s entry to its marks at the bridge\'s last pairing\'s removal before the camera resets', async () => {
+ vi.spyOn(EventedHTTPServer, 'destroyExistingConnectionsAfterUnpair').mockImplementation(() => undefined)
+ const name = username(19)
+ const bridge = new Bridge('Bridge', uuid.generate('record unpaired bridge'))
+ const target = new Accessory('Camera', uuid.generate('record unpaired bridged'))
+ const camera = new CameraController(createCameraControllerOptions())
+ target.configureController(camera)
+ bridge.addBridgedAccessory(target)
+ await publish(bridge, name)
+ bridge._accessoryInfo!.addPairedClient(clientUsername0, clientPublicKey0, PermissionTypes.ADMIN)
+ provisioned(name, target.UUID)
+ const readAtReset: unknown[] = []
+ const reset = camera.handleFactoryReset.bind(camera)
+ vi.spyOn(camera, 'handleFactoryReset').mockImplementation(() => {
+ readAtReset.push(RecordingProvisioning.load(name, target.UUID))
+ reset()
+ })
+
+ // @ts-expect-error: private access
+ bridge.handleRemovePairing(connection, clientUsername0, callback)
+
+ expect(callback).toHaveBeenCalledWith(0)
+ expect(readAtReset).toEqual([
+ { clipMark: 9n, sequenceMark: 5n },
+ ])
+ expect(RecordingProvisioning.load(name, target.UUID)).toStrictEqual({ clipMark: 9n, sequenceMark: 5n })
+ })
+
+ it('keeps the record as stored and warns once per failed write at a bridged camera\'s removal, a first publish and the last pairing\'s removal', async () => {
+ vi.spyOn(EventedHTTPServer, 'destroyExistingConnectionsAfterUnpair').mockImplementation(() => undefined)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const removedName = username(20)
+ const removedBridge = new Bridge('Front Bridge', uuid.generate('record failed removal bridge'))
+ const removed = new Accessory('Front Camera', uuid.generate('record failed removal'))
+ const earlyName = username(21)
+ const earlyBridge = new Bridge('Back Bridge', uuid.generate('record failed early bridge'))
+ const early = new Accessory('Back Camera', uuid.generate('record failed early'))
+ const unpairedName = username(22)
+ const unpaired = new Accessory('Side Camera', uuid.generate('record failed unpaired'))
+ const pairings = AccessoryInfo.create(unpairedName)
+ const keyOnly = { cameraKey: CAMERA_KEY, publishingPoint: PUBLISHING_POINT }
+ await publish(removedBridge, removedName)
+ removedBridge.addBridgedAccessory(removed)
+ provisioned(removedName, removed.UUID)
+ provisioned(earlyName, early.UUID)
+ earlyBridge.addBridgedAccessory(early)
+ earlyBridge.removeBridgedAccessory(early)
+ pairings.addPairedClient(clientUsername0, clientPublicKey0, PermissionTypes.ADMIN)
+ pairings.save = vi.fn()
+ unpaired._accessoryInfo = pairings
+ RecordingProvisioning.save(unpairedName, unpaired.UUID, keyOnly)
+
+ // Only the record's own writes fail. The publish still stores the accessory's pairing data.
+ const storage = HAPStorage.storage()
+ const setItemSync = storage.setItemSync.bind(storage)
+ const removeItemSync = storage.removeItemSync.bind(storage)
+ const failing = (key: string): void => {
+ if (key.startsWith('RecordingProvisioning.')) {
+ throw new Error('The disk is full.')
+ }
+ }
+ vi.spyOn(storage, 'setItemSync').mockImplementation((key, value) => {
+ failing(key)
+ setItemSync(key, value)
+ })
+ vi.spyOn(storage, 'removeItemSync').mockImplementation((key) => {
+ failing(key)
+ removeItemSync(key)
+ })
+
+ expect(() => removedBridge.removeBridgedAccessory(removed)).not.toThrow()
+ await expect(publish(earlyBridge, earlyName)).resolves.toBeUndefined()
+ // @ts-expect-error: private access
+ expect(() => unpaired.handleRemovePairing(connection, clientUsername0, callback)).not.toThrow()
+
+ expect(callback).toHaveBeenCalledWith(0)
+ expect(warn.mock.calls).toEqual([
+ [`[${removedBridge.displayName}] The recording provisioning record could not be written: The disk is full.`],
+ [`[${earlyBridge.displayName}] The recording provisioning record could not be written: The disk is full.`],
+ ['[Side Camera] The recording provisioning record could not be written: The disk is full.'],
+ ])
+ expect(RecordingProvisioning.load(removedName, removed.UUID)).toStrictEqual({
+ cameraKey: CAMERA_KEY,
+ clipMark: 9n,
+ publishingPoint: PUBLISHING_POINT,
+ sequenceMark: 5n,
+ })
+ expect(RecordingProvisioning.load(earlyName, early.UUID)).toStrictEqual({
+ cameraKey: CAMERA_KEY,
+ clipMark: 9n,
+ publishingPoint: PUBLISHING_POINT,
+ sequenceMark: 5n,
+ })
+ expect(RecordingProvisioning.load(unpairedName, unpaired.UUID)).toStrictEqual(keyOnly)
+ })
+
+ it('clears a camera\'s entry to its marks when it leaves a published bridge and keeps its neighbor\'s whole', async () => {
+ const name = username(17)
+ const bridge = new Bridge('Bridge', uuid.generate('record bridge'))
+ const target = new Accessory('Camera', uuid.generate('record bridged'))
+ const neighbor = uuid.generate('record neighbor')
+ await publish(bridge, name)
+ provisioned(name, target.UUID)
+ provisioned(name, neighbor)
+ bridge.addBridgedAccessory(target)
+
+ bridge.removeBridgedAccessory(target)
+
+ expect(RecordingProvisioning.load(name, target.UUID)).toStrictEqual({ clipMark: 9n, sequenceMark: 5n })
+ expect(RecordingProvisioning.load(name, neighbor)).toStrictEqual({
+ cameraKey: CAMERA_KEY,
+ clipMark: 9n,
+ publishingPoint: PUBLISHING_POINT,
+ sequenceMark: 5n,
+ })
+ })
+
+ it('clears the entry of a camera that left a bridge before its first publish to its marks once that publish loads storage, before the camera hears it', async () => {
+ const name = username(18)
+ const bridge = new Bridge('Bridge', uuid.generate('record unpublished bridge'))
+ const target = new Accessory('Camera', uuid.generate('record removed early'))
+ const neighbor = uuid.generate('record early neighbor')
+ const camera = new CameraController(createCameraControllerOptions())
+ target.configureController(camera)
+ provisioned(name, target.UUID)
+ provisioned(name, neighbor)
+ bridge.addBridgedAccessory(target)
+ bridge.removeBridgedAccessory(target)
+
+ expect(RecordingProvisioning.load(name, target.UUID)).toStrictEqual({
+ cameraKey: CAMERA_KEY,
+ clipMark: 9n,
+ publishingPoint: PUBLISHING_POINT,
+ sequenceMark: 5n,
+ })
+
+ // The camera is added back before the publish: the publish hands it the username, which it must hear only after its entry is cleared.
+ bridge.addBridgedAccessory(target)
+ const load = vi.spyOn(bridge.controllerStorage, 'load')
+ const clearProvisioning = vi.spyOn(RecordingProvisioning, 'clearProvisioning')
+ const handleAccessoryContext = vi.spyOn(camera, 'handleAccessoryContext')
+
+ await publish(bridge, name)
+
+ const heard = handleAccessoryContext.mock.calls.findIndex(([context]) => context.username === name)
+
+ expect(handleAccessoryContext.mock.invocationCallOrder[heard]).toBeGreaterThan(clearProvisioning.mock.invocationCallOrder[0])
+
+ expect(RecordingProvisioning.load(name, target.UUID)).toStrictEqual({ clipMark: 9n, sequenceMark: 5n })
+ expect(RecordingProvisioning.load(name, neighbor)).toStrictEqual({
+ cameraKey: CAMERA_KEY,
+ clipMark: 9n,
+ publishingPoint: PUBLISHING_POINT,
+ sequenceMark: 5n,
+ })
+
+ // The accessory's clear comes first, and the camera, which starts without the capabilities block, then clears its own entry inside the context it
+ // hears, finding it cleared already and writing nothing.
+ expect(clearProvisioning.mock.calls).toEqual([
+ [name, target.UUID],
+ [name, target.UUID],
+ ])
+ expect(clearProvisioning.mock.invocationCallOrder[1]).toBeGreaterThan(handleAccessoryContext.mock.invocationCallOrder[heard])
+ expect(clearProvisioning.mock.invocationCallOrder[0]).toBeGreaterThan(load.mock.invocationCallOrder[0])
+ })
+ })
+
describe('publish', () => {
it('blocks a standalone accessory containing invalid characteristic permissions', async () => {
const service = accessory.addService(Service.Switch)
@@ -2233,6 +2897,243 @@ describe('Accessory', () => {
})
})
+ it('answers a transient write response to its write and to a read on the writing connection, and the default value to another connection', async () => {
+ onCharacteristic.setProps({
+ format: Formats.TLV8,
+ perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE],
+ transient: true,
+ })
+ onCharacteristic.onSet(() => 'AQEB')
+
+ // The write and the reads run on emitter connections, because the hold reads the writer's connection and the shared one carries none of its methods.
+ connection = buildEmitterConnection()
+ const other = buildEmitterConnection()
+
+ await testRequestResponse({
+ characteristics: [
+ {
+ aid,
+ iid: iids.on,
+ value: 'AQEC',
+ r: true,
+ },
+ ],
+ }, {
+ aid,
+ iid: iids.on,
+ status: HAPStatus.SUCCESS,
+ value: 'AQEB',
+ })
+
+ const readRequest = {
+ ids: [
+ { aid, iid: iids.on },
+ ],
+ includeMeta: false,
+ includeEvent: false,
+ includeType: false,
+ includePerms: false,
+ }
+
+ // @ts-expect-error: private access
+ accessory.handleGetCharacteristics(connection, readRequest, callback)
+
+ await callbackPromise
+
+ const writerResponse: CharacteristicsReadResponse = {
+ characteristics: [
+ { aid, iid: iids.on, value: 'AQEB' },
+ ],
+ }
+
+ expect(callback).toHaveBeenCalledTimes(1)
+ expect(callback).toHaveBeenCalledWith(undefined, writerResponse)
+
+ callback.mockReset()
+
+ // @ts-expect-error: private access
+ accessory.handleGetCharacteristics(other, readRequest, callback)
+
+ await callbackPromise
+
+ const otherResponse: CharacteristicsReadResponse = {
+ characteristics: [
+ { aid, iid: iids.on, value: '' },
+ ],
+ }
+
+ expect(callback).toHaveBeenCalledTimes(1)
+ expect(callback).toHaveBeenCalledWith(undefined, otherResponse)
+ })
+
+ /* Captures each debug line the accessory prints during a row of the describe that calls it, rendered as it would reach the log, which lets a row read the
+ * value each line carries. The hooks it registers put the debug module back after each row.
+ */
+ function captureAccessoryDebugLines(): (needle: string) => string[] {
+ let originalEnable: string
+ let originalLog: (...args: unknown[]) => unknown
+ let captured: string[]
+
+ beforeEach(() => {
+ captured = []
+ originalEnable = createDebug.disable()
+ originalLog = createDebug.log
+ createDebug.log = (...args: unknown[]) => {
+ captured.push(format(...args))
+ }
+ createDebug.enable('HAP-NodeJS:Accessory')
+ })
+
+ afterEach(() => {
+ createDebug.log = originalLog
+ createDebug.disable()
+ if (originalEnable) {
+ createDebug.enable(originalEnable)
+ }
+ })
+
+ return needle => captured.filter(line => line.includes(needle))
+ }
+
+ describe('write debug lines', () => {
+ const SECRET = 'U0VDUkVU'
+
+ // Each debug line the accessory prints during a row, which lets a row read the value each line carries.
+ const linesWith = captureAccessoryDebugLines()
+
+ // One successful write and one the handler refuses: the processing, setting and error lines each print the written value once or twice.
+ const writeSuccessThenRefusal = async (): Promise => {
+ onCharacteristic.onSet(() => {})
+
+ await testRequestResponse({
+ characteristics: [
+ { aid, iid: iids.on, value: SECRET },
+ ],
+ }, {
+ aid,
+ iid: iids.on,
+ status: HAPStatus.SUCCESS,
+ })
+
+ onCharacteristic.onSet(() => {
+ throw new HapStatusError(HAPStatus.RESOURCE_BUSY)
+ })
+
+ await testRequestResponse({
+ characteristics: [
+ { aid, iid: iids.on, value: SECRET },
+ ],
+ }, {
+ aid,
+ iid: iids.on,
+ status: HAPStatus.RESOURCE_BUSY,
+ })
+ }
+
+ it('print a marker in place of a value written to a sensitive characteristic', async () => {
+ onCharacteristic.setProps({
+ format: Formats.TLV8,
+ perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE],
+ transient: true,
+ sensitive: true,
+ })
+
+ await writeSuccessThenRefusal()
+
+ expect(linesWith('Processing characteristic set')).toEqual([
+ expect.stringContaining('"value":""'),
+ expect.stringContaining('"value":""'),
+ ])
+ expect(linesWith('Setting Characteristic')).toEqual([
+ expect.stringContaining('to value '),
+ ])
+ expect(linesWith('Error setting Characteristic')).toEqual([
+ expect.stringContaining('to value '),
+ ])
+ expect(linesWith(SECRET)).toEqual([])
+ })
+
+ it('print a TLV8 value written to a characteristic without the flag as its size, and the request with each value hidden', async () => {
+ onCharacteristic.setProps({
+ format: Formats.TLV8,
+ perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE],
+ transient: true,
+ })
+
+ await writeSuccessThenRefusal()
+
+ expect(linesWith('Processing characteristic set')).toEqual([
+ expect.stringContaining('"value":""'),
+ expect.stringContaining('"value":""'),
+ ])
+ expect(linesWith('Setting Characteristic')).toEqual([
+ expect.stringContaining('to value '),
+ ])
+ expect(linesWith('Error setting Characteristic')).toEqual([
+ expect.stringContaining('to value '),
+ ])
+ expect(linesWith('')).toEqual([])
+ expect(linesWith(SECRET)).toEqual([])
+ })
+ })
+
+ describe('read debug lines', () => {
+ const SECRET = 'U0VDUkVU'
+
+ // Each debug line the accessory prints during a row, which lets a row read the value each line carries.
+ const linesWith = captureAccessoryDebugLines()
+
+ // One read the read handler answers with the secret.
+ const readSecret = async (): Promise => {
+ onCharacteristic.onGet(() => SECRET)
+
+ // @ts-expect-error: private access
+ accessory.handleGetCharacteristics(connection, {
+ ids: [
+ { aid, iid: iids.on },
+ ],
+ includeMeta: false,
+ includeEvent: false,
+ includeType: false,
+ includePerms: false,
+ }, callback)
+
+ await callbackPromise
+ }
+
+ it('print a marker in place of a value read from a sensitive characteristic', async () => {
+ onCharacteristic.setProps({
+ format: Formats.TLV8,
+ perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE],
+ transient: true,
+ sensitive: true,
+ })
+
+ await readSecret()
+
+ expect(linesWith('Got Characteristic')).toEqual([
+ expect.stringContaining('value: ""'),
+ ])
+ expect(linesWith(SECRET)).toEqual([])
+ })
+
+ it('print a TLV8 value read from a characteristic without the flag as its size', async () => {
+ onCharacteristic.setProps({
+ format: Formats.TLV8,
+ perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE],
+ transient: true,
+ })
+
+ await readSecret()
+
+ expect(linesWith('Got Characteristic')).toEqual([
+ expect.stringContaining('value: ""'),
+ ])
+ expect(linesWith('')).toEqual([])
+ expect(linesWith(SECRET)).toEqual([])
+ })
+ })
+
it('write non-existent characteristic', async () => {
await testRequestResponse({
characteristics: [
@@ -2769,21 +3670,21 @@ describe('Accessory', () => {
accessory.configureController(cameraController)
})
- const testRequestResponse = async (partial: Partial = {}) => {
+ const testRequestResponse = async (partial: Partial = {}, requestConnection = buildEmitterConnection()) => {
// @ts-expect-error: private access
accessory.handleResource({
'resource-type': ResourceRequestType.IMAGE,
'image-width': 200,
'image-height': 200,
...partial,
- }, callback)
+ }, callback, requestConnection)
await callbackPromise
}
it('unknown resource type', () => {
// @ts-expect-error: private access
- accessory.handleResource({ 'resource-type': 'unknown' }, callback)
+ accessory.handleResource({ 'resource-type': 'unknown' }, callback, buildEmitterConnection())
expect(callback).toHaveBeenCalledWith({
httpCode: HAPHTTPCode.NOT_FOUND,
@@ -2799,7 +3700,7 @@ describe('Accessory', () => {
'resource-type': ResourceRequestType.IMAGE,
'image-width': 200,
'image-height': 200,
- }, callback)
+ }, callback, buildEmitterConnection())
expect(callback).toHaveBeenCalledWith({
httpCode: HAPHTTPCode.NOT_FOUND,
@@ -2860,6 +3761,36 @@ describe('Accessory', () => {
await testRequestResponse()
expect(callback).toHaveBeenCalledWith({ httpCode: HAPHTTPCode.MULTI_STATUS, status: HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE })
})
+
+ it('takes back the close listener and the max-listener slot a snapshot adds to a connection that stays open once it settles, answered and refused',
+ async () => {
+ const open = buildEmitterConnection()
+ const held = (): number[] => [
+ open.listenerCount(HAPConnectionEvent.CLOSED),
+ open.getMaxListeners(),
+ ]
+ const before = held()
+ const pending = testRequestResponse({}, open)
+
+ expect(held()).toEqual([before[0] + 1, before[1] + 1])
+
+ await pending
+
+ expect(callback).toHaveBeenCalledWith(undefined, MOCK_IMAGE)
+ expect(held()).toEqual(before)
+
+ callback.mockReset()
+ cameraController.recordingManagement!.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, false)
+
+ const refused = testRequestResponse({}, open)
+
+ expect(held()).toEqual([before[0] + 1, before[1] + 1])
+
+ await refused
+
+ expect(callback).toHaveBeenCalledWith({ httpCode: HAPHTTPCode.MULTI_STATUS, status: HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE })
+ expect(held()).toEqual(before)
+ })
})
describe('characteristic read/write characteristicWarning', () => {
@@ -3039,6 +3970,74 @@ describe('Accessory', () => {
})
})
+ describe('a snapshot over a paired connection', () => {
+ const clientUsername = 'CA:FE:00:00:00:05'
+
+ it('aborts the signal of a pending snapshot of a camera with the block as the connection its resource request arrived on is destroyed', async () => {
+ const clientKeyPair = tweetnacl.sign.keyPair()
+ const clientInfo = {
+ privateKey: Buffer.from(clientKeyPair.secretKey),
+ publicKey: Buffer.from(clientKeyPair.publicKey),
+ username: clientUsername,
+ }
+ const paired = AccessoryInfo.create(serverUsername)
+ const snapshot = snapshotFunction()
+
+ // @ts-expect-error: private access
+ paired.setupID = Accessory._generateSetupID()
+ paired.displayName = 'Camera'
+ paired.category = Categories.IP_CAMERA
+ paired.pincode = '031-45-154'
+ paired.save = saveMock
+ paired.addPairedClient(clientUsername, clientInfo.publicKey, PermissionTypes.ADMIN)
+ // The published accessory loads the paired record above in place of a stored one.
+ vi.spyOn(AccessoryInfo, 'load').mockReturnValue(paired)
+ snapshot.mockImplementation(async () => await deferred().promise)
+ accessory.configureController(new CameraController(capabilitiesCameraOptions({
+ snapshot,
+ streaming: idleStreaming(),
+ videoSensors: [FIRST_VIDEO_SENSOR],
+ })))
+
+ const listening: Promise<[port: number, hostname: string]> = awaitEventOnce(accessory, AccessoryEventTypes.LISTENING)
+
+ await accessory.publish({
+ advertiser: MDNSAdvertiser.BONJOUR,
+ category: Categories.IP_CAMERA,
+ pincode: paired.pincode,
+ port: 0,
+ username: serverUsername,
+ })
+
+ const [port] = await listening
+ const client = new HAPHTTPClient('127.0.0.1', port)
+
+ await client.connect()
+ client.enableEncryption(await new PairVerifyClient(client).sendPairVerify({
+ publicKey: Buffer.from(paired.signPk),
+ username: serverUsername,
+ }, clientInfo))
+
+ // The request is never answered, since its asker is gone. The row waits on the function's signal and not on the request.
+ void client.sendResourceRequest({
+ 'image-height': 360,
+ 'image-width': 640,
+ 'resource-type': ResourceRequestType.IMAGE,
+ }).catch(() => undefined)
+
+ await until(() => snapshot.mock.calls.length === 1)
+
+ const [[, signal]] = snapshot.mock.calls
+
+ expect(signal.aborted).toBe(false)
+
+ client.destroy()
+ await until(() => signal.aborted)
+
+ expect(signal.aborted).toBe(true)
+ })
+ })
+
describe('characteristicWarning', () => {
let consoleWarnSpy: MockInstance
diff --git a/src/lib/Accessory.ts b/src/lib/Accessory.ts
index 692cb481d..8d3058b54 100644
--- a/src/lib/Accessory.ts
+++ b/src/lib/Accessory.ts
@@ -26,6 +26,8 @@ import type {
ControllerIdentifier,
ControllerServiceMap,
} from './controller/Controller.js'
+import type { ControllerAccessoryContext } from './controller/index.js'
+import type { AccessoryInformation } from './definitions/index.js'
import type {
AccessoriesCallback,
AddPairingCallback,
@@ -77,12 +79,15 @@ import {
import { AccessoryInfo, PermissionTypes } from './model/AccessoryInfo.js'
import { ControllerStorage } from './model/ControllerStorage.js'
import { IdentifierCache } from './model/IdentifierCache.js'
+import { RecordingProvisioning } from './model/RecordingProvisioning.js'
import { Service, ServiceEventTypes } from './Service.js'
import { checkName } from './util/checkName.js'
import { clone } from './util/clone.js'
import { errorMessage, errorStack } from './util/errors.js'
+import { HAPConnectionEvent } from './util/eventedhttp.js'
import { HapStatusError } from './util/hapStatusError.js'
import { once } from './util/once.js'
+import { callDelegate } from './util/promise-utils.js'
import { extractHAPStatusFromError, formatOutgoingCharacteristicValue } from './util/request-util.js'
import * as uuid from './util/uuid.js'
import { toShortForm } from './util/uuid.js'
@@ -96,6 +101,8 @@ function isCharacteristicOperationContext(context: unknown): context is Characte
const hksvDebug = createDebug('HAP-NodeJS:HKSV')
const MAX_ACCESSORIES = 149 // Maximum number of bridged accessories per bridge.
const MAX_SERVICES = 100
+// The debug lines print this in place of a value written to or read from a sensitive characteristic, because users paste debug logs into public issues.
+const REDACTED_VALUE = ''
/**
* Known category values. Category is a hint to iOS clients about what "type" of Accessory this represents, for UI only.
@@ -461,6 +468,13 @@ export class Accessory extends EventEmitter {
private serializedControllers?: Record // store uninitialized controller data after an Accessory.deserialize call
private activeCameraController?: CameraController
+ /**
+ * The UUIDs of the bridged accessories removed while this accessory has no username. The first publish learns the username their recording provisioning
+ * entries are stored under and clears each entry to its marks. A removal after a destroy needs no clear, because the destroy removed that username's
+ * whole record.
+ */
+ private readonly unpublishedRemovals = new Set()
+
/**
* @private
*/
@@ -757,6 +771,7 @@ export class Accessory extends EventEmitter {
this.bridgedAccessories.push(accessory)
this.controllerStorage.linkAccessory(accessory) // init controllers of bridged accessory
+ accessory.handAccessoryContext()
if (!deferUpdate) {
this.enqueueConfigurationUpdate()
@@ -802,6 +817,18 @@ export class Accessory extends EventEmitter {
}
this.controllerStorage.unlinkAccessory(accessory)
+ accessory.handAccessoryContext()
+
+ // A camera that leaves its bridge has its recording provisioning cleared to its marks, as at an unpairing, because the service keeps its session folders
+ // and a plugin may add the same camera back. Homebridge removes the cached accessories a plugin no longer has before it publishes the bridge. A
+ // removal made before the username is known is carried out at the first publish.
+ const username = this._accessoryInfo?.username
+
+ if (username === undefined) {
+ this.unpublishedRemovals.add(accessory.UUID)
+ } else {
+ this.writeRecordingProvisioning(() => RecordingProvisioning.clearProvisioning(username, accessory.UUID))
+ }
if (!deferUpdate) {
this.enqueueConfigurationUpdate()
@@ -936,6 +963,8 @@ export class Accessory extends EventEmitter {
if (controller instanceof CameraController) { // save CameraController for Snapshot handling
this.activeCameraController = controller
}
+
+ this.handAccessoryContext()
}
/**
@@ -959,6 +988,10 @@ export class Accessory extends EventEmitter {
if (isSerializableController(controller)) {
// this will reset the state change delegate before we call handleControllerRemoved()
this.controllerStorage.untrackController(controller)
+ // The controller leaves the accessory, and it alone is handed a context reading not published, before its factory reset, through the hand's guard:
+ // a failure there is logged and the removal runs on.
+ callDelegate(() => controller.handleAccessoryContext?.(this.accessoryContext(false)),
+ `[${this.displayName}] A controller failed to take its accessory's context`)
}
if (controller.handleFactoryReset) {
@@ -984,6 +1017,52 @@ export class Accessory extends EventEmitter {
}
}
+ /* Hands each serializable controller of this accessory the accessory's context: its Accessory Information service, its UUID, the username it is
+ * published under and whether it is published, which it is while it holds a server, the username and the server read from its bridge for a bridged
+ * accessory. It runs at every controller configure, at every publish once the controller storage has restored what it holds and again at the publish's
+ * end, at the unpublish that drops the server, before its first wait, and at every link and unlink. A destroy hands it reading not published once its
+ * data is removed, and a controller being removed is handed it alone, reading not published, before its factory reset. A controller treats a context
+ * whose username, UUID and published state are unchanged as no change.
+ *
+ * Each controller's hand is guarded: a throw or a rejection is logged once as that controller's failure, and the hand goes on to the accessory's other
+ * controllers, a bridge's to every bridged accessory after it, and its caller runs to its end. A controller's handler writes characteristics, a camera's
+ * as it leaves service, and the library emits a characteristic's change event with no guard. A listener a plugin attached there can throw out of the
+ * hand, and Homebridge's shutdown calls unpublish with nothing above it to answer for a failure. A controller whose handler failed is left as far as its
+ * handler got.
+ */
+ private handAccessoryContext(published = (this.bridged ? this.bridge?._server : this._server) !== undefined): void {
+ const context = this.accessoryContext(published)
+
+ for (const { controller } of Object.values(this.controllers)) {
+ if (isSerializableController(controller)) {
+ callDelegate(() => controller.handleAccessoryContext?.(context), `[${this.displayName}] A controller failed to take its accessory's context`)
+ }
+ }
+ }
+
+ // The context a controller of this accessory is handed, its username read from its bridge for a bridged accessory.
+ private accessoryContext(published: boolean): ControllerAccessoryContext {
+ const accessoryInformation = this.getService(Service.AccessoryInformation) as AccessoryInformation
+ const username = (this.bridged ? this.bridge?._accessoryInfo : this._accessoryInfo)?.username
+
+ return {
+ accessoryInformation,
+ accessoryUUID: this.UUID,
+ published,
+ username,
+ }
+ }
+
+ // A write of the recording provisioning record that fails keeps what the store held and is logged. An unpairing, a bridged accessory's removal or a
+ // publish carries on whatever the disk does.
+ private writeRecordingProvisioning(write: () => void): void {
+ try {
+ write()
+ } catch (error) {
+ console.warn(`[${this.displayName}] The recording provisioning record could not be written: ${errorMessage(error)}`)
+ }
+ }
+
private handleAccessoryUnpairedForControllers(): void {
for (const context of Object.values(this.controllers)) {
const controller = context.controller
@@ -1395,6 +1474,20 @@ export class Accessory extends EventEmitter {
if (!this.initialized) { // controller storage is only loaded from disk the first time we publish!
this.controllerStorage.load(info.username) // initializing controller data
+
+ // Each bridged accessory removed before this first publish has its recording provisioning entry cleared to its marks here, the outcome its removal
+ // after the publish would have had.
+ for (const accessoryUUID of this.unpublishedRemovals) {
+ this.writeRecordingProvisioning(() => RecordingProvisioning.clearProvisioning(info.username, accessoryUUID))
+ }
+
+ this.unpublishedRemovals.clear()
+ }
+
+ // The accessory's controllers and every bridged accessory's learn the username they are published under, after the first publish's restore above.
+ this.handAccessoryContext()
+ for (const accessory of this.bridgedAccessories) {
+ accessory.handAccessoryContext()
}
// assign aid/iid
@@ -1402,7 +1495,8 @@ export class Accessory extends EventEmitter {
// get our accessory information in HAP format and determine if our configuration (that is, our
// Accessories/Services/Characteristics) has changed since the last time we were published. make
- // sure to omit actual values since these are not part of the "configuration".
+ // sure to omit actual values since these are not part of the "configuration", but for the types
+ // whose value states a camera's configuration, which a characteristic's representation keeps.
const config = this.internalHAPRepresentation(false)
// TODO queue this check until about 5 seconds after startup, allowing some last changes after the publish call
// without constantly incrementing the current config number
@@ -1489,12 +1583,21 @@ export class Accessory extends EventEmitter {
this._server.listen(info.port, parsed.serverAddress)
this.initialized = true
+
+ // The accessory's controllers and every bridged accessory's learn that it is published once it holds its server, in this call rather than at the
+ // server's listening event.
+ this.handAccessoryContext()
+ for (const accessory of this.bridgedAccessories) {
+ accessory.handAccessoryContext()
+ }
}
/**
* Removes this Accessory from the local network
* Accessory object will no longer be valid after invoking this method
* Trying to invoke publish() on the object will result in undefined behavior
+ *
+ * Its controllers, and those of each accessory bridged to it, hear that it is not published, and a camera ends its own streams within the call.
*/
public destroy(): Promise {
const promise = this.unpublish()
@@ -1507,11 +1610,23 @@ export class Accessory extends EventEmitter {
this.controllerStorage.cancelQueuedSave() // it would write the file again which was just removed
this.controllerStorage = new ControllerStorage(this)
}
+
+ // The controllers and every bridged accessory's learn, once the data is removed, that the accessory is not published and, unless it is bridged, is
+ // published under no username: none writes its removed data again.
+ this.handAccessoryContext(false)
+ for (const accessory of this.bridgedAccessories) {
+ accessory.handAccessoryContext(false)
+ }
this.removeAllListeners()
return promise
}
+ /**
+ * Removes this accessory from the network, closing its HAP server and ending its advertisement. Its controllers, and those of each accessory bridged to
+ * it, hear that it is not published before the call's first wait, which means a camera ends its own streams within the call's synchronous part. A controller's
+ * failure there is logged and stops nothing of the unpublish.
+ */
public async unpublish(): Promise {
this.unpublishCount++ // cancels a publish() which is still checking its advertiser
if (this.configurationChangeDebounceTimeout) {
@@ -1522,6 +1637,13 @@ export class Accessory extends EventEmitter {
if (this._server) {
this._server.destroy()
this._server = undefined
+
+ // The controllers and every bridged accessory's learn that the accessory is not published before the first wait, which means the call's synchronous part
+ // tells them.
+ this.handAccessoryContext()
+ for (const accessory of this.bridgedAccessories) {
+ accessory.handAccessoryContext()
+ }
}
if (this._advertiser) {
// noinspection JSIgnoredPromiseFromCall
@@ -1542,7 +1664,8 @@ export class Accessory extends EventEmitter {
if (this._advertiser && this._identifierCache) {
// get our accessory information in HAP format and determine if our configuration (that is, our
// Accessories/Services/Characteristics) has changed since the last time we were published. make
- // sure to omit actual values since these are not part of the "configuration".
+ // sure to omit actual values since these are not part of the "configuration", but for the types
+ // whose value states a camera's configuration, which a characteristic's representation keeps.
try {
const config = this.internalHAPRepresentation()
this.dropStaleEventRegistrations()
@@ -1671,6 +1794,11 @@ export class Accessory extends EventEmitter {
}
this.emit(AccessoryEventTypes.UNPAIRED)
+ // What the hubs provisioned on every camera stored under this username is cleared before any controller resets: each reset reads the cleared
+ // record, and every number the cameras used is kept.
+ const { username: accessoryUsername } = this._accessoryInfo
+ this.writeRecordingProvisioning(() => RecordingProvisioning.clearProvisioning(accessoryUsername))
+
this.handleAccessoryUnpairedForControllers()
for (const accessory of this.bridgedAccessories) {
accessory.handleAccessoryUnpairedForControllers()
@@ -1862,7 +1990,10 @@ export class Accessory extends EventEmitter {
return characteristic.handleGetRequest(connection).then((value) => {
value = formatOutgoingCharacteristicValue(value, characteristic.props)
- debug('[%s] Got Characteristic "%s" value: "%s"', this.displayName, characteristic.displayName, loggableValue(characteristic, value))
+ debug('[%s] Got Characteristic "%s" value: "%s"', this.displayName, characteristic.displayName,
+ characteristic.props.sensitive
+ ? REDACTED_VALUE
+ : loggableValue(characteristic, value))
const data: PartialCharacteristicReadData = {
value: value ?? null,
@@ -2023,13 +2154,16 @@ export class Accessory extends EventEmitter {
}
const accessory = this.getAccessoryByAID(data.aid)
+ const loggedValue = characteristic.props.sensitive
+ ? REDACTED_VALUE
+ : loggableValue(characteristic, data.value)
return characteristic.handleSetRequest(data.value, connection).then(async (value) => {
if (data.value && accessory?.isIdentifyCharacteristic(characteristic)) {
await accessory.handlePairedIdentify(characteristic)
}
return value
}).then((value) => {
- debug('[%s] Setting Characteristic "%s" to value %s', this.displayName, characteristic.displayName, loggableValue(characteristic, data.value))
+ debug('[%s] Setting Characteristic "%s" to value %s', this.displayName, characteristic.displayName, loggedValue)
return {
// if write response is requested and a value is provided (0, false and '' are values too), return that
value: data.r && value != null
@@ -2039,7 +2173,7 @@ export class Accessory extends EventEmitter {
status: HAPStatus.SUCCESS,
}
}, (status: HAPStatus) => {
- debug('[%s] Error setting Characteristic "%s" to value %s: ', this.displayName, characteristic.displayName, loggableValue(characteristic, data.value), HAPStatus[status])
+ debug('[%s] Error setting Characteristic "%s" to value %s: ', this.displayName, characteristic.displayName, loggedValue, HAPStatus[status])
return { status }
})
@@ -2048,7 +2182,7 @@ export class Accessory extends EventEmitter {
return { status: HAPStatus.SUCCESS }
}
- private handleResource(data: ResourceRequest, callback: ResourceRequestCallback): void {
+ private handleResource(data: ResourceRequest, callback: ResourceRequestCallback, connection: HAPConnection): void {
if (data['resource-type'] === ResourceRequestType.IMAGE) {
const aid = data.aid // aid is optionally supplied by HomeKit (for example when camera is bridged, multiple cams, etc)
@@ -2066,15 +2200,31 @@ export class Accessory extends EventEmitter {
}
if (!controller) {
- debug('[%s] received snapshot request though no camera controller was associated!')
+ debug('[%s] received snapshot request though no camera controller was associated!', this.displayName)
callback({ httpCode: HAPHTTPCode.NOT_FOUND, status: HAPStatus.RESOURCE_DOES_NOT_EXIST })
return
}
- controller.handleSnapshotRequest(data['image-height'], data['image-width'], accessory?.displayName, data.reason)
+ /* The accessory makes the snapshot's signal because the protocol layer is where a request's asker is known to be gone, and the controller runs the
+ * call: the request's connection closing aborts it, through one close listener and one more max-listener slot, each taken back as the snapshot
+ * settles, whichever way. A connection that stays open holds nothing of a settled snapshot. A legacy camera's handler is handed no signal.
+ */
+ const asker = new AbortController()
+ const listener = (): void => asker.abort()
+ const release = (): void => {
+ connection.removeListener(HAPConnectionEvent.CLOSED, listener)
+ connection.setMaxListeners(connection.getMaxListeners() - 1)
+ }
+
+ connection.setMaxListeners(connection.getMaxListeners() + 1)
+ connection.on(HAPConnectionEvent.CLOSED, listener)
+
+ controller.handleSnapshotRequest(data['image-height'], data['image-width'], accessory?.displayName, data.reason, asker.signal)
.then((buffer) => {
+ release()
callback(undefined, buffer)
}, (status: HAPStatus) => {
+ release()
callback({ httpCode: HAPHTTPCode.MULTI_STATUS, status })
})
@@ -2337,6 +2487,7 @@ export class Accessory extends EventEmitter {
IdentifierCache.remove(username)
AccessoryInfo.remove(username)
ControllerStorage.remove(username)
+ RecordingProvisioning.remove(username)
}
private static serializeServiceMap(serviceMap: ControllerServiceMap): SerializedServiceMap {
diff --git a/src/lib/Characteristic.spec.ts b/src/lib/Characteristic.spec.ts
index 9bcc96411..d18724120 100644
--- a/src/lib/Characteristic.spec.ts
+++ b/src/lib/Characteristic.spec.ts
@@ -11,6 +11,7 @@ import { Buffer } from 'node:buffer'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { buildEmitterConnection } from '../test-utils/connectionFixtures.js'
import { CharacteristicWarningType } from './Accessory.js'
import {
Access,
@@ -24,6 +25,7 @@ import {
} from './Characteristic.js'
import { SelectedRTPStreamConfiguration } from './definitions/index.js'
import { HAPStatus } from './HAPServer.js'
+import { HAPConnectionEvent } from './util/eventedhttp.js'
import { HapStatusError } from './util/hapStatusError.js'
import * as uuid from './util/uuid.js'
@@ -2913,3 +2915,405 @@ describe('Characteristic', () => {
})
})
})
+
+describe('transient characteristics', () => {
+ const WRITE_RESPONSE_PERMS = [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE]
+ let connection: HAPConnection
+
+ beforeEach(() => {
+ connection = buildEmitterConnection()
+ })
+
+ function createTransientCharacteristic(): Characteristic {
+ return createCharacteristicWithProps({
+ format: Formats.TLV8,
+ perms: WRITE_RESPONSE_PERMS,
+ transient: true,
+ })
+ }
+
+ it('keeps the flag through construction and clears it with null', () => {
+ const characteristic = createTransientCharacteristic()
+
+ expect(characteristic.props.transient).toBe(true)
+ expect(characteristic.value).toBeNull()
+
+ characteristic.setProps({ transient: null })
+
+ expect(characteristic.props.transient).toBeUndefined()
+ })
+
+ it('resolves an onSet write response without storing it or emitting a change', async () => {
+ const characteristic = createTransientCharacteristic()
+ const change = vi.fn()
+ characteristic.on(CharacteristicEventTypes.CHANGE, change)
+ characteristic.onSet(() => 'AQEB')
+
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB')
+ expect(characteristic.value).toBeNull()
+ expect(change).not.toHaveBeenCalled()
+ })
+
+ it('resolves an on(\'set\') write response without storing it or emitting a change', async () => {
+ const characteristic = createTransientCharacteristic()
+ const change = vi.fn()
+ characteristic.on(CharacteristicEventTypes.CHANGE, change)
+ characteristic.on('set', (_value, callback) => {
+ callback(undefined, 'AQEB')
+ })
+
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB')
+ expect(characteristic.value).toBeNull()
+ expect(change).not.toHaveBeenCalled()
+ })
+
+ it('stores no value and emits no change for an onSet write without a response', async () => {
+ const characteristic = createTransientCharacteristic()
+ const change = vi.fn()
+ characteristic.on(CharacteristicEventTypes.CHANGE, change)
+ characteristic.onSet(vi.fn())
+
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBeUndefined()
+ expect(characteristic.value).toBeNull()
+ expect(change).not.toHaveBeenCalled()
+ })
+
+ it('stores no value and emits no change for a write without a handler', async () => {
+ const characteristic = createTransientCharacteristic()
+ const change = vi.fn()
+ characteristic.on(CharacteristicEventTypes.CHANGE, change)
+
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBeUndefined()
+ expect(characteristic.value).toBeNull()
+ expect(change).not.toHaveBeenCalled()
+ })
+
+ it('stores no value and emits no change for an on(\'set\') write without a response', async () => {
+ const characteristic = createTransientCharacteristic()
+ const change = vi.fn()
+ characteristic.on(CharacteristicEventTypes.CHANGE, change)
+ characteristic.on('set', (_value, callback) => {
+ callback()
+ })
+
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBeUndefined()
+ expect(characteristic.value).toBeNull()
+ expect(change).not.toHaveBeenCalled()
+ })
+
+ it('reads the format\'s default value rather than a stored value when it has no read handler', async () => {
+ const characteristic = createTransientCharacteristic()
+ characteristic.value = 'AQEB'
+
+ await expect(characteristic.handleGetRequest()).resolves.toBe('')
+ })
+
+ it('resolves an onGet value without storing it or emitting a change', async () => {
+ const characteristic = createTransientCharacteristic()
+ const change = vi.fn()
+ characteristic.on(CharacteristicEventTypes.CHANGE, change)
+ characteristic.onGet(() => 'AgEA')
+
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AgEA')
+ expect(characteristic.value).toBeNull()
+ expect(change).not.toHaveBeenCalled()
+ })
+
+ it('resolves an on(\'get\') value without storing it or emitting a change', async () => {
+ const characteristic = createTransientCharacteristic()
+ const change = vi.fn()
+ characteristic.on(CharacteristicEventTypes.CHANGE, change)
+ characteristic.on(CharacteristicEventTypes.GET, (callback) => {
+ callback(undefined, 'AgEA')
+ })
+
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AgEA')
+ expect(characteristic.value).toBeNull()
+ expect(change).not.toHaveBeenCalled()
+ })
+
+ it('serves the format\'s default value from the cached representation', async () => {
+ const characteristic = createTransientCharacteristic()
+ characteristic.iid = 1
+ characteristic.value = 'AQEB'
+
+ const json = await characteristic.toHAP(connection, false)
+
+ expect(json.value).toBe('')
+ })
+
+ it('serves the format\'s default value when the read handler throws', async () => {
+ const characteristic = createTransientCharacteristic()
+ characteristic.iid = 1
+ characteristic.onGet(() => {
+ throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ })
+
+ const json = await characteristic.toHAP(connection)
+
+ expect(json.value).toBe('')
+ })
+
+ it('serializes no value and keeps the flag', () => {
+ const characteristic = createTransientCharacteristic()
+ characteristic.value = 'AQEB'
+
+ const json = Characteristic.serialize(characteristic)
+
+ expect(json.value).toBeNull()
+ expect(json.props.transient).toBe(true)
+ })
+
+ it('keeps the flag through deserialize with and without a known constructor', () => {
+ const json = Characteristic.serialize(createTransientCharacteristic())
+
+ expect(Characteristic.deserialize(json).props.transient).toBe(true)
+ expect(Characteristic.deserialize({ ...json, constructorName: 'CryptoHash', UUID: Characteristic.CryptoHash.UUID }).props.transient).toBe(true)
+ })
+
+ it('stores and serves an onSet write response without the flag', async () => {
+ const characteristic = createCharacteristicWithProps({ format: Formats.TLV8, perms: WRITE_RESPONSE_PERMS })
+ characteristic.onSet(() => 'AQEB')
+
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB')
+ expect(characteristic.value).toBe('AQEB')
+ await expect(characteristic.handleGetRequest()).resolves.toBe('AQEB')
+ })
+
+ it('stores and serves an on(\'set\') write response without the flag', async () => {
+ const characteristic = createCharacteristicWithProps({ format: Formats.TLV8, perms: WRITE_RESPONSE_PERMS })
+ characteristic.on('set', (_value, callback) => {
+ callback(undefined, 'AQEB')
+ })
+
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB')
+ expect(characteristic.value).toBe('AQEB')
+ await expect(characteristic.handleGetRequest()).resolves.toBe('AQEB')
+ })
+
+ it('restores no value from a cache that carries one, with and without a known constructor', () => {
+ const json: SerializedCharacteristic = {
+ displayName: 'Test',
+ UUID: uuid.generate('Foo'),
+ eventOnlyCharacteristic: false,
+ value: 'AQEB',
+ props: {
+ format: Formats.TLV8,
+ perms: WRITE_RESPONSE_PERMS,
+ transient: true,
+ },
+ }
+
+ expect(Characteristic.deserialize(json).value).toBeNull()
+ expect(Characteristic.deserialize({ ...json, constructorName: 'CryptoHash', UUID: Characteristic.CryptoHash.UUID }).value).toBe('')
+ })
+
+ it('holds an onSet answer for its writer, whose read answers it, while another connection and a read without one answer the default', async () => {
+ const characteristic = createTransientCharacteristic()
+ const other = buildEmitterConnection()
+ const change = vi.fn()
+ characteristic.on(CharacteristicEventTypes.CHANGE, change)
+ characteristic.onSet(() => 'AQEB')
+
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB')
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AQEB')
+ await expect(characteristic.handleGetRequest(other)).resolves.toBe('')
+ await expect(characteristic.handleGetRequest()).resolves.toBe('')
+ expect(characteristic.value).toBeNull()
+ expect(change).not.toHaveBeenCalled()
+ })
+
+ it('holds an on(\'set\') answer for its writer, whose read answers it, while another connection and a read without one answer the default', async () => {
+ const characteristic = createTransientCharacteristic()
+ const other = buildEmitterConnection()
+ const change = vi.fn()
+ characteristic.on(CharacteristicEventTypes.CHANGE, change)
+ characteristic.on('set', (_value, callback) => {
+ callback(undefined, 'AQEB')
+ })
+
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB')
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AQEB')
+ await expect(characteristic.handleGetRequest(other)).resolves.toBe('')
+ await expect(characteristic.handleGetRequest()).resolves.toBe('')
+ expect(characteristic.value).toBeNull()
+ expect(change).not.toHaveBeenCalled()
+ })
+
+ it('holds the answer of a transient characteristic without write response, resolving the write empty and warning of nothing', async () => {
+ const characteristic = createCharacteristicWithProps({
+ format: Formats.TLV8,
+ perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
+ transient: true,
+ })
+ const warning = vi.fn()
+ characteristic.on(CharacteristicEventTypes.CHARACTERISTIC_WARNING, warning)
+ characteristic.onSet(() => 'AQEB')
+
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBeUndefined()
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AQEB')
+ expect(warning).not.toHaveBeenCalled()
+ })
+
+ it('replaces a held answer at the next answered write and releases it at an answerless, a refused, an invalid and a handlerless write', async () => {
+ const characteristic = createTransientCharacteristic()
+ const handler = { answer: 'AQEB' as string | undefined, refuses: false }
+ characteristic.onSet(() => {
+ if (handler.refuses) {
+ throw new HapStatusError(HAPStatus.RESOURCE_BUSY)
+ }
+
+ return handler.answer
+ })
+
+ await characteristic.handleSetRequest('AQEC', connection)
+ handler.answer = 'AQED'
+ await characteristic.handleSetRequest('AQEC', connection)
+
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AQED')
+ expect(connection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(1)
+
+ handler.answer = undefined
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBeUndefined()
+
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('')
+
+ handler.answer = 'AQEB'
+ await characteristic.handleSetRequest('AQEC', connection)
+ handler.refuses = true
+ await expect(characteristic.handleSetRequest('AQEC', connection)).rejects.toBe(HAPStatus.RESOURCE_BUSY)
+
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('')
+
+ handler.refuses = false
+ await characteristic.handleSetRequest('AQEC', connection)
+ await expect(characteristic.handleSetRequest(1, connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST)
+
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('')
+
+ await characteristic.handleSetRequest('AQEC', connection)
+ characteristic.removeOnSet()
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBeUndefined()
+
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('')
+ expect(connection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(0)
+ })
+
+ it('releases a held answer, its close listener and its extra max-listener slot at its writer\'s close', async () => {
+ const characteristic = createTransientCharacteristic()
+ const limit = connection.getMaxListeners()
+ characteristic.onSet(() => 'AQEB')
+
+ await characteristic.handleSetRequest('AQEC', connection)
+
+ expect(connection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(1)
+ expect(connection.getMaxListeners()).toBe(limit + 1)
+
+ connection.emit(HAPConnectionEvent.CLOSED)
+
+ expect(connection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(0)
+ expect(connection.getMaxListeners()).toBe(limit)
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('')
+ })
+
+ it('holds nothing and adds no listener for a write answered after its connection closed', async () => {
+ const characteristic = createTransientCharacteristic()
+ characteristic.onSet(() => 'AQEB')
+
+ connection.emit(HAPConnectionEvent.CLOSED)
+
+ await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB')
+ expect(connection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(0)
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('')
+ })
+
+ it('serves a held answer ahead of an onGet handler, which the writer\'s read does not call and another connection\'s read does', async () => {
+ const characteristic = createTransientCharacteristic()
+ const other = buildEmitterConnection()
+ const getHandler = vi.fn(() => 'AgEA')
+ characteristic.onGet(getHandler)
+ characteristic.onSet(() => 'AQEB')
+
+ await characteristic.handleSetRequest('AQEC', connection)
+
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AQEB')
+ expect(getHandler).not.toHaveBeenCalled()
+ await expect(characteristic.handleGetRequest(other)).resolves.toBe('AgEA')
+ expect(getHandler).toHaveBeenCalledTimes(1)
+ })
+
+ it('answers the default to a read after a refused write when it has no read handler, never the status the write left', async () => {
+ const characteristic = createTransientCharacteristic()
+ characteristic.onSet(() => {
+ throw new HapStatusError(HAPStatus.RESOURCE_BUSY)
+ })
+
+ await expect(characteristic.handleSetRequest('AQEC', connection)).rejects.toBe(HAPStatus.RESOURCE_BUSY)
+
+ expect(characteristic.statusCode).toBe(HAPStatus.RESOURCE_BUSY)
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('')
+ await expect(characteristic.handleGetRequest()).resolves.toBe('')
+ })
+
+ it('releases one connection\'s answer or every connection\'s at its release entry point, and leaves a connection holding none as it was', async () => {
+ const characteristic = createTransientCharacteristic()
+ const second = buildEmitterConnection()
+ const idle = buildEmitterConnection()
+ const limit = connection.getMaxListeners()
+ const unrelated = vi.fn()
+ idle.on(HAPConnectionEvent.CLOSED, unrelated)
+ characteristic.onSet(() => 'AQEB')
+
+ createTransientCharacteristic().releaseTransientAnswers(idle)
+
+ await characteristic.handleSetRequest('AQEC', connection)
+ await characteristic.handleSetRequest('AQEC', second)
+ characteristic.releaseTransientAnswers(connection)
+
+ expect(connection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(0)
+ expect(connection.getMaxListeners()).toBe(limit)
+ await expect(characteristic.handleGetRequest(connection)).resolves.toBe('')
+ expect(second.listenerCount(HAPConnectionEvent.CLOSED)).toBe(1)
+ expect(second.getMaxListeners()).toBe(limit + 1)
+ await expect(characteristic.handleGetRequest(second)).resolves.toBe('AQEB')
+
+ characteristic.releaseTransientAnswers(idle)
+
+ expect(idle.listenerCount(HAPConnectionEvent.CLOSED)).toBe(1)
+ expect(idle.getMaxListeners()).toBe(limit)
+
+ characteristic.releaseTransientAnswers()
+
+ expect(second.listenerCount(HAPConnectionEvent.CLOSED)).toBe(0)
+ expect(second.getMaxListeners()).toBe(limit)
+ await expect(characteristic.handleGetRequest(second)).resolves.toBe('')
+ })
+})
+
+describe('sensitive characteristics', () => {
+ function createSensitiveCharacteristic(): Characteristic {
+ return createCharacteristicWithProps({
+ format: Formats.TLV8,
+ perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE],
+ sensitive: true,
+ })
+ }
+
+ it('keeps the flag through construction and clears it with null', () => {
+ const characteristic = createSensitiveCharacteristic()
+
+ expect(characteristic.props.sensitive).toBe(true)
+
+ characteristic.setProps({ sensitive: null })
+
+ expect(characteristic.props.sensitive).toBeUndefined()
+ })
+
+ it('keeps the flag through serialize and deserialize with and without a known constructor', () => {
+ const json = Characteristic.serialize(createSensitiveCharacteristic())
+
+ expect(json.props.sensitive).toBe(true)
+ expect(Characteristic.deserialize(json).props.sensitive).toBe(true)
+ expect(Characteristic.deserialize({ ...json, constructorName: 'CryptoHash' }).props.sensitive).toBe(true)
+ })
+})
diff --git a/src/lib/Characteristic.ts b/src/lib/Characteristic.ts
index 25797d2ad..7e1250506 100644
--- a/src/lib/Characteristic.ts
+++ b/src/lib/Characteristic.ts
@@ -18,8 +18,20 @@ import type {
AudioFeedback,
BatteryLevel,
Brightness,
+ BufferActivityCommand,
+ BufferEventCommand,
+ BufferEventSequenceNumber,
+ BufferUploadCommand,
ButtonEvent,
+ CameraCapabilitiesData,
+ CameraClientCertificate,
+ CameraClientCertificateStatus,
+ CameraClientCSR,
+ CameraKey,
+ CameraKeyID,
CameraOperatingModeIndicator,
+ CameraRecordingPublishingPoint,
+ CameraZones,
CarbonDioxideDetected,
CarbonDioxideLevel,
CarbonDioxidePeakLevel,
@@ -37,6 +49,7 @@ import type {
ConfiguredName,
ConnectionHealthMonitor,
ContactSensorState,
+ ContributingSensors,
CoolingThresholdTemperature,
CryptoHash,
CurrentAirPurifierState,
@@ -108,6 +121,7 @@ import type {
MetricsBufferFullState,
Model,
MotionDetected,
+ MotionEnabled,
MultifunctionButton,
Mute,
Name,
@@ -156,6 +170,7 @@ import type {
RotationDirection,
RotationSpeed,
RouterStatus,
+ RTPStreamingControl,
Saturation,
SecuritySystemAlarmType,
SecuritySystemCurrentState,
@@ -166,6 +181,7 @@ import type {
SelectedRTPStreamConfiguration,
SelectedSessionKeepaliveConfigurationList,
SelectedSleepConfiguration,
+ SensorUUID,
SerialNumber,
ServiceLabelIndex,
ServiceLabelNamespace,
@@ -193,11 +209,13 @@ import type {
StatusJammed,
StatusLowBattery,
StatusTampered,
+ StreamingEnabled,
StreamingStatus,
SulphurDioxideDensity,
SupportedAssetTypes,
SupportedAudioRecordingConfiguration,
SupportedAudioStreamConfiguration,
+ SupportedAudioStreamTiers,
SupportedCameraRecordingConfiguration,
SupportedCharacteristicValueTransitionConfiguration,
SupportedDataStreamTransportConfiguration,
@@ -212,6 +230,7 @@ import type {
SupportedTransferTransportConfiguration,
SupportedVideoRecordingConfiguration,
SupportedVideoStreamConfiguration,
+ SupportedVideoStreamTiers,
SwingMode,
TapType,
TargetAirPurifierState,
@@ -255,6 +274,14 @@ import type {
WANConfigurationList,
WANStatusList,
WaterLevel,
+ WebRTCNumberOfActiveSessions,
+ WebRTCProvideAnswer,
+ WebRTCReoffer,
+ WebRTCSolicitOffer,
+ WebRTCStreamingControl,
+ WebRTCSupportedAudioStreamTiers,
+ WebRTCSupportedVideoStreamTiers,
+ WebRTCUpdateSession,
WiFiCapabilities,
WiFiConfigurationControl,
WiFiSatelliteStatus,
@@ -272,6 +299,7 @@ import { CharacteristicWarningType } from './Accessory.js'
import { HAPStatus } from './HAPServer.js'
import { clone } from './util/clone.js'
import { errorMessage, errorStack } from './util/errors.js'
+import { HAPConnectionEvent } from './util/eventedhttp.js'
import { HapStatusError } from './util/hapStatusError.js'
import { once } from './util/once.js'
import {
@@ -284,6 +312,7 @@ import {
numericUpperBound,
} from './util/request-util.js'
import { BASE_UUID, toShortForm } from './util/uuid.js'
+import { lendGuardInstall } from './util/valueGuard.js'
const debug = createDebug('HAP-NodeJS:Characteristic')
@@ -457,6 +486,22 @@ export interface CharacteristicProps {
*/
validValueRanges?: [min: number, max: number]
adminOnlyAccess?: Access[]
+ /**
+ * Marks a control point whose values are transient: a value a HAP request carries never lingers in {@link Characteristic.value}, and it cannot
+ * reach another controller. The value the set handler returns for a write, Write Response or not, is held for the connection that wrote it and
+ * answers that connection's plain reads ahead of any read handler, until the connection's next write of the characteristic, a write that is refused
+ * or answers nothing, the connection's close, or the release the owning class calls when a session or the service ends. Every other read returns
+ * what the read handler supplies, or the format's default value when there is none, and never a status a write left. A write response reaches only
+ * the write that produced it. A write leaves the value unchanged and emits no change event. A serialized characteristic neither carries a value
+ * nor takes one back from the cache.
+ */
+ transient?: boolean
+ /**
+ * Marks a characteristic whose values carry secret material, such as a key: the accessory's debug lines print `` in place of a value
+ * written to it or read from it. The flag governs logging alone: a control point that must also keep the value out of
+ * {@link Characteristic.value} and the cache sets {@link CharacteristicProps.transient} beside it.
+ */
+ sensitive?: boolean
}
/**
@@ -732,6 +777,26 @@ function minWithUndefined(a?: number, b?: number): number | undefined {
}
}
+// The answer a transient characteristic holds for one connection: the value its last answered write returned, which a later answer replaces, and the
+// close listener that releases it. The connection's close drops the answer with the connection.
+interface TransientAnswer {
+ value: CharacteristicValue
+ readonly listener: () => void
+}
+
+/* The types whose value states a camera's configuration, which the hashed representation writes where it writes `null` for every other value: a hub
+ * learns a camera's capabilities and its stream tiers from these values alone. A change to one must raise the configuration number as a change to a
+ * service does. Each is named by its class on `Characteristic` and read at the call, since the generated definitions attach the classes after this module
+ * loads, and the names are held to the class's own: a misspelled one fails the compile.
+ */
+const CONFIGURATION_VALUE_TYPES = [
+ 'CameraCapabilitiesData',
+ 'SupportedVideoStreamTiers',
+ 'SupportedAudioStreamTiers',
+ 'WebRTCSupportedVideoStreamTiers',
+ 'WebRTCSupportedAudioStreamTiers',
+] as const satisfies readonly (keyof typeof Characteristic)[]
+
/**
* Characteristic represents a particular typed variable that can be assigned to a Service. For instance, a
* "Hue" Characteristic might store a 'float' value of type 'arcdegrees'. You could add the Hue Characteristic
@@ -819,14 +884,62 @@ export class Characteristic extends EventEmitter {
* @group Characteristic Definitions
*/
public static Brightness: typeof Brightness
+ /**
+ * @group Characteristic Definitions
+ */
+ public static BufferActivityCommand: typeof BufferActivityCommand
+ /**
+ * @group Characteristic Definitions
+ */
+ public static BufferEventCommand: typeof BufferEventCommand
+ /**
+ * @group Characteristic Definitions
+ */
+ public static BufferEventSequenceNumber: typeof BufferEventSequenceNumber
+ /**
+ * @group Characteristic Definitions
+ */
+ public static BufferUploadCommand: typeof BufferUploadCommand
/**
* @group Characteristic Definitions
*/
public static ButtonEvent: typeof ButtonEvent
+ /**
+ * @group Characteristic Definitions
+ */
+ public static CameraCapabilitiesData: typeof CameraCapabilitiesData
+ /**
+ * @group Characteristic Definitions
+ */
+ public static CameraClientCertificate: typeof CameraClientCertificate
+ /**
+ * @group Characteristic Definitions
+ */
+ public static CameraClientCertificateStatus: typeof CameraClientCertificateStatus
+ /**
+ * @group Characteristic Definitions
+ */
+ public static CameraClientCSR: typeof CameraClientCSR
+ /**
+ * @group Characteristic Definitions
+ */
+ public static CameraKey: typeof CameraKey
+ /**
+ * @group Characteristic Definitions
+ */
+ public static CameraKeyID: typeof CameraKeyID
/**
* @group Characteristic Definitions
*/
public static CameraOperatingModeIndicator: typeof CameraOperatingModeIndicator
+ /**
+ * @group Characteristic Definitions
+ */
+ public static CameraRecordingPublishingPoint: typeof CameraRecordingPublishingPoint
+ /**
+ * @group Characteristic Definitions
+ */
+ public static CameraZones: typeof CameraZones
/**
* @group Characteristic Definitions
*/
@@ -895,6 +1008,10 @@ export class Characteristic extends EventEmitter {
* @group Characteristic Definitions
*/
public static ContactSensorState: typeof ContactSensorState
+ /**
+ * @group Characteristic Definitions
+ */
+ public static ContributingSensors: typeof ContributingSensors
/**
* @group Characteristic Definitions
*/
@@ -1179,6 +1296,10 @@ export class Characteristic extends EventEmitter {
* @group Characteristic Definitions
*/
public static MotionDetected: typeof MotionDetected
+ /**
+ * @group Characteristic Definitions
+ */
+ public static MotionEnabled: typeof MotionEnabled
/**
* @group Characteristic Definitions
*/
@@ -1374,6 +1495,10 @@ export class Characteristic extends EventEmitter {
* @group Characteristic Definitions
*/
public static RouterStatus: typeof RouterStatus
+ /**
+ * @group Characteristic Definitions
+ */
+ public static RTPStreamingControl: typeof RTPStreamingControl
/**
* @group Characteristic Definitions
*/
@@ -1414,6 +1539,10 @@ export class Characteristic extends EventEmitter {
* @group Characteristic Definitions
*/
public static SelectedSleepConfiguration: typeof SelectedSleepConfiguration
+ /**
+ * @group Characteristic Definitions
+ */
+ public static SensorUUID: typeof SensorUUID
/**
* @group Characteristic Definitions
*/
@@ -1522,6 +1651,10 @@ export class Characteristic extends EventEmitter {
* @group Characteristic Definitions
*/
public static StatusTampered: typeof StatusTampered
+ /**
+ * @group Characteristic Definitions
+ */
+ public static StreamingEnabled: typeof StreamingEnabled
/**
* @group Characteristic Definitions
*/
@@ -1542,6 +1675,10 @@ export class Characteristic extends EventEmitter {
* @group Characteristic Definitions
*/
public static SupportedAudioStreamConfiguration: typeof SupportedAudioStreamConfiguration
+ /**
+ * @group Characteristic Definitions
+ */
+ public static SupportedAudioStreamTiers: typeof SupportedAudioStreamTiers
/**
* @group Characteristic Definitions
*/
@@ -1598,6 +1735,10 @@ export class Characteristic extends EventEmitter {
* @group Characteristic Definitions
*/
public static SupportedVideoStreamConfiguration: typeof SupportedVideoStreamConfiguration
+ /**
+ * @group Characteristic Definitions
+ */
+ public static SupportedVideoStreamTiers: typeof SupportedVideoStreamTiers
/**
* @group Characteristic Definitions
*/
@@ -1776,6 +1917,38 @@ export class Characteristic extends EventEmitter {
* @group Characteristic Definitions
*/
public static WaterLevel: typeof WaterLevel
+ /**
+ * @group Characteristic Definitions
+ */
+ public static WebRTCNumberOfActiveSessions: typeof WebRTCNumberOfActiveSessions
+ /**
+ * @group Characteristic Definitions
+ */
+ public static WebRTCProvideAnswer: typeof WebRTCProvideAnswer
+ /**
+ * @group Characteristic Definitions
+ */
+ public static WebRTCReoffer: typeof WebRTCReoffer
+ /**
+ * @group Characteristic Definitions
+ */
+ public static WebRTCSolicitOffer: typeof WebRTCSolicitOffer
+ /**
+ * @group Characteristic Definitions
+ */
+ public static WebRTCStreamingControl: typeof WebRTCStreamingControl
+ /**
+ * @group Characteristic Definitions
+ */
+ public static WebRTCSupportedAudioStreamTiers: typeof WebRTCSupportedAudioStreamTiers
+ /**
+ * @group Characteristic Definitions
+ */
+ public static WebRTCSupportedVideoStreamTiers: typeof WebRTCSupportedVideoStreamTiers
+ /**
+ * @group Characteristic Definitions
+ */
+ public static WebRTCUpdateSession: typeof WebRTCUpdateSession
/**
* @group Characteristic Definitions
*/
@@ -1790,6 +1963,25 @@ export class Characteristic extends EventEmitter {
public static WiFiSatelliteStatus: typeof WiFiSatelliteStatus
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ /* The class lends the one way to give a single characteristic a clean-up step of its own, which the library's guards install. Every path that stores
+ * or answers a value a plugin supplies runs the class's step first, through the characteristic itself, which means that characteristic alone runs anything more:
+ * its own step runs the class's and answers the guard's value for the result, and its disposal deletes it. The class's step shows again. An
+ * accessory listing that asks no read handler answers the held value as stored, with no step.
+ */
+ static {
+ lendGuardInstall((characteristic, guard) => {
+ const clean = characteristic.validateUserInput.bind(characteristic)
+
+ characteristic.validateUserInput = (value, warningType) => guard(clean(value, warningType))
+
+ return {
+ [Symbol.dispose]: () => {
+ Reflect.deleteProperty(characteristic, 'validateUserInput')
+ },
+ }
+ })
+ }
+
// NOTICE: when adding/changing properties, remember to possibly adjust the serialize/deserialize functions
public displayName: string
public UUID: string
@@ -1812,6 +2004,9 @@ export class Characteristic extends EventEmitter {
private setHandler?: CharacteristicSetHandler
private subscriptions = 0
+ // The answers a transient characteristic holds, by the connection that wrote each. The map is created with the first answer: a characteristic no
+ // connection ever answered, which is nearly every one on a large bridge, allocates none.
+ private transientAnswers?: Map
/**
* @private
*/
@@ -2087,6 +2282,12 @@ export class Characteristic extends EventEmitter {
if (props.adminOnlyAccess !== undefined) {
this.props.adminOnlyAccess = props.adminOnlyAccess ?? undefined
}
+ if (props.transient !== undefined) {
+ this.props.transient = props.transient ?? undefined
+ }
+ if (props.sensitive !== undefined) {
+ this.props.sensitive = props.sensitive ?? undefined
+ }
if (this.props.minValue != null && this.props.maxValue != null) { // the eqeq instead of eqeqeq is important here
if (this.props.minValue > this.props.maxValue) { // see https://github.com/homebridge/HAP-NodeJS/issues/690
@@ -2408,6 +2609,17 @@ export class Characteristic extends EventEmitter {
throw HAPStatus.WRITE_ONLY_CHARACTERISTIC
}
+ // A transient characteristic answers its writer's plain read with the answer that writer holds, ahead of any read handler, because a plain read is the
+ // only way an answer reaches a writer whose request asked for no write response.
+ const held = this.props.transient && connection
+ ? this.transientAnswers?.get(connection)
+ : undefined
+
+ if (held) {
+ this.statusCode = HAPStatus.SUCCESS
+ return held.value
+ }
+
if (this.UUID === Characteristic.ProgrammableSwitchEvent.UUID) {
// special workaround for event only programmable switch event, which must always return null
return null
@@ -2431,6 +2643,10 @@ export class Characteristic extends EventEmitter {
return Promise.reject(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
}
+ if (this.props.transient) {
+ return value
+ }
+
const oldValue = this.value
this.value = value
@@ -2464,6 +2680,11 @@ export class Characteristic extends EventEmitter {
}
if (this.listenerCount(CharacteristicEventTypes.GET) === 0) {
+ // A transient characteristic answers the default ahead of the status check: a status a refused write left never answers a read.
+ if (this.props.transient) {
+ return this.getDefaultValue()
+ }
+
if (this.statusCode) {
throw this.statusCode
}
@@ -2506,6 +2727,12 @@ export class Characteristic extends EventEmitter {
reject(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
return
}
+
+ if (this.props.transient) {
+ resolve(value)
+ return
+ }
+
const oldValue = this.value
this.value = value
@@ -2552,6 +2779,7 @@ export class Characteristic extends EventEmitter {
value = this.validateClientSuppliedValue(value)
} catch (e) {
debug(`[${this.displayName}]`, errorMessage(e))
+ this.answerTransientWrite(connection)
return Promise.reject(HAPStatus.INVALID_VALUE_IN_REQUEST)
}
}
@@ -2571,13 +2799,26 @@ export class Characteristic extends EventEmitter {
this.statusCode = HAPStatus.SUCCESS
if (writeResponse != null && this.props.perms.includes(Perms.WRITE_RESPONSE)) {
- this.value = this.validateUserInput(writeResponse)
- return this.value!
+ const response = this.validateUserInput(writeResponse)
+
+ if (this.props.transient) {
+ this.answerTransientWrite(connection, response)
+ } else {
+ this.value = response
+ }
+
+ return response!
} else {
+ if (this.props.transient) {
+ this.answerWithoutWriteResponse(connection, writeResponse)
+ return
+ }
+
if (writeResponse != null) {
this.characteristicWarning('SET handler returned write response value, though the characteristic doesn\'t support write response',
CharacteristicWarningType.DEBUG_MESSAGE)
}
+
this.value = value
this.emit(
@@ -2593,6 +2834,8 @@ export class Characteristic extends EventEmitter {
return
}
} catch (error) {
+ this.answerTransientWrite(connection)
+
if (typeof error === 'number') {
const hapStatusError = new HapStatusError(error)
this.statusCode = hapStatusError.hapStatus
@@ -2608,6 +2851,11 @@ export class Characteristic extends EventEmitter {
}
if (this.listenerCount(CharacteristicEventTypes.SET) === 0) {
+ if (this.props.transient) {
+ this.answerTransientWrite(connection)
+ return Promise.resolve()
+ }
+
this.value = value
this.emit(CharacteristicEventTypes.CHANGE, {
originator: connection,
@@ -2622,6 +2870,8 @@ export class Characteristic extends EventEmitter {
try {
this.emit(CharacteristicEventTypes.SET, value, once((status, writeResponse) => {
if (status) {
+ this.answerTransientWrite(connection)
+
if (typeof status === 'number') {
const hapStatusError = new HapStatusError(status)
this.statusCode = hapStatusError.hapStatus
@@ -2639,22 +2889,38 @@ export class Characteristic extends EventEmitter {
if (writeResponse != null && this.props.perms.includes(Perms.WRITE_RESPONSE)) {
// support write response simply by letting the implementor pass the response as second argument to the callback
+ let response: Nullable
try {
- this.value = this.validateUserInput(writeResponse)
+ response = this.validateUserInput(writeResponse)
} catch (error) {
// this runs inside the plugin's callback; a throw would land in the plugin and leave the request unanswered
this.characteristicWarning(`An illegal write response value was supplied by the write handler for characteristic: ${errorMessage(error)}`,
CharacteristicWarningType.WARN_MESSAGE, errorStack(error))
this.statusCode = HAPStatus.SERVICE_COMMUNICATION_FAILURE
+ this.answerTransientWrite(connection)
reject(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
return
}
- resolve(this.value!)
+
+ if (this.props.transient) {
+ this.answerTransientWrite(connection, response)
+ } else {
+ this.value = response
+ }
+
+ resolve(response!)
} else {
+ if (this.props.transient) {
+ this.answerWithoutWriteResponse(connection, writeResponse)
+ resolve()
+ return
+ }
+
if (writeResponse != null) {
this.characteristicWarning('SET handler returned write response value, though the characteristic doesn\'t support write response',
CharacteristicWarningType.DEBUG_MESSAGE)
}
+
this.value = value
resolve()
@@ -2674,12 +2940,103 @@ export class Characteristic extends EventEmitter {
this.characteristicWarning(`Unhandled error thrown inside write handler for characteristic: ${errorMessage(error)}`,
CharacteristicWarningType.ERROR_MESSAGE, errorStack(error))
this.statusCode = HAPStatus.SERVICE_COMMUNICATION_FAILURE
+ this.answerTransientWrite(connection)
reject(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
}
})
}
}
+ /**
+ * Releases the answers a transient characteristic holds for its writers: one connection's, its close listener and its extra max-listener slot with it,
+ * or every connection's when none is given. A connection that holds no answer is left as it was, its listeners and its max listeners untouched. The
+ * owning classes call this at each boundary that ends or bounds an answer, a session's end or the service's reset among them, and the connection's close
+ * and its refused or answerless writes reach it as well.
+ * @param connection - The connection whose answer goes, or `undefined` for every connection's.
+ * @private
+ */
+ releaseTransientAnswers(connection?: HAPConnection): void {
+ const answers = this.transientAnswers
+
+ if (!answers) {
+ return
+ }
+
+ // The writers are read into an array first, which is why the loop deletes from a map it is not walking.
+ const writers = connection
+ ? [connection]
+ : Array.from(answers.keys())
+
+ for (const writer of writers) {
+ const answer = answers.get(writer)
+
+ if (answer) {
+ answers.delete(writer)
+ writer.removeListener(HAPConnectionEvent.CLOSED, answer.listener)
+ writer.setMaxListeners(writer.getMaxListeners() - 1)
+ }
+ }
+ }
+
+ /* Settles a transient write's answer for its writer: an answer holds, replacing the one the connection held, and a write that is refused or answers
+ * nothing releases it. A write without a connection, which a plugin makes, and a write to a characteristic that is not transient touch nothing.
+ */
+ private answerTransientWrite(connection: HAPConnection | undefined, answer?: Nullable): void {
+ if (!this.props.transient || connection === undefined) {
+ return
+ }
+
+ if (answer == null) {
+ this.releaseTransientAnswers(connection)
+ return
+ }
+
+ // A connection that no longer reads as authenticated is closing or closed, and a closed one would never release an answer, because its close
+ // listeners have run and been removed: it holds nothing.
+ if (!connection.isAuthenticated()) {
+ this.releaseTransientAnswers(connection)
+ return
+ }
+
+ this.transientAnswers ??= new Map()
+
+ const held = this.transientAnswers.get(connection)
+
+ if (held) {
+ held.value = answer
+ return
+ }
+
+ // The first answer a connection holds adds one close listener and one max-listener slot, as ConnectionSessions does, and its release removes both.
+ const listener = (): void => this.releaseTransientAnswers(connection)
+ this.transientAnswers.set(connection, { listener, value: answer })
+ connection.setMaxListeners(connection.getMaxListeners() + 1)
+ connection.on(HAPConnectionEvent.CLOSED, listener)
+ }
+
+ /* A transient write's handler that returns an answer without the Write Response permission, Setup Endpoints' case, holds it once it validates as a write
+ * response would, because a plain read is the only way it reaches its writer. One that fails validation holds nothing and logs the warning any handler
+ * returning a response without the permission logs, and its author still hears of it.
+ */
+ private answerWithoutWriteResponse(connection: HAPConnection | undefined, writeResponse: Nullable | void): void {
+ if (writeResponse == null) {
+ this.answerTransientWrite(connection)
+ return
+ }
+
+ let answer: Nullable
+ try {
+ answer = this.validateUserInput(writeResponse)
+ } catch {
+ this.characteristicWarning('SET handler returned write response value, though the characteristic doesn\'t support write response',
+ CharacteristicWarningType.DEBUG_MESSAGE)
+ this.answerTransientWrite(connection)
+ return
+ }
+
+ this.answerTransientWrite(connection, answer)
+ }
+
/**
* Called once a HomeKit controller subscribes to events of this characteristic.
* @private
@@ -3161,7 +3518,9 @@ export class Characteristic extends EventEmitter {
debug('[%s] Error getting value for characteristic on /accessories request. Returning default value instead: %s', this.displayName, `${value}`)
return value // use default value
})
- : this.value
+ : this.props.transient
+ ? this.getDefaultValue()
+ : this.value
object.value = formatOutgoingCharacteristicValue(value, this.props)
}
@@ -3170,16 +3529,19 @@ export class Characteristic extends EventEmitter {
}
/**
- * Returns a JSON representation of this characteristic without the value.
+ * Returns the JSON representation of this characteristic the configuration number is hashed from: its value is `null`, but for a type whose value
+ * states a camera's configuration, `CONFIGURATION_VALUE_TYPES`, whose value it holds. A change to that value raises the number.
* @private
*/
internalHAPRepresentation(): CharacteristicJsonObject {
assert(this.iid, `iid cannot be undefined for characteristic '${this.displayName}'`)
- // TODO include the value for characteristics of the AccessoryInformation service
+ // TODO the values of the AccessoryInformation service's characteristics state the accessory's configuration too, and could join the list.
return {
'type': toShortForm(this.UUID),
'iid': this.iid,
- 'value': null,
+ 'value': CONFIGURATION_VALUE_TYPES.some(name => Characteristic[name].UUID === this.UUID)
+ ? this.value
+ : null,
'perms': this.props.perms,
'description': this.props.description || this.displayName,
'format': this.props.format,
@@ -3211,7 +3573,7 @@ export class Characteristic extends EventEmitter {
UUID: characteristic.UUID,
eventOnlyCharacteristic: characteristic.UUID === Characteristic.ProgrammableSwitchEvent.UUID, // support downgrades for now
constructorName,
- value: characteristic.value,
+ value: characteristic.props.transient ? null : characteristic.value,
props: clone({}, characteristic.props),
}
}
@@ -3239,7 +3601,10 @@ export class Characteristic extends EventEmitter {
characteristic = new Characteristic(json.displayName, json.UUID, json.props)
}
- characteristic.value = json.value
+ // A transient characteristic takes no value from the cache, which can predate its flag and hold a value a HAP request carried.
+ if (!characteristic.props.transient) {
+ characteristic.value = json.value
+ }
return characteristic
}
diff --git a/src/lib/HAPServer.spec.ts b/src/lib/HAPServer.spec.ts
index 4c86fba9b..41814d131 100644
--- a/src/lib/HAPServer.spec.ts
+++ b/src/lib/HAPServer.spec.ts
@@ -1524,13 +1524,26 @@ describe('HAPServer', () => {
'resource-type': ResourceRequestType.IMAGE,
}
- server.on(HAPServerEventTypes.REQUEST_RESOURCE, (resource, callback) => {
+ const connections: HAPConnection[] = []
+
+ server.on(HAPServerEventTypes.ACCESSORIES, (connection, callback) => {
+ connections.push(connection)
+ callback(undefined, { accessories: [] })
+ })
+ server.on(HAPServerEventTypes.REQUEST_RESOURCE, (resource, callback, connection) => {
expect(resource).toEqual(request)
+ connections.push(connection)
callback(undefined, image)
})
+ await client.sendAccessoriesRequest()
+
const result = await client.sendResourceRequest(request)
expect(result).toEqual(image)
+
+ // The listener is handed the connection the request arrived on, the one the client's earlier request reached.
+ expect(connections).toHaveLength(2)
+ expect(connections[1]).toBe(connections[0])
})
})
diff --git a/src/lib/HAPServer.ts b/src/lib/HAPServer.ts
index 44c4e0901..91cbbccc7 100644
--- a/src/lib/HAPServer.ts
+++ b/src/lib/HAPServer.ts
@@ -288,7 +288,7 @@ export declare interface HAPServer {
event: 'set-characteristics',
listener: (connection: HAPConnection, request: CharacteristicsWriteRequest, callback: WriteCharacteristicsCallback) => void
): this
- on(event: 'request-resource', listener: (resource: ResourceRequest, callback: ResourceRequestCallback) => void): this
+ on(event: 'request-resource', listener: (resource: ResourceRequest, callback: ResourceRequestCallback, connection: HAPConnection) => void): this
on(event: 'connection-closed', listener: (connection: HAPConnection) => void): this
@@ -310,7 +310,7 @@ export declare interface HAPServer {
emit(event: 'accessories', connection: HAPConnection, callback: AccessoriesCallback): boolean
emit(event: 'get-characteristics', connection: HAPConnection, request: CharacteristicsReadRequest, callback: ReadCharacteristicsCallback): boolean
emit(event: 'set-characteristics', connection: HAPConnection, request: CharacteristicsWriteRequest, callback: WriteCharacteristicsCallback): boolean
- emit(event: 'request-resource', resource: ResourceRequest, callback: ResourceRequestCallback): boolean
+ emit(event: 'request-resource', resource: ResourceRequest, callback: ResourceRequestCallback, connection: HAPConnection): boolean
emit(event: 'connection-closed', connection: HAPConnection): boolean
}
@@ -1272,7 +1272,7 @@ export class HAPServer extends EventEmitter {
response.writeHead(HAPHTTPCode.OK, { 'Content-Type': HAPMimeTypes.IMAGE_JPEG })
response.end(resource)
}
- }))
+ }), connection)
} else {
response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON }) // method not allowed
response.end(JSON.stringify({ status: HAPStatus.INVALID_VALUE_IN_REQUEST }))
diff --git a/src/lib/Service.ts b/src/lib/Service.ts
index ce15f668f..5efe3ecc0 100644
--- a/src/lib/Service.ts
+++ b/src/lib/Service.ts
@@ -14,9 +14,17 @@ import type {
Assistant,
AudioStreamManagement,
Battery,
+ CameraBufferManagement,
+ CameraCapabilities,
+ CameraClientCertificateManagement,
+ CameraGlobalOperatingMode,
+ CameraKeyManagement,
+ CameraMotionZones,
+ CameraMultiTierRTPStreamManagement,
CameraOperatingMode,
CameraRecordingManagement,
CameraRTPStreamManagement,
+ CameraWebRTCStreamManagement,
CarbonDioxideSensor,
CarbonMonoxideSensor,
CloudRelay,
@@ -218,6 +226,34 @@ export class Service extends EventEmitter {
* @group Service Definitions
*/
public static Battery: typeof Battery
+ /**
+ * @group Service Definitions
+ */
+ public static CameraBufferManagement: typeof CameraBufferManagement
+ /**
+ * @group Service Definitions
+ */
+ public static CameraCapabilities: typeof CameraCapabilities
+ /**
+ * @group Service Definitions
+ */
+ public static CameraClientCertificateManagement: typeof CameraClientCertificateManagement
+ /**
+ * @group Service Definitions
+ */
+ public static CameraGlobalOperatingMode: typeof CameraGlobalOperatingMode
+ /**
+ * @group Service Definitions
+ */
+ public static CameraKeyManagement: typeof CameraKeyManagement
+ /**
+ * @group Service Definitions
+ */
+ public static CameraMotionZones: typeof CameraMotionZones
+ /**
+ * @group Service Definitions
+ */
+ public static CameraMultiTierRTPStreamManagement: typeof CameraMultiTierRTPStreamManagement
/**
* @group Service Definitions
*/
@@ -230,6 +266,10 @@ export class Service extends EventEmitter {
* @group Service Definitions
*/
public static CameraRTPStreamManagement: typeof CameraRTPStreamManagement
+ /**
+ * @group Service Definitions
+ */
+ public static CameraWebRTCStreamManagement: typeof CameraWebRTCStreamManagement
/**
* @group Service Definitions
*/
@@ -890,7 +930,8 @@ export class Service extends EventEmitter {
this.emitCharacteristicWarningEvent(characteristic, CharacteristicWarningType.TIMEOUT_READ,
`The read handler for the characteristic '${characteristic?.displayName
}' didn't respond at all! Please check that you properly call the callback!`)
- service.characteristics.push(characteristic.internalHAPRepresentation()) // value is set to null
+ // The representation's value is null, but for a type whose value states a camera's configuration, whose held value stands.
+ service.characteristics.push(characteristic.internalHAPRepresentation())
}
} catch (error) {
// thrown inside a timer, this would end the process
diff --git a/src/lib/camera/GlobalOperatingMode.spec.ts b/src/lib/camera/GlobalOperatingMode.spec.ts
new file mode 100644
index 000000000..c84cf8c74
--- /dev/null
+++ b/src/lib/camera/GlobalOperatingMode.spec.ts
@@ -0,0 +1,334 @@
+import type { Mock } from 'vitest'
+
+import type { CharacteristicsWriteRequest } from '../../types.js'
+import type { CameraControllerLegacyOptions, CameraControllerOptions, CameraControllerServiceMap } from '../controller/index.js'
+import type { CameraGlobalOperatingMode } from '../definitions/index.js'
+import type { HAPConnection } from '../util/eventedhttp.js'
+import type { OperatingModeState } from './OperatingModePolicy.js'
+
+import { describe, expect, it, vi } from 'vitest'
+
+import {
+ capabilitiesCameraOptions,
+ createCameraControllerOptions,
+ idleStreaming,
+ NUMBERED_USERNAME,
+ numberedAccessory,
+ savedMapOf,
+ videoSensor,
+} from '../../test-utils/cameraFixtures.js'
+import { Accessory } from '../Accessory.js'
+import { Access, Characteristic } from '../Characteristic.js'
+import { CameraController, CameraControllerEvents, DoorbellController } from '../controller/index.js'
+import { HAPStatus } from '../HAPServer.js'
+import { IdentifierCache } from '../model/IdentifierCache.js'
+import { Service } from '../Service.js'
+import * as uuid from '../util/uuid.js'
+
+import '../definitions/index.js'
+
+const GLOBAL_OPERATING_MODE = 'cameraCapabilities:globalOperatingMode'
+const HUB = {} as HAPConnection
+
+const SENSOR = videoSensor('a1b2c3d4-0000-4000-8000-000000000001')
+
+const PERSISTED_SLICE: OperatingModeState = {
+ recordingActive: false,
+ recordingAudioActive: false,
+ eventSnapshotsActive: true,
+ homeKitCameraActive: true,
+ periodicSnapshotsActive: true,
+}
+
+const GLOBAL_SLICE: OperatingModeState = {
+ ...PERSISTED_SLICE,
+ globalStreamingEnabled: false,
+ operatingModeIndicator: true,
+ manuallyDisabled: false,
+ nightVision: false,
+ thirdPartyCameraActive: false,
+}
+
+function legacyOptions(overrides: Partial = {}): CameraControllerLegacyOptions {
+ return {
+ ...createCameraControllerOptions(),
+ ...overrides,
+ }
+}
+
+function withCapabilities(): CameraControllerOptions {
+ return capabilitiesCameraOptions({
+ videoSensors: [SENSOR],
+ streaming: idleStreaming(),
+ })
+}
+
+function configured(options: CameraControllerOptions): { camera: CameraController, map: CameraControllerServiceMap } {
+ const camera = new CameraController(options)
+ const map = camera.constructServices()
+ camera.configureServices()
+ return { camera, map }
+}
+
+function globalOf(map: CameraControllerServiceMap): CameraGlobalOperatingMode {
+ return map[GLOBAL_OPERATING_MODE] as CameraGlobalOperatingMode
+}
+
+function capabilityKeys(map: CameraControllerServiceMap): string[] {
+ return Object.keys(map).filter(key => key.startsWith('cameraCapabilities:'))
+}
+
+describe('global operating mode', () => {
+ it('builds the service with the policy\'s values', () => {
+ const { map } = configured(withCapabilities())
+ const global = globalOf(map)
+
+ expect(global.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.ON)
+ expect(global.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(true)
+ expect(global.getCharacteristic(Characteristic.CameraOperatingModeIndicator).value).toBe(Characteristic.CameraOperatingModeIndicator.ENABLE)
+ })
+
+ it('marks the camera state and the status light admin-only on both services and leaves night vision unmarked', () => {
+ const { camera, map } = configured(withCapabilities())
+ const global = globalOf(map)
+ const legacyIndicator = camera.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.CameraOperatingModeIndicator)
+
+ expect(global.getCharacteristic(Characteristic.HomeKitCameraActive).props.adminOnlyAccess).toEqual([Access.WRITE])
+ expect(global.getCharacteristic(Characteristic.CameraOperatingModeIndicator).props.adminOnlyAccess).toEqual([Access.WRITE])
+ expect(global.getCharacteristic(Characteristic.StreamingEnabled).props.adminOnlyAccess).toEqual([Access.WRITE])
+ expect(global.getCharacteristic(Characteristic.NightVision).props.adminOnlyAccess).toBeUndefined()
+ expect(legacyIndicator.props.adminOnlyAccess).toEqual([Access.WRITE])
+ })
+
+ it('marks the legacy operating-mode fields admin-only on a recording camera and leaves recording audio unmarked', () => {
+ const { camera } = configured(legacyOptions())
+ const { operatingModeService, recordingManagementService } = camera.recordingManagement!
+
+ expect(operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).props.adminOnlyAccess).toEqual([Access.WRITE])
+ expect(operatingModeService.getCharacteristic(Characteristic.EventSnapshotsActive).props.adminOnlyAccess).toEqual([Access.WRITE])
+ expect(operatingModeService.getCharacteristic(Characteristic.PeriodicSnapshotsActive).props.adminOnlyAccess).toEqual([Access.WRITE])
+ expect(recordingManagementService.getCharacteristic(Characteristic.Active).props.adminOnlyAccess).toEqual([Access.WRITE])
+ expect(recordingManagementService.getCharacteristic(Characteristic.RecordingAudioActive).props.adminOnlyAccess).toBeUndefined()
+ })
+
+ it('adopts a saved service with its cached values and reports no change', () => {
+ const saved = savedMapOf(new CameraController(withCapabilities()))
+ const global = globalOf(saved)
+ global.getCharacteristic(Characteristic.StreamingEnabled).value = false
+ global.getCharacteristic(Characteristic.CameraOperatingModeIndicator).value = Characteristic.CameraOperatingModeIndicator.DISABLE
+ const camera = new CameraController(withCapabilities())
+ const changes = vi.fn()
+ const saves = vi.fn()
+ camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, changes)
+ camera.setupStateChangeDelegate(saves)
+
+ expect(camera.initWithServices(saved)).toBeUndefined()
+
+ camera.configureServices()
+
+ expect(globalOf(saved)).toBe(global)
+ expect(camera.serialize()!.operatingMode).toMatchObject({
+ globalStreamingEnabled: false,
+ operatingModeIndicator: false,
+ })
+ expect(changes).not.toHaveBeenCalled()
+ expect(saves).not.toHaveBeenCalled()
+ })
+
+ it('constructs the global service under its prefixed key only for a camera with the capabilities block', () => {
+ expect(capabilityKeys(configured(withCapabilities()).map)).toContain(GLOBAL_OPERATING_MODE)
+ expect(capabilityKeys(configured(legacyOptions()).map)).toEqual([])
+ })
+
+ it('deletes every prefixed key a camera without the block restores, keeps every other key and reports the change', () => {
+ const saved = savedMapOf(new CameraController(withCapabilities()))
+ saved['cameraCapabilities:retired'] = new Service.CameraCapabilities('', '')
+ const kept = Object.keys(saved).filter(key => !key.startsWith('cameraCapabilities:'))
+
+ const restored = new CameraController(legacyOptions()).initWithServices(saved)
+
+ expect(restored).toBeDefined()
+ expect(capabilityKeys(restored!)).toEqual([])
+ expect(Object.keys(restored!)).toEqual(expect.arrayContaining(kept))
+ })
+
+ it('reconciles the prefixed keys of a doorbell', () => {
+ const constructed = new DoorbellController(withCapabilities()).constructServices()
+ const saved = savedMapOf(new DoorbellController(withCapabilities()))
+
+ const restored = new DoorbellController(legacyOptions()).initWithServices(saved)
+
+ expect(capabilityKeys(constructed)).toContain(GLOBAL_OPERATING_MODE)
+ expect(capabilityKeys(restored!)).toEqual([])
+ })
+
+ it('emits one operating-mode change per write on either projection and none for the refresh', async () => {
+ const { camera, map } = configured(withCapabilities())
+ const changes = vi.fn()
+ camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, changes)
+
+ await camera.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).handleSetRequest(0, HUB)
+ await globalOf(map).getCharacteristic(Characteristic.HomeKitCameraActive).handleSetRequest(1, HUB)
+
+ expect(changes.mock.calls).toEqual([
+ [
+ { field: 'homeKitCameraActive', value: false, reason: 'write' },
+ ],
+ [
+ { field: 'homeKitCameraActive', value: true, reason: 'write' },
+ ],
+ ])
+ })
+
+ // A camera with the capabilities block must record, because one without the recording option throws at its construction, which is why this row resets the global
+ // service of a recording camera alone.
+ it('resets the global service at a factory reset run twice', () => {
+ const { camera, map } = configured(withCapabilities())
+ const global = globalOf(map)
+ global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ global.updateCharacteristic(Characteristic.StreamingEnabled, false)
+ global.updateCharacteristic(Characteristic.CameraOperatingModeIndicator, Characteristic.CameraOperatingModeIndicator.DISABLE)
+
+ camera.handleFactoryReset()
+ camera.handleFactoryReset()
+
+ expect(global.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.ON)
+ expect(global.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(true)
+ expect(global.getCharacteristic(Characteristic.CameraOperatingModeIndicator).value).toBe(Characteristic.CameraOperatingModeIndicator.ENABLE)
+ })
+
+ it('builds a new global service over the new policy when a removed instance is configured again', () => {
+ const camera = new CameraController(withCapabilities())
+ const first = new Accessory('First', uuid.generate('global-operating-mode-first'))
+ first.configureController(camera)
+ const removed = first.getService(Service.CameraGlobalOperatingMode)!
+ first.removeController(camera)
+ const second = new Accessory('Second', uuid.generate('global-operating-mode-second'))
+
+ second.configureController(camera)
+ const global = second.getService(Service.CameraGlobalOperatingMode)!
+ global.updateCharacteristic(Characteristic.StreamingEnabled, false)
+ removed.updateCharacteristic(Characteristic.StreamingEnabled, true)
+
+ expect(global).not.toBe(removed)
+ expect(camera.serialize()!.operatingMode!.globalStreamingEnabled).toBe(false)
+ })
+
+ it('serves a stream on a camera with neither recording nor the block after it restores a recording camera with the camera off', async () => {
+ const recordingCamera = configured(legacyOptions()).camera
+ recordingCamera.recordingManagement!.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ const { camera } = configured(legacyOptions({ recording: undefined }))
+
+ camera.deserialize(recordingCamera.serialize()!)
+
+ await expect(camera.streamManagements[0].service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest('AAAA', HUB))
+ .rejects
+ .toBe(HAPStatus.INVALID_VALUE_IN_REQUEST)
+ })
+
+ it('carries the global fields a recording camera without the block restores until a factory reset', async () => {
+ const { camera } = configured(legacyOptions())
+
+ camera.deserialize({
+ ...camera.serialize()!,
+ operatingMode: GLOBAL_SLICE,
+ })
+
+ await expect(camera.streamManagements[0].service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest('AAAA', HUB))
+ .rejects
+ .toBe(HAPStatus.INVALID_VALUE_IN_REQUEST)
+ expect(camera.serialize()!.operatingMode).toEqual(GLOBAL_SLICE)
+
+ camera.handleFactoryReset()
+
+ expect(camera.serialize()!.operatingMode).toEqual(PERSISTED_SLICE)
+ })
+
+ it('carries a slice with the global fields untouched through a camera with neither recording nor the block, and no other slice', () => {
+ const { camera } = configured(legacyOptions({ recording: undefined }))
+
+ camera.deserialize({
+ streamManagements: [],
+ operatingMode: GLOBAL_SLICE,
+ })
+
+ expect(camera.serialize()!.operatingMode).toEqual(GLOBAL_SLICE)
+
+ camera.deserialize({
+ streamManagements: [],
+ operatingMode: PERSISTED_SLICE,
+ })
+
+ expect(camera.serialize()!.operatingMode).toBeUndefined()
+ })
+
+ it('hands the policy a timed write of Manually Disabled on the global service, one operating-mode change with the written value', async () => {
+ const { aid, changes, connection, iid, write } = manuallyDisabledCamera()
+
+ connection.timedWritePid = 1337
+
+ await expect(write({
+ characteristics: [
+ { aid, iid, value: 1 },
+ ],
+ pid: 1337,
+ })).resolves.toEqual({
+ characteristics: [
+ { aid, iid, status: HAPStatus.SUCCESS },
+ ],
+ })
+ expect(changes.mock.calls).toEqual([
+ [
+ { field: 'manuallyDisabled', value: true, reason: 'write' },
+ ],
+ ])
+ })
+
+ it('answers a plain write of Manually Disabled on the global service with an invalid value, the policy hearing no change', async () => {
+ const { aid, changes, iid, write } = manuallyDisabledCamera()
+
+ await expect(write({
+ characteristics: [
+ { aid, iid, value: 1 },
+ ],
+ })).resolves.toEqual({
+ characteristics: [
+ { aid, iid, status: HAPStatus.INVALID_VALUE_IN_REQUEST },
+ ],
+ })
+ expect(changes).not.toHaveBeenCalled()
+ })
+})
+
+/* A numbered camera with the capabilities block whose global operating mode service carries Manually Disabled, with the characteristic's numbers, the
+ * camera's operating-mode changes a mock, and a write that goes through the accessory on one connection, as a hub's does.
+ */
+function manuallyDisabledCamera(): {
+ aid: number
+ changes: Mock
+ connection: HAPConnection
+ iid: number
+ write: (request: CharacteristicsWriteRequest) => Promise
+} {
+ const camera = new CameraController(withCapabilities())
+ const cache = new IdentifierCache(NUMBERED_USERNAME)
+ const accessory = numberedAccessory(camera, cache)
+ const characteristic = accessory.getService(Service.CameraGlobalOperatingMode)!.addCharacteristic(Characteristic.ManuallyDisabled)
+ const connection = {} as HAPConnection
+ const changes = vi.fn()
+
+ // The characteristic joins after the accessory was numbered, which is why it is numbered again.
+ accessory._assignIDs(cache)
+ camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, changes)
+
+ return {
+ aid: accessory.aid!,
+ changes,
+ connection,
+ iid: characteristic.iid!,
+ write: async request => new Promise((resolve) => {
+ // @ts-expect-error: private access
+ accessory.handleSetCharacteristics(connection, request, (_error: unknown, written: unknown) => resolve(written))
+ }),
+ }
+}
diff --git a/src/lib/camera/GlobalOperatingMode.ts b/src/lib/camera/GlobalOperatingMode.ts
new file mode 100644
index 000000000..820ae1a0b
--- /dev/null
+++ b/src/lib/camera/GlobalOperatingMode.ts
@@ -0,0 +1,61 @@
+import type { ControllerServiceMap } from '../controller/index.js'
+import type { CameraGlobalOperatingMode } from '../definitions/index.js'
+import type { OperatingModePolicy } from './OperatingModePolicy.js'
+
+import { Characteristic } from '../Characteristic.js'
+import { Service } from '../Service.js'
+import { CAPABILITY_KEY_PREFIX } from './capabilityKeys.js'
+
+/**
+ * The Camera Global Operating Mode service, which projects the operating-mode policy's camera-wide fields. It holds no state of its own: every value the
+ * service shows is a field of the policy, which binds the service's characteristics and marks the admin-only ones.
+ */
+export class GlobalOperatingMode {
+ /**
+ * The key the service carries in the camera's service map.
+ */
+ static readonly SERVICE_KEY = `${CAPABILITY_KEY_PREFIX}globalOperatingMode`
+
+ /**
+ * The camera's `CameraGlobalOperatingMode` service.
+ */
+ readonly service: CameraGlobalOperatingMode
+
+ /**
+ * Adopts the saved service, or builds one whose characteristics read the policy's values, and binds it to the policy.
+ * @param policy - The camera's operating-mode policy.
+ * @param service - The saved service, when the camera restores one.
+ */
+ constructor(policy: OperatingModePolicy, service?: CameraGlobalOperatingMode) {
+ this.service = service ?? GlobalOperatingMode.constructService(policy)
+ policy.bindGlobalOperatingMode(this.service)
+ }
+
+ /**
+ * Reconciles the surface in a restored service map, adopting its saved service or creating and inserting one. A camera without the camera capabilities
+ * block reconciles no surface, and the capability key sweep deletes a saved one.
+ * @param serviceMap - The camera's service map, changed in place.
+ * @param create - Builds the surface over the saved service, or over a new one when it is given none.
+ * @returns Whether the map changed.
+ */
+ static reconcile(serviceMap: ControllerServiceMap, create: (service?: CameraGlobalOperatingMode) => GlobalOperatingMode): boolean {
+ const saved = serviceMap[GlobalOperatingMode.SERVICE_KEY] as CameraGlobalOperatingMode | undefined
+ const surface = create(saved)
+
+ if (saved) {
+ return false
+ }
+
+ serviceMap[GlobalOperatingMode.SERVICE_KEY] = surface.service
+ return true
+ }
+
+ // A fresh characteristic reads its format's default, the camera off and streaming disabled among them, which is why each starts at the field the policy holds.
+ private static constructService(policy: OperatingModePolicy): CameraGlobalOperatingMode {
+ const service = new Service.CameraGlobalOperatingMode('', '')
+ service.setCharacteristic(Characteristic.HomeKitCameraActive, policy.homeKitCameraActive)
+ service.setCharacteristic(Characteristic.StreamingEnabled, policy.globalStreamingEnabled)
+ service.setCharacteristic(Characteristic.CameraOperatingModeIndicator, policy.operatingModeIndicator)
+ return service
+ }
+}
diff --git a/src/lib/camera/MotionAttribution.spec.ts b/src/lib/camera/MotionAttribution.spec.ts
new file mode 100644
index 000000000..1dff49188
--- /dev/null
+++ b/src/lib/camera/MotionAttribution.spec.ts
@@ -0,0 +1,987 @@
+import type { CharacteristicChange } from '../Characteristic.js'
+import type { CameraControllerOptions, CameraControllerServiceMap } from '../controller/index.js'
+import type { HAPConnection } from '../util/eventedhttp.js'
+import type { CameraReporter } from './diagnostics/CameraReporter.js'
+import type { CameraProblem } from './diagnostics/problems.js'
+import type { OperatingModeChange } from './OperatingModePolicy.js'
+
+import { Buffer } from 'node:buffer'
+
+import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
+
+import {
+ createCameraControllerOptions,
+ definedEntries,
+ FIRST_VIDEO_SENSOR,
+ handPublishedContext,
+ NUMBERED_ACCESSORY_UUID,
+ numberedAccessory,
+ SECOND_VIDEO_SENSOR,
+ twoSensorCameraOptions,
+} from '../../test-utils/cameraFixtures.js'
+import { detachedReporter, problemsOf } from '../../test-utils/reporterFixtures.js'
+import { settle } from '../../test-utils/settle.js'
+import { Accessory } from '../Accessory.js'
+import { Access, Characteristic, CharacteristicEventTypes } from '../Characteristic.js'
+import { CameraController, CameraControllerEvents, DoorbellController } from '../controller/index.js'
+import { HAPStatus } from '../HAPServer.js'
+import { AccessoryInfo, PermissionTypes } from '../model/AccessoryInfo.js'
+import { IdentifierCache } from '../model/IdentifierCache.js'
+import { Service, ServiceEventTypes } from '../Service.js'
+import { decodeContributingSensors, encodeContributingSensors } from './capabilities/cameraSensors.js'
+import { onCameraProblem } from './diagnostics/problems.js'
+import { MotionAttribution } from './MotionAttribution.js'
+import { CMAFRecordingManagement } from './recording/CMAFRecordingManagement.js'
+
+// The first and the second video sensor's UUIDs in the registry's order and in lowercase, as the attribution takes them, and one no camera here has.
+const FIRST = FIRST_VIDEO_SENSOR.uuid.toLowerCase()
+const SECOND = SECOND_VIDEO_SENSOR.uuid.toLowerCase()
+const SENSOR_UUIDS = [FIRST, SECOND]
+const UNKNOWN = 'e0000009-0000-4000-8000-000000000009'
+const ANOTHER_UNKNOWN = 'e000000a-0000-4000-8000-00000000000a'
+
+const HUB = {} as HAPConnection
+
+// The cameras a row wires, removed after it. No listener outlives its row.
+const wiredCameras: CameraController[] = []
+
+afterEach(() => {
+ for (const camera of wiredCameras.splice(0)) {
+ camera.handleControllerRemoved()
+ }
+
+ vi.restoreAllMocks()
+})
+
+// An attribution over the given motion sensor and the fixture's video sensors, which hears no edge of Motion Detected, its reporter one of no camera
+// unless a row hands its own.
+function attributed(sensor = new Service.MotionSensor('', ''), reporter: CameraReporter = detachedReporter()): { attribution: MotionAttribution, sensor: Service } {
+ return {
+ attribution: new MotionAttribution(sensor, SENSOR_UUIDS, reporter),
+ sensor,
+ }
+}
+
+// The attribution of a configured two-sensor camera whose motion sensor is the given one: each edge of Motion Detected reaches it through the camera
+// controller's own listener.
+function wired(sensor = new Service.MotionSensor('', '')): { attribution: MotionAttribution, camera: CameraController, sensor: Service } {
+ const camera = new CameraController({
+ ...twoSensorCameraOptions(),
+ sensors: { motion: sensor },
+ })
+
+ wiredCameras.push(camera)
+ camera.constructServices()
+ camera.configureServices()
+
+ // @ts-expect-error: private access
+ return { attribution: camera.motionAttribution!, camera, sensor }
+}
+
+// The video sensors a motion sensor's Contributing Sensors lists, in its order, as the codec decodes them.
+function listed(sensor: Service): string[] {
+ return decodeContributingSensors(sensor.getCharacteristic(Characteristic.ContributingSensors).value as string).sensorList.map(({ sensorUUID }) => sensorUUID)
+}
+
+// Each write of Contributing Sensors and Motion Detected from here on, in the order their change events arrive.
+function writesOf(sensor: Service): string[] {
+ const writes: string[] = []
+
+ sensor.getCharacteristic(Characteristic.ContributingSensors).on(CharacteristicEventTypes.CHANGE, () => writes.push('contributing sensors'))
+ sensor.getCharacteristic(Characteristic.MotionDetected).on(CharacteristicEventTypes.CHANGE, () => writes.push('motion detected'))
+
+ return writes
+}
+
+describe('motion attribution', () => {
+ it('adds contributing sensors listing none to a sensor at rest, and lists every sensor in registry order on one with motion and a stale list', () => {
+ const sensor = new Service.MotionSensor('', '')
+
+ expect(sensor.testCharacteristic(Characteristic.ContributingSensors)).toBe(false)
+
+ attributed(sensor)
+
+ expect(sensor.testCharacteristic(Characteristic.ContributingSensors)).toBe(true)
+ expect(listed(sensor)).toEqual([])
+
+ const stale = new Service.MotionSensor('', '')
+ const staleList = encodeContributingSensors({
+ sensorList: [
+ { sensorUUID: SECOND },
+ ],
+ })
+ stale.updateCharacteristic(Characteristic.MotionDetected, true)
+ stale.getCharacteristic(Characteristic.ContributingSensors).updateValue(staleList)
+
+ attributed(stale)
+
+ expect(listed(stale)).toEqual([FIRST, SECOND])
+ })
+
+ it('lists every sensor in registry order at a direct write of motion detected true', () => {
+ const { sensor } = wired()
+
+ sensor.updateCharacteristic(Characteristic.MotionDetected, true)
+
+ expect(listed(sensor)).toEqual([FIRST, SECOND])
+ })
+
+ it('lists no sensor at a direct write of motion detected false', () => {
+ const { sensor } = wired()
+ sensor.updateCharacteristic(Characteristic.MotionDetected, true)
+
+ sensor.updateCharacteristic(Characteristic.MotionDetected, false)
+
+ expect(listed(sensor)).toEqual([])
+ })
+
+ it('writes the list before the service forwards the motion change at a direct write of motion detected, raised and cleared alike', () => {
+ const { sensor } = wired()
+ const forwarded: string[] = []
+ sensor.on(ServiceEventTypes.CHARACTERISTIC_CHANGE, ({ characteristic }) => forwarded.push(characteristic.UUID))
+
+ sensor.updateCharacteristic(Characteristic.MotionDetected, true)
+ sensor.updateCharacteristic(Characteristic.MotionDetected, false)
+
+ expect(forwarded).toEqual([
+ Characteristic.ContributingSensors.UUID,
+ Characteristic.MotionDetected.UUID,
+ Characteristic.ContributingSensors.UUID,
+ Characteristic.MotionDetected.UUID,
+ ])
+ })
+
+ it('lists every sensor for a report of motion that names none', () => {
+ const { attribution, sensor } = attributed()
+
+ attribution.report(true)
+
+ expect(listed(sensor)).toEqual([FIRST, SECOND])
+
+ attribution.report(true, [SECOND])
+ attribution.report(true, [])
+
+ expect(listed(sensor)).toEqual([FIRST, SECOND])
+ })
+
+ it('lists each named sensor once in registry order whatever its case, leaving out an unknown one with one warning, and every sensor for all unknown', () => {
+ const { attribution, sensor } = attributed()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+
+ attribution.report(true, [
+ SECOND_VIDEO_SENSOR.uuid,
+ FIRST,
+ SECOND,
+ UNKNOWN,
+ ])
+
+ expect(listed(sensor)).toEqual([FIRST, SECOND])
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(warn.mock.calls[0][0]).toContain(UNKNOWN)
+
+ warn.mockClear()
+ attribution.report(true, [UNKNOWN, ANOTHER_UNKNOWN])
+
+ expect(listed(sensor)).toEqual([FIRST, SECOND])
+ expect(warn).toHaveBeenCalledTimes(2)
+ expect(warn.mock.calls[0][0]).toContain(UNKNOWN)
+ expect(warn.mock.calls[1][0]).toContain(ANOTHER_UNKNOWN)
+ })
+
+ it('rewrites the list and writes no motion detected for a report of motion while motion is detected', () => {
+ const { attribution, sensor } = attributed()
+ attribution.report(true)
+ const writes = writesOf(sensor)
+
+ attribution.report(true, [FIRST])
+
+ expect(listed(sensor)).toEqual([FIRST])
+ expect(writes).toEqual(['contributing sensors'])
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(true)
+ })
+
+ it('lists no sensor and warns nothing for a report of cleared motion naming an unknown sensor', () => {
+ const { attribution, sensor } = attributed()
+ attribution.report(true)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+
+ attribution.report(false, [UNKNOWN])
+
+ expect(listed(sensor)).toEqual([])
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false)
+ expect(warn).not.toHaveBeenCalled()
+ })
+
+ it('writes the list once and then motion detected once for a report of motion at rest', () => {
+ const { attribution, sensor } = attributed()
+ const writes = writesOf(sensor)
+
+ attribution.report(true, [SECOND])
+
+ expect(writes).toEqual(['contributing sensors', 'motion detected'])
+ expect(listed(sensor)).toEqual([SECOND])
+ })
+
+ it('writes the list once and then motion detected once for a report of cleared motion while motion is detected', () => {
+ const { attribution, sensor } = attributed()
+ attribution.report(true)
+ const writes = writesOf(sensor)
+
+ attribution.report(false)
+
+ expect(writes).toEqual(['contributing sensors', 'motion detected'])
+ expect(listed(sensor)).toEqual([])
+ })
+
+ it('lists no sensor at a direct write of motion detected false after a report of motion naming the second sensor', () => {
+ const { attribution, sensor } = wired()
+ attribution.report(true, [SECOND])
+
+ sensor.updateCharacteristic(Characteristic.MotionDetected, false)
+
+ expect(listed(sensor)).toEqual([])
+ })
+
+ it('leaves the list at a motion detected write after its camera\'s removal, the service keeping its own listener alone', () => {
+ const sensor = new Service.MotionSensor('', '')
+ const motionDetected = sensor.getCharacteristic(Characteristic.MotionDetected)
+ const own = motionDetected.listenerCount(CharacteristicEventTypes.CHANGE)
+ const { attribution, camera } = wired(sensor)
+
+ expect(motionDetected.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(own + 1)
+
+ attribution.report(true, [SECOND])
+ camera.handleControllerRemoved()
+ sensor.updateCharacteristic(Characteristic.MotionDetected, false)
+
+ expect(motionDetected.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(own)
+ expect(listed(sensor)).toEqual([SECOND])
+ })
+
+ it('keeps a named list at a direct write that leaves motion detected as it stands, and writes no motion detected for cleared motion at rest', () => {
+ const { attribution, sensor } = wired()
+ attribution.report(true, [SECOND])
+
+ sensor.updateCharacteristic(Characteristic.MotionDetected, true)
+
+ expect(listed(sensor)).toEqual([SECOND])
+
+ attribution.report(false)
+ const writes = writesOf(sensor)
+ attribution.report(false)
+
+ expect(writes).toEqual(['contributing sensors'])
+ expect(listed(sensor)).toEqual([])
+ })
+
+ it('lists every sensor for a report whose names are no list, and leaves out an entry that is no string, each with one warning', () => {
+ const { attribution, sensor } = attributed()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+
+ attribution.report(true, SECOND as unknown as readonly string[])
+
+ expect(listed(sensor)).toEqual([FIRST, SECOND])
+ expect(warn).toHaveBeenCalledTimes(1)
+
+ warn.mockClear()
+ attribution.report(true, [SECOND, 7] as unknown as readonly string[])
+
+ expect(listed(sensor)).toEqual([SECOND])
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(warn.mock.calls[0][0]).toContain('7')
+ })
+
+ it.each([
+ {
+ named: [UNKNOWN],
+ refusal: 'an unknown sensor',
+ },
+ {
+ named: SECOND as unknown as readonly string[],
+ refusal: 'names that are no list',
+ },
+ {
+ named: [7] as unknown as readonly string[],
+ refusal: 'an entry that is no string',
+ },
+ ])('raises one value-refused problem at the level warning, carrying no field but its accessory, for a report naming $refusal', ({ named }) => {
+ const { problems, reporter } = problemsOf()
+ const { attribution } = attributed(new Service.MotionSensor('', ''), reporter)
+
+ attribution.report(true, named)
+
+ // Each problem is read whole, its sentence's wording aside, and a field it gains or loses is read too.
+ expect(problems).toEqual([
+ {
+ accessoryUUID: expect.any(String),
+ kind: 'value-refused',
+ level: 'warning',
+ sentence: expect.any(String),
+ },
+ ])
+ })
+
+ describe('camera controller wiring', () => {
+ // The username of an accessory a row pairs and numbers, and the pairings a write arrives under. Each row numbers over an identifier cache of its own.
+ const USERNAME = 'AA:BB:CC:DD:EE:01'
+ const ADMIN = 'AA:BB:CC:DD:EE:02'
+ const USER = 'AA:BB:CC:DD:EE:03'
+
+ // The cameras a row builds, removed after it. No policy or attribution listener outlives its row.
+ const cameras: CameraController[] = []
+
+ afterEach(() => {
+ for (const camera of cameras.splice(0)) {
+ camera.handleControllerRemoved()
+ }
+ })
+
+ // A camera built from the given options, by default the two-sensor camera with the capabilities block.
+ function cameraOf(options: CameraControllerOptions = twoSensorCameraOptions()): CameraController {
+ const camera = new CameraController(options)
+
+ cameras.push(camera)
+ return camera
+ }
+
+ // A camera's services, constructed and configured as a first run of the accessory configures them.
+ function configured(camera: CameraController): CameraControllerServiceMap {
+ const map = camera.constructServices()
+ camera.configureServices()
+
+ return map
+ }
+
+ // A saved accessory as a cached accessory restores at startup, its camera not yet configured.
+ function cachedAccessory(saved: Accessory): Accessory {
+ return Accessory.deserialize(Accessory.serialize(saved))
+ }
+
+ // Each change of Motion Detected the sensor's service forwards from here on, by its old and new values.
+ function motionForwarded(sensor: Service): Pick[] {
+ const forwarded: Pick[] = []
+
+ sensor.on(ServiceEventTypes.CHARACTERISTIC_CHANGE, ({ characteristic, newValue, oldValue }) => {
+ if (characteristic.UUID === Characteristic.MotionDetected.UUID) {
+ forwarded.push({ newValue, oldValue })
+ }
+ })
+
+ return forwarded
+ }
+
+ // Each way a plugin writes motion on a motion sensor's Motion Detected, or answers it to a hub's read through a read handler.
+ const WRITERS = [
+ {
+ read: false,
+ write: async (sensor: Service) => sensor.getCharacteristic(Characteristic.MotionDetected).updateValue(true),
+ writer: 'updateValue of true',
+ },
+ {
+ read: false,
+ write: async (sensor: Service) => sensor.getCharacteristic(Characteristic.MotionDetected).updateValue(1),
+ writer: 'updateValue of 1',
+ },
+ {
+ read: false,
+ write: async (sensor: Service) => sensor.getCharacteristic(Characteristic.MotionDetected).setValue(true),
+ writer: 'setValue',
+ },
+ {
+ read: false,
+ write: async (sensor: Service) => sensor.getCharacteristic(Characteristic.MotionDetected).sendEventNotification(true),
+ writer: 'sendEventNotification',
+ },
+ {
+ read: false,
+ write: async (sensor: Service) => sensor.updateCharacteristic(Characteristic.MotionDetected, true),
+ writer: 'the service\'s updateCharacteristic',
+ },
+ {
+ read: false,
+ write: async (sensor: Service) => sensor.setCharacteristic(Characteristic.MotionDetected, true),
+ writer: 'the service\'s setCharacteristic',
+ },
+ {
+ read: true,
+ write: async (sensor: Service) => sensor.getCharacteristic(Characteristic.MotionDetected).onGet(() => true).handleGetRequest(HUB),
+ writer: 'an onGet handler\'s answer to a hub\'s read',
+ },
+ {
+ read: true,
+ write: async (sensor: Service) => sensor.getCharacteristic(Characteristic.MotionDetected)
+ .on(CharacteristicEventTypes.GET, callback => callback(null, true))
+ .handleGetRequest(HUB),
+ writer: 'a get listener\'s answer to a hub\'s read',
+ },
+ ]
+
+ it('adds contributing sensors listing none and motion enabled reading on to a block camera\'s own motion sensor', () => {
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+
+ expect(sensor.testCharacteristic(Characteristic.ContributingSensors)).toBe(true)
+ expect(listed(sensor)).toEqual([])
+ expect(sensor.getCharacteristic(Characteristic.MotionEnabled).value).toBe(true)
+ })
+
+ it('adds neither characteristic to the motion sensor of a camera without the block', () => {
+ const camera = cameraOf(createCameraControllerOptions())
+ configured(camera)
+
+ expect(camera.motionService!.testCharacteristic(Characteristic.ContributingSensors)).toBe(false)
+ expect(camera.motionService!.testCharacteristic(Characteristic.MotionEnabled)).toBe(false)
+ })
+
+ it('raises motion naming the second sensor and clears it, listing the second sensor and then none', () => {
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+
+ camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid])
+
+ expect(listed(sensor)).toEqual([SECOND])
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(true)
+
+ camera.updateMotionDetected(false)
+
+ expect(listed(sensor)).toEqual([])
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false)
+ })
+
+ it('hands the attribution each edge of a direct write of motion detected once, from the controller\'s one listener', () => {
+ const motionChanged = vi.spyOn(MotionAttribution.prototype, 'motionChanged')
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+
+ sensor.updateCharacteristic(Characteristic.MotionDetected, true)
+
+ expect(listed(sensor)).toEqual([FIRST, SECOND])
+
+ sensor.updateCharacteristic(Characteristic.MotionDetected, false)
+
+ expect(listed(sensor)).toEqual([])
+ expect(motionChanged.mock.calls).toEqual([
+ [true],
+ [false],
+ ])
+ })
+
+ it('hands the attribution the edge of a report once, which leaves the list the report named', () => {
+ const motionChanged = vi.spyOn(MotionAttribution.prototype, 'motionChanged')
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+
+ camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid])
+
+ expect(listed(sensor)).toEqual([SECOND])
+ expect(motionChanged.mock.calls).toEqual([
+ [true],
+ ])
+ })
+
+ it('hands the attribution nothing for a repeat, and releases the controller\'s listener at a removal', () => {
+ const motionChanged = vi.spyOn(MotionAttribution.prototype, 'motionChanged')
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+ const motionDetected = sensor.getCharacteristic(Characteristic.MotionDetected)
+ const listening = motionDetected.listenerCount(CharacteristicEventTypes.CHANGE)
+ camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid])
+ motionChanged.mockClear()
+
+ sensor.updateCharacteristic(Characteristic.MotionDetected, true)
+ camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid])
+
+ expect(motionChanged).not.toHaveBeenCalled()
+ expect(listed(sensor)).toEqual([SECOND])
+
+ camera.handleControllerRemoved()
+
+ expect(motionDetected.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(listening - 1)
+ })
+
+ it('writes motion detected alone on a camera without the block', () => {
+ const camera = cameraOf(createCameraControllerOptions())
+ configured(camera)
+
+ camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid])
+
+ expect(camera.motionService!.getCharacteristic(Characteristic.MotionDetected).value).toBe(true)
+ expect(camera.motionService!.testCharacteristic(Characteristic.ContributingSensors)).toBe(false)
+ })
+
+ it('warns once and changes nothing for a motion update on a camera without a motion sensor', () => {
+ // A camera with the block needs its motion sensor unless it is a doorbell, which is why the camera without one is a doorbell with the block.
+ const camera = new DoorbellController({
+ ...twoSensorCameraOptions(),
+ sensors: { occupancy: true },
+ })
+
+ cameras.push(camera)
+
+ const map = configured(camera)
+ const before = camera.serialize()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+
+ camera.updateMotionDetected(true, [FIRST])
+
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(camera.motionService).toBeUndefined()
+ expect(Object.values(map).some(service => service?.UUID === Service.MotionSensor.UUID)).toBe(false)
+ expect(camera.serialize()).toEqual(before)
+ })
+
+ it('reports a motion update on a camera with the block and without a motion sensor as a refused value, printed bare before its configure and '
+ + 'published on its accessory\'s channel once it holds that accessory and the channel has a subscriber', async () => {
+ const sentence = 'The camera has no motion sensor, which means the motion update reaches nothing.'
+ const camera = new DoorbellController({
+ ...twoSensorCameraOptions(),
+ sensors: { occupancy: true },
+ })
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const problems: CameraProblem[] = []
+
+ cameras.push(camera)
+ camera.updateMotionDetected(true)
+
+ expect(warn.mock.calls).toEqual([
+ [sentence],
+ ])
+
+ configured(camera)
+ handPublishedContext(camera)
+
+ const subscription = onCameraProblem(NUMBERED_ACCESSORY_UUID, problem => problems.push(problem))
+
+ onTestFinished(() => {
+ subscription[Symbol.dispose]()
+ })
+ camera.updateMotionDetected(true, [FIRST])
+ await settle()
+
+ expect(problems).toEqual([
+ {
+ accessoryUUID: NUMBERED_ACCESSORY_UUID,
+ kind: 'value-refused',
+ level: 'warning',
+ sentence,
+ },
+ ])
+ expect(warn).toHaveBeenCalledOnce()
+ })
+
+ it('adds each characteristic only the block adds to a plugin\'s own motion sensor and removes them from it at a restore without the block, where a '
+ + 'camera that never had the block keeps what the plugin gave its sensor', () => {
+ const supplied = new Service.MotionSensor('', '')
+ const map = configured(cameraOf({
+ ...twoSensorCameraOptions(),
+ sensors: { motion: supplied, occupancy: true },
+ }))
+
+ expect(supplied.testCharacteristic(Characteristic.ContributingSensors)).toBe(true)
+ expect(supplied.testCharacteristic(Characteristic.MotionEnabled)).toBe(true)
+
+ const legacy = cameraOf({
+ ...createCameraControllerOptions(),
+ sensors: { motion: supplied, occupancy: true },
+ })
+ legacy.initWithServices(definedEntries(map))
+ legacy.configureServices()
+
+ expect(legacy.motionService).toBe(supplied)
+ expect(supplied.testCharacteristic(Characteristic.ContributingSensors)).toBe(false)
+ expect(supplied.testCharacteristic(Characteristic.MotionEnabled)).toBe(false)
+
+ // A plugin's own sensor on a camera that never had the block carries the Motion Enabled its plugin gave it, and the map that camera saved carries no
+ // key under the capability prefix.
+ const own = new Service.MotionSensor('', '')
+ own.getCharacteristic(Characteristic.MotionEnabled)
+ const ownOptions = {
+ ...createCameraControllerOptions(),
+ sensors: { motion: own, occupancy: true },
+ }
+ const legacySaved = definedEntries(configured(cameraOf(ownOptions)))
+
+ cameraOf(ownOptions).initWithServices(legacySaved)
+
+ expect(Object.keys(legacySaved).filter(key => key.startsWith('cameraCapabilities:'))).toEqual([])
+ expect(own.testCharacteristic(Characteristic.MotionEnabled)).toBe(true)
+ })
+
+ it('adopts a block camera\'s saved owned sensor a plugin hands back as its own at a restore without the block, removing each characteristic only the '
+ + 'block adds', () => {
+ const saved = definedEntries(configured(cameraOf()))
+ const owned = saved.motionService!
+
+ const restored = cameraOf({
+ ...createCameraControllerOptions(),
+ sensors: { motion: owned, occupancy: true },
+ })
+ restored.initWithServices(saved)
+
+ expect(restored.motionService).toBe(owned)
+ expect(owned.testCharacteristic(Characteristic.ContributingSensors)).toBe(false)
+ expect(owned.testCharacteristic(Characteristic.MotionEnabled)).toBe(false)
+ })
+
+ it('drops each characteristic only the block adds from an owned sensor a block camera saved at a restore without the block, and keeps a legacy camera\'s', () => {
+ const saved = definedEntries(configured(cameraOf()))
+ const owned = saved.motionService!
+
+ expect(owned.testCharacteristic(Characteristic.ContributingSensors)).toBe(true)
+ expect(owned.testCharacteristic(Characteristic.MotionEnabled)).toBe(true)
+
+ const restored = cameraOf(createCameraControllerOptions())
+ restored.initWithServices(saved)
+
+ expect(restored.motionService).toBe(owned)
+ expect(owned.testCharacteristic(Characteristic.ContributingSensors)).toBe(false)
+ expect(owned.testCharacteristic(Characteristic.MotionEnabled)).toBe(false)
+
+ // A legacy camera's plugin gave its own sensor Motion Enabled, and the map it saved carries no key under the capability prefix.
+ const legacySaved = definedEntries(configured(cameraOf(createCameraControllerOptions())))
+ const legacy = legacySaved.motionService!
+ legacy.getCharacteristic(Characteristic.MotionEnabled)
+
+ expect(Object.keys(legacySaved).filter(key => key.startsWith('cameraCapabilities:'))).toEqual([])
+
+ cameraOf(createCameraControllerOptions()).initWithServices(legacySaved)
+
+ expect(legacy.testCharacteristic(Characteristic.MotionEnabled)).toBe(true)
+ })
+
+ it('reports motion enabled for a hub write, a factory reset and a restore, each under its reason, and serializes the value each leaves', async () => {
+ const camera = cameraOf()
+ configured(camera)
+ const motionEnabled = camera.motionService!.getCharacteristic(Characteristic.MotionEnabled)
+ const changes: OperatingModeChange[] = []
+ camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, change => changes.push(change))
+ const heard = (): OperatingModeChange[] => changes.filter(({ field }) => field === 'motionEnabled')
+
+ await motionEnabled.handleSetRequest(false, HUB)
+
+ expect(heard()).toEqual([
+ { field: 'motionEnabled', value: false, reason: 'write' },
+ ])
+ expect(camera.serialize()!.operatingMode!.motionEnabled).toBe(false)
+
+ camera.handleFactoryReset()
+
+ expect(heard().at(-1)).toEqual({ field: 'motionEnabled', value: true, reason: 'reset' })
+ expect(camera.serialize()!.operatingMode!.motionEnabled).toBe(true)
+
+ camera.deserialize({
+ streamManagements: [],
+ operatingMode: {
+ ...camera.serialize()!.operatingMode!,
+ motionEnabled: false,
+ },
+ })
+
+ expect(heard().at(-1)).toEqual({ field: 'motionEnabled', value: false, reason: 'restore' })
+ expect(heard()).toHaveLength(3)
+ expect(camera.serialize()!.operatingMode!.motionEnabled).toBe(false)
+ expect(motionEnabled.value).toBe(false)
+ })
+
+ it('refuses a user pairing\'s write of a motion enabled cached without the admin-only mark, leaving the value and the policy', async () => {
+ const restored = cachedAccessory(numberedAccessory(cameraOf()))
+ const motionEnabled = restored.getService(Service.MotionSensor)!.getCharacteristic(Characteristic.MotionEnabled)
+ motionEnabled.setProps({ adminOnlyAccess: null })
+
+ expect(motionEnabled.props.adminOnlyAccess).toBeUndefined()
+
+ const camera = cameraOf()
+ const accessory = numberedAccessory(camera, new IdentifierCache(USERNAME), restored)
+ const changes = vi.fn()
+ camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, changes)
+ const pairings = AccessoryInfo.create(USERNAME)
+ pairings.addPairedClient(ADMIN, Buffer.alloc(32, 1), PermissionTypes.ADMIN)
+ pairings.addPairedClient(USER, Buffer.alloc(32, 2), PermissionTypes.USER)
+ accessory._accessoryInfo = pairings
+
+ const response = await new Promise((resolve) => {
+ // @ts-expect-error: private access
+ accessory.handleSetCharacteristics({ username: USER } as HAPConnection, {
+ characteristics: [
+ { aid: accessory.aid!, iid: motionEnabled.iid!, value: false },
+ ],
+ }, (_error: unknown, written: unknown) => resolve(written))
+ })
+
+ expect(response).toEqual({
+ characteristics: [
+ { aid: accessory.aid, iid: motionEnabled.iid, status: HAPStatus.INSUFFICIENT_PRIVILEGES },
+ ],
+ })
+ expect(motionEnabled.props.adminOnlyAccess).toEqual([Access.WRITE])
+ expect(motionEnabled.value).toBe(true)
+ expect(camera.serialize()!.operatingMode!.motionEnabled).toBe(true)
+ expect(changes).not.toHaveBeenCalled()
+ })
+
+ it('leaves motion detected and motion enabled their service\'s listener alone after a removal, a motion detected write rewriting no list', () => {
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+ camera.updateMotionDetected(true, [SECOND])
+
+ camera.handleControllerRemoved()
+
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).listenerCount(CharacteristicEventTypes.CHANGE)).toBe(1)
+ expect(sensor.getCharacteristic(Characteristic.MotionEnabled).listenerCount(CharacteristicEventTypes.CHANGE)).toBe(1)
+
+ sensor.updateCharacteristic(Characteristic.MotionDetected, false)
+
+ expect(listed(sensor)).toEqual([SECOND])
+ })
+
+ it.each(WRITERS)('stores motion written by $writer while motion enabled reads on, the service forwarding one change to it', async ({ write }) => {
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+ const forwarded = motionForwarded(sensor)
+
+ await write(sensor)
+
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(true)
+ expect(forwarded).toEqual([
+ {
+ newValue: true,
+ oldValue: false,
+ },
+ ])
+ })
+
+ it('stores motion written on its motion detected after a removal, whatever motion enabled is written to after it', () => {
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+
+ // The removal's factory reset writes Motion Enabled on before the guard goes, and only a write of off after the removal shows a guard left behind.
+ camera.handleControllerRemoved()
+ sensor.getCharacteristic(Characteristic.MotionEnabled).updateValue(false)
+
+ const forwarded = motionForwarded(sensor)
+
+ sensor.getCharacteristic(Characteristic.MotionDetected).updateValue(true)
+
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(true)
+ expect(forwarded).toEqual([
+ {
+ newValue: true,
+ oldValue: false,
+ },
+ ])
+ })
+
+ it('adopts a cached owned sensor with one of each characteristic, its cached motion enabled off standing until the restore writes the field', () => {
+ const saved = numberedAccessory(cameraOf())
+ saved.getService(Service.MotionSensor)!.getCharacteristic(Characteristic.MotionEnabled).updateValue(false)
+ const camera = cameraOf()
+ const sensor = numberedAccessory(camera, new IdentifierCache(USERNAME), cachedAccessory(saved)).getService(Service.MotionSensor)!
+ const motionEnabled = sensor.getCharacteristic(Characteristic.MotionEnabled)
+
+ expect(sensor.characteristics.filter(({ UUID }) => UUID === Characteristic.ContributingSensors.UUID)).toHaveLength(1)
+ expect(sensor.characteristics.filter(({ UUID }) => UUID === Characteristic.MotionEnabled.UUID)).toHaveLength(1)
+ expect(motionEnabled.value).toBe(false)
+
+ camera.deserialize({
+ streamManagements: [],
+ operatingMode: {
+ ...camera.serialize()!.operatingMode!,
+ motionEnabled: true,
+ },
+ })
+
+ expect(motionEnabled.value).toBe(true)
+ })
+
+ describe('motion enabled off', () => {
+ /* A cached accessory saved with its motion standing and its Motion Enabled as the row asks, each written into its serialized form, since the saved
+ * camera's guard stores no motion written while Motion Enabled reads off, and a fresh camera configured on it, as a cached accessory restores at
+ * startup with no stored operating mode.
+ */
+ function restoredStanding(motionEnabled: boolean): { camera: CameraController, sensor: Service } {
+ const serialized = Accessory.serialize(numberedAccessory(cameraOf()))
+ const savedSensor = serialized.services.find(({ UUID }) => UUID === Service.MotionSensor.UUID)!
+
+ for (const characteristic of savedSensor.characteristics) {
+ if (characteristic.UUID === Characteristic.MotionDetected.UUID) {
+ characteristic.value = true
+ }
+
+ if (characteristic.UUID === Characteristic.MotionEnabled.UUID) {
+ characteristic.value = motionEnabled
+ }
+ }
+
+ const camera = cameraOf()
+
+ return {
+ camera,
+ sensor: numberedAccessory(camera, new IdentifierCache(USERNAME), Accessory.deserialize(serialized)).getService(Service.MotionSensor)!,
+ }
+ }
+
+ it('holds back reported motion and motion written directly, writing no characteristic and raising no problem for a refused report, and lets a '
+ + 'reported clear through', async () => {
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+
+ await sensor.getCharacteristic(Characteristic.MotionEnabled).handleSetRequest(false, HUB)
+
+ const writes = writesOf(sensor)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+
+ // The refused report names a sensor the camera does not have beside its own, and reads neither.
+ camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid, UNKNOWN])
+
+ expect(writes).toEqual([])
+ expect(warn).not.toHaveBeenCalled()
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false)
+
+ // Motion the plugin writes directly is stored as no motion, and a reported clear lists none.
+ sensor.updateCharacteristic(Characteristic.MotionDetected, true)
+
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false)
+
+ camera.updateMotionDetected(false)
+
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false)
+ expect(listed(sensor)).toEqual([])
+ })
+
+ it.each(WRITERS)('stores no motion for motion written by $writer, which the clip path does not hear and a read answers as none', async ({
+ read,
+ write,
+ }) => {
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+
+ await sensor.getCharacteristic(Characteristic.MotionEnabled).handleSetRequest(false, HUB)
+
+ const clip = vi.spyOn(CMAFRecordingManagement.prototype, 'motionChanged')
+ const forwarded = motionForwarded(sensor)
+ const motionDetected = sensor.getCharacteristic(Characteristic.MotionDetected)
+
+ await write(sensor)
+
+ expect(motionDetected.value).toBe(false)
+ // A write forwards one change of no motion to no motion, and a read handler's answer forwards none.
+ expect(forwarded).toEqual(read
+ ? []
+ : [
+ {
+ newValue: false,
+ oldValue: false,
+ },
+ ])
+ expect(listed(sensor)).toEqual([])
+ expect(clip).not.toHaveBeenCalled()
+ expect(await motionDetected.handleGetRequest(HUB)).toBe(false)
+ })
+
+ it('answers no motion to a hub\'s read of motion assigned directly to motion detected\'s value, with no read handler', async () => {
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+ const motionDetected = sensor.getCharacteristic(Characteristic.MotionDetected)
+
+ await sensor.getCharacteristic(Characteristic.MotionEnabled).handleSetRequest(false, HUB)
+ motionDetected.value = true
+
+ expect(await motionDetected.handleGetRequest(HUB)).toBe(false)
+ })
+
+ it('clears standing motion at a hub write of motion enabled off, writing an empty list and then motion detected false, and hands the clip path '
+ + 'the clear', async () => {
+ const clip = vi.spyOn(CMAFRecordingManagement.prototype, 'motionChanged')
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+
+ camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid])
+
+ const writes = writesOf(sensor)
+
+ await sensor.getCharacteristic(Characteristic.MotionEnabled).handleSetRequest(false, HUB)
+
+ expect(writes).toEqual(['contributing sensors', 'motion detected'])
+ expect(listed(sensor)).toEqual([])
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false)
+ expect(clip.mock.calls).toEqual([
+ [true],
+ [false],
+ ])
+ })
+
+ it('clears the motion a cached accessory restored standing at a restore of motion enabled off', () => {
+ const { camera, sensor } = restoredStanding(true)
+
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(true)
+ expect(listed(sensor)).toEqual([FIRST, SECOND])
+
+ camera.deserialize({
+ streamManagements: [],
+ operatingMode: {
+ ...camera.serialize()!.operatingMode!,
+ motionEnabled: false,
+ },
+ })
+
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false)
+ expect(listed(sensor)).toEqual([])
+ })
+
+ it('clears the motion a cached accessory restored standing beside motion enabled off at its configure, with no stored operating mode', () => {
+ const { sensor } = restoredStanding(false)
+
+ expect(sensor.getCharacteristic(Characteristic.MotionEnabled).value).toBe(false)
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false)
+ expect(listed(sensor)).toEqual([])
+ })
+
+ it('raises nothing as motion enabled turns on again, and the next report of motion passes', async () => {
+ const camera = cameraOf()
+ configured(camera)
+ const sensor = camera.motionService!
+ const motionEnabled = sensor.getCharacteristic(Characteristic.MotionEnabled)
+
+ await motionEnabled.handleSetRequest(false, HUB)
+ camera.updateMotionDetected(true)
+
+ const writes = writesOf(sensor)
+
+ await motionEnabled.handleSetRequest(true, HUB)
+
+ expect(writes).toEqual([])
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false)
+
+ camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid])
+
+ expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(true)
+ expect(listed(sensor)).toEqual([SECOND])
+ })
+ })
+
+ it('serializes the base fields alone in the operating mode of a camera without the block', () => {
+ const camera = cameraOf(createCameraControllerOptions())
+ configured(camera)
+
+ expect(Object.keys(camera.serialize()!.operatingMode!)).toEqual([
+ 'recordingActive',
+ 'recordingAudioActive',
+ 'eventSnapshotsActive',
+ 'homeKitCameraActive',
+ 'periodicSnapshotsActive',
+ ])
+ })
+ })
+})
diff --git a/src/lib/camera/MotionAttribution.ts b/src/lib/camera/MotionAttribution.ts
new file mode 100644
index 000000000..299a366df
--- /dev/null
+++ b/src/lib/camera/MotionAttribution.ts
@@ -0,0 +1,143 @@
+import type { MotionSensor } from '../definitions/index.js'
+import type { CameraReporter } from './diagnostics/CameraReporter.js'
+
+import { Characteristic } from '../Characteristic.js'
+import { admitsValue } from '../util/valueGuard.js'
+import { encodeContributingSensors } from './capabilities/cameraSensors.js'
+
+/**
+ * The owner of a camera's motion sensor's Contributing Sensors, whether the camera controller built the sensor or the plugin supplied it. The list names the
+ * video sensors that contribute to the motion currently detected. It follows Motion Detected: motion a plugin raises by writing Motion Detected without
+ * naming sensors belongs to every video sensor, and motion at rest lists none. A report writes the list before Motion Detected, and the camera controller
+ * hands the attribution each edge of Motion Detected from its one listener, registered ahead of the service's own: a direct write's list is written
+ * before the service forwards the motion change too, and a hub that reads the list on the motion notification finds it. A sensor whose Contributing Sensors
+ * a plugin removes gets no list, because the attribution writes only the characteristic it took at its construction.
+ */
+export class MotionAttribution {
+ private readonly motionDetected: Characteristic
+ private readonly contributingSensors: Characteristic
+
+ /**
+ * The camera's reporter, through which a value of a report the attribution cannot place is a refused value of the camera's.
+ */
+ private readonly reporter: CameraReporter
+
+ /**
+ * The video sensors' UUIDs in the registry's order, in lowercase.
+ */
+ private readonly sensorUUIDs: readonly string[]
+
+ /**
+ * Set while a report writes Motion Detected. The edge the write causes leaves the list the report wrote.
+ */
+ private reporting = false
+
+ /**
+ * Adds Contributing Sensors when the sensor lacks it and writes it from the sensor's current Motion Detected, which means a cached list is corrected.
+ * @param motionSensor - The camera's motion sensor.
+ * @param sensorUUIDs - The video sensors' UUIDs in the registry's order, in lowercase.
+ * @param reporter - The camera's reporter.
+ */
+ constructor(motionSensor: MotionSensor, sensorUUIDs: readonly string[], reporter: CameraReporter) {
+ this.sensorUUIDs = sensorUUIDs
+ this.reporter = reporter
+ this.motionDetected = motionSensor.getCharacteristic(Characteristic.MotionDetected)
+ this.contributingSensors = motionSensor.getCharacteristic(Characteristic.ContributingSensors)
+ this.write(this.motionDetected.value
+ ? sensorUUIDs
+ : [])
+ }
+
+ /**
+ * Raises or clears motion and names the video sensors that saw it, writing Contributing Sensors and then Motion Detected when it moves. Detected motion
+ * lists each named sensor the camera has once, in the registry's order, whatever the case of its UUID, and a report that names none it has lists every
+ * sensor. An entry that names no sensor of the camera, or that is no string, is left out with one value-refused problem, and a value that is no list
+ * names none. Cleared motion lists none and reads no names. Motion the guard of Motion Detected does not store, motion while Motion Enabled reads off,
+ * is asked of that guard first, and its report writes no characteristic, reads no names and raises no problem.
+ * @param detected - Whether motion is detected.
+ * @param sensorUUIDs - The video sensors that saw the motion.
+ */
+ report(detected: boolean, sensorUUIDs?: readonly string[]): void {
+ if (!admitsValue(this.motionDetected, detected)) {
+ return
+ }
+
+ this.write(detected
+ ? this.attributed(sensorUUIDs)
+ : [])
+
+ if (!!this.motionDetected.value === detected) {
+ return
+ }
+
+ this.reporting = true
+
+ try {
+ this.motionDetected.updateValue(detected)
+ } finally {
+ this.reporting = false
+ }
+ }
+
+ /**
+ * Takes an edge of Motion Detected, which the camera controller hands it only when the value moves. A write that leaves it as it stands keeps a list
+ * a report named. A direct write of Motion Detected attributes the motion to every video sensor, and an edge a report causes leaves the list the report
+ * wrote.
+ * @param detected - Whether motion is detected.
+ */
+ motionChanged(detected: boolean): void {
+ if (this.reporting) {
+ return
+ }
+
+ this.write(detected
+ ? this.sensorUUIDs
+ : [])
+ }
+
+ // The named sensors the camera has, in the registry's order. A plugin's runtime value takes the report-and-coerce path rather than a throw: an entry
+ // the camera cannot place is left out with a value-refused problem and a value that is no list names none.
+ private attributed(named: unknown): readonly string[] {
+ if (named === undefined) {
+ return this.sensorUUIDs
+ }
+
+ if (!Array.isArray(named)) {
+ this.refused(`A motion report named its video sensors with ${String(named)}, which is no list. The motion belongs to every video sensor.`)
+ return this.sensorUUIDs
+ }
+
+ const known = new Set()
+
+ for (const entry of named) {
+ if (typeof entry !== 'string') {
+ this.refused(`A motion report named the video sensor ${String(entry)}, which is no sensor UUID, and the report leaves it out.`)
+ continue
+ }
+
+ const sensorUUID = entry.toLowerCase()
+
+ if (!this.sensorUUIDs.includes(sensorUUID)) {
+ this.refused(`A motion report named the video sensor "${entry}", which the camera does not have, and the report leaves it out.`)
+ continue
+ }
+
+ known.add(sensorUUID)
+ }
+
+ return known.size === 0
+ ? this.sensorUUIDs
+ : this.sensorUUIDs.filter(sensorUUID => known.has(sensorUUID))
+ }
+
+ // Reports a value of a motion report the attribution cannot place as a refused value of the camera's, at the level the console warns at.
+ private refused(sentence: string): void {
+ this.reporter.problem({ kind: 'value-refused', level: 'warning', sentence })
+ }
+
+ private write(sensorUUIDs: readonly string[]): void {
+ const sensorList = sensorUUIDs.map(sensorUUID => ({ sensorUUID }))
+
+ this.contributingSensors.updateValue(encodeContributingSensors({ sensorList }))
+ }
+}
diff --git a/src/lib/camera/MotionZonesManagement.spec.ts b/src/lib/camera/MotionZonesManagement.spec.ts
new file mode 100644
index 000000000..374dc529f
--- /dev/null
+++ b/src/lib/camera/MotionZonesManagement.spec.ts
@@ -0,0 +1,1323 @@
+import type { Deferred } from '../../test-utils/settle.js'
+import type { CameraControllerCapabilitiesOptions, CameraControllerOptions, CameraControllerServiceMap } from '../controller/index.js'
+import type { CameraMotionZones } from '../definitions/index.js'
+import type { CameraZonePolygon, CameraZoneVertex } from './capabilities/index.js'
+import type { MotionZonesManagementState } from './MotionZonesManagement.js'
+
+import { Buffer } from 'node:buffer'
+import { getEventListeners } from 'node:events'
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ buildEmitterConnection,
+ capabilitiesCameraOptions,
+ createCameraControllerOptions,
+ FIRST_VIDEO_SENSOR,
+ idleStreaming,
+ motionZonesFunction,
+ savedMapOf,
+ SECOND_VIDEO_SENSOR,
+ twoSensorCameraOptions,
+ webRTCStreamingOptions,
+} from '../../test-utils/cameraFixtures.js'
+import { detachedReporter } from '../../test-utils/reporterFixtures.js'
+import { deferred, fakeTimeoutSignals, settle } from '../../test-utils/settle.js'
+import { Characteristic } from '../Characteristic.js'
+import { CameraController } from '../controller/index.js'
+import { HAPStatus } from '../HAPServer.js'
+import { Service } from '../Service.js'
+import { HAPConnectionEvent } from '../util/eventedhttp.js'
+import { CAMERA_SPECIFICATION_VERSION } from './capabilities/cameraSensors.js'
+import { CameraZoneApplicationMethod } from './capabilities/index.js'
+import { decodeCameraZones, encodeCameraZones } from './capabilities/zones.js'
+import { MotionZonesManagement } from './MotionZonesManagement.js'
+import { DELEGATE_CALL_TIMEOUT } from './session/settleWithin.js'
+
+// The first and the second video sensor's UUIDs in lowercase, as the registry keys them.
+const FIRST = FIRST_VIDEO_SENSOR.uuid.toLowerCase()
+const SECOND = SECOND_VIDEO_SENSOR.uuid.toLowerCase()
+
+// The zone identifier the rows draw with.
+const ZONE = 'a0000001-0000-4000-8000-00000000000a'
+
+// The Camera Zones value a service starts with, Zone Data Version 2 with no entry, built through the codec as every value here is.
+const DEFAULT_ZONES = encodeCameraZones({ zoneDataVersion: 2, zoneData: [] })
+const DEFAULT_STATE: MotionZonesManagementState = { active: true, zones: DEFAULT_ZONES }
+
+function polygon(identifier: string, vertices: CameraZoneVertex[]): CameraZonePolygon {
+ return { identifier, vertices }
+}
+
+// A Camera Zones value holding one Zone Data entry of the given polygons.
+function zonesValue(...polygons: CameraZonePolygon[]): string {
+ return encodeCameraZones({
+ zoneDataVersion: 2,
+ zoneData: [
+ { method: CameraZoneApplicationMethod.NORMAL, polygons },
+ ],
+ })
+}
+
+// A triangle inside each fixture sensor's dimensions, and the Zone Data the sensor's function is handed for it.
+const TRIANGLE = zonesValue(polygon(ZONE, [
+ [0, 0],
+ [100, 0],
+ [0, 100],
+]))
+const TRIANGLE_DATA = decodeCameraZones(TRIANGLE).zoneData
+
+// A write's answer once it arrives, recorded rather than awaited. A row reads whether a write is still waiting: the status it was refused or failed
+// with, or resolved.
+function answerOf(write: Promise): { answer?: 'resolved' | HAPStatus } {
+ const record: { answer?: 'resolved' | HAPStatus } = {}
+
+ write.then(() => {
+ record.answer = 'resolved'
+ }, (status: HAPStatus) => {
+ record.answer = status
+ })
+
+ return record
+}
+
+// The managements a row builds, destroyed after it.
+const managements: MotionZonesManagement[] = []
+
+afterEach(() => {
+ for (const management of managements.splice(0)) {
+ management.destroy()
+ }
+
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+// A management over the first sensor's dimensions, its motionZones function the fixture's and its saves recorded, over the given saved service or a new one.
+function harness(service?: CameraMotionZones): {
+ management: MotionZonesManagement
+ motionZones: ReturnType
+ saves: ReturnType
+ service: CameraMotionZones
+ active: Characteristic
+ zones: Characteristic
+} {
+ const motionZones = motionZonesFunction()
+ const saves = vi.fn()
+ const management = new MotionZonesManagement({
+ motionZones,
+ reporter: detachedReporter(),
+ sensorUUID: FIRST_VIDEO_SENSOR.uuid,
+ sensorDimensions: { ...FIRST_VIDEO_SENSOR.dimensions },
+ }, service)
+ management.setupStateChangeDelegate(saves)
+ managements.push(management)
+
+ const built = management.getService()
+
+ return {
+ management,
+ motionZones,
+ saves,
+ service: built,
+ active: built.getCharacteristic(Characteristic.Active),
+ zones: built.getCharacteristic(Characteristic.CameraZones),
+ }
+}
+
+/* A Camera Zones write of the triangle over a fresh harness, whose function call returns a held promise that a factory reset follows the given number of
+ * no-op continuations deep, as a plugin's own continuation on the call it was handed can run one. The write waits on the call before the row releases it,
+ * and its answer is the status it failed with, or resolved.
+ */
+async function writeWithResetAfterSettling(depth: number): Promise & { answer: 'resolved' | HAPStatus }> {
+ const built = harness()
+ const held = deferred()
+
+ built.motionZones.mockImplementationOnce(() => {
+ let continuation: Promise = held.promise
+
+ for (let turn = 0; turn < depth; turn++) {
+ continuation = continuation.then(() => undefined)
+ }
+
+ void continuation.then(() => built.management.handleFactoryReset())
+
+ return held.promise
+ })
+
+ const write = built.zones.handleSetRequest(TRIANGLE, buildEmitterConnection()).then(() => 'resolved' as const, (status: HAPStatus) => status)
+ await settle()
+ held.resolve()
+ const answer = await write
+ await settle()
+
+ return { ...built, answer }
+}
+
+describe('motionZonesManagement', () => {
+ // The listener collects each rejection no handler takes during a row, any of which would end a Homebridge process.
+ const unhandled: unknown[] = []
+ const collect = (reason: unknown): void => {
+ unhandled.push(reason)
+ }
+
+ beforeEach(() => {
+ unhandled.length = 0
+ process.on('unhandledRejection', collect)
+ })
+
+ afterEach(() => {
+ process.off('unhandledRejection', collect)
+ })
+
+ describe('the service', () => {
+ it('builds the service under the lowercase sensor UUID with the spec version, active on and no zone, and gives an adopted one the defaults', () => {
+ const { management, service, active, zones } = harness()
+
+ expect(service.UUID).toBe(Service.CameraMotionZones.UUID)
+ expect(service.subtype).toBe(FIRST)
+ expect(service.getCharacteristic(Characteristic.Version).value).toBe(CAMERA_SPECIFICATION_VERSION)
+ expect(active.value).toBe(Characteristic.Active.ACTIVE)
+ expect(decodeCameraZones(zones.value as string)).toEqual({ zoneDataVersion: 2, zoneData: [] })
+ expect(management.serviceKey).toBe(`cameraCapabilities:motionZones:${FIRST}`)
+ expect(MotionZonesManagement.serviceKey(FIRST_VIDEO_SENSOR.uuid)).toBe(`cameraCapabilities:motionZones:${FIRST}`)
+
+ const saved = new Service.CameraMotionZones('', FIRST)
+ saved.updateCharacteristic(Characteristic.Active, Characteristic.Active.INACTIVE)
+ saved.updateCharacteristic(Characteristic.CameraZones, TRIANGLE)
+ const adopted = harness(saved)
+
+ expect(adopted.service).toBe(saved)
+ expect(adopted.active.value).toBe(Characteristic.Active.ACTIVE)
+ expect(adopted.zones.value).toBe(DEFAULT_ZONES)
+ expect(saved.getCharacteristic(Characteristic.Version).value).toBe(CAMERA_SPECIFICATION_VERSION)
+ expect(adopted.management.serialize()).toEqual(DEFAULT_STATE)
+ })
+ })
+
+ describe('writes', () => {
+ // Each value a write is refused for, and the error class the decoder throws for the ones it cannot decode.
+ const refusals: { name: string, value: string, decoderError?: ErrorConstructor }[] = [
+ {
+ name: 'a value without its zone data version',
+ value: Buffer.from([0x02, 0x00]).toString('base64'),
+ decoderError: TypeError,
+ },
+ {
+ name: 'a zone data version other than 2',
+ value: encodeCameraZones({ zoneDataVersion: 1, zoneData: [] }),
+ decoderError: RangeError,
+ },
+ {
+ name: 'a value whose framing is cut short',
+ value: Buffer.from([0x01, 0x05, 0x02]).toString('base64'),
+ decoderError: Error,
+ },
+ {
+ name: 'a polygon of two vertices',
+ value: zonesValue(polygon(ZONE, [
+ [0, 0],
+ [10, 10],
+ ])),
+ },
+ {
+ name: 'a vertex beyond the sensor\'s width',
+ value: zonesValue(polygon(ZONE, [
+ [0, 0],
+ [1921, 0],
+ [0, 10],
+ ])),
+ },
+ {
+ name: 'a vertex beyond the sensor\'s height',
+ value: zonesValue(polygon(ZONE, [
+ [0, 0],
+ [10, 0],
+ [0, 1081],
+ ])),
+ },
+ {
+ name: 'an identifier repeated within the value',
+ value: zonesValue(polygon(ZONE, [
+ [0, 0],
+ [100, 0],
+ [0, 100],
+ ]), polygon(ZONE, [
+ [5, 5],
+ [50, 5],
+ [5, 50],
+ ])),
+ },
+ ]
+
+ it.each(refusals)('refuses $name with one warning, no delegate call and no save, a read answering the zones in force', async ({ value, decoderError }) => {
+ // The decoder throws the row's class for a value it cannot decode and nothing for one a rule refuses.
+ let thrown: unknown
+
+ try {
+ decodeCameraZones(value)
+ } catch (error) {
+ thrown = error
+ }
+
+ expect((thrown as Error | undefined)?.constructor).toBe(decoderError)
+
+ const { management, motionZones, saves, zones } = harness()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+
+ await expect(zones.handleSetRequest(value, buildEmitterConnection())).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST)
+
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(warn.mock.calls[0][0]).toContain(FIRST)
+ expect(motionZones).not.toHaveBeenCalled()
+ expect(zones.value).toBe(DEFAULT_ZONES)
+ expect(management.serialize()).toEqual(DEFAULT_STATE)
+ expect(saves).not.toHaveBeenCalled()
+ expect(await zones.handleGetRequest()).toBe(DEFAULT_ZONES)
+ })
+
+ const accepted: { name: string, value: string }[] = [
+ {
+ name: 'an empty zone list',
+ value: encodeCameraZones({ zoneDataVersion: 2, zoneData: [] }),
+ },
+ {
+ name: 'a zone data entry with no polygons',
+ value: zonesValue(),
+ },
+ {
+ name: 'a vertex at exactly the sensor\'s width and height',
+ value: zonesValue(polygon(ZONE, [
+ [0, 0],
+ [1920, 0],
+ [1920, 1080],
+ ])),
+ },
+ ]
+
+ it.each(accepted)('accepts $name, telling the delegate once, then setting the value and saving once', async ({ value }) => {
+ const { management, motionZones, saves, zones } = harness()
+
+ await zones.handleSetRequest(value, buildEmitterConnection())
+
+ expect(motionZones.mock.calls).toEqual([
+ [
+ { active: true, zoneData: decodeCameraZones(value).zoneData },
+ 'write',
+ expect.any(AbortSignal),
+ ],
+ ])
+ expect(zones.value).toBe(value)
+ expect(management.serialize()).toEqual({ active: true, zones: value })
+ expect(saves).toHaveBeenCalledTimes(1)
+ })
+
+ it('tells the delegate the zones in force and active off at a write of active 0, then sets it and saves once', async () => {
+ const { management, motionZones, saves, active, zones } = harness()
+ await zones.handleSetRequest(TRIANGLE, buildEmitterConnection())
+ motionZones.mockClear()
+ saves.mockClear()
+
+ await active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())
+
+ expect(motionZones.mock.calls).toEqual([
+ [
+ { active: false, zoneData: TRIANGLE_DATA },
+ 'write',
+ expect.any(AbortSignal),
+ ],
+ ])
+ expect(active.value).toBe(Characteristic.Active.INACTIVE)
+ expect(management.serialize()).toEqual({ active: false, zones: TRIANGLE })
+ expect(saves).toHaveBeenCalledTimes(1)
+ })
+
+ it('fails a write the delegate rejects, logging it once and keeping the zones in force, which a read answers', async () => {
+ const { management, motionZones, saves, zones } = harness()
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ motionZones.mockRejectedValueOnce(new Error('The detector failed.'))
+
+ await expect(zones.handleSetRequest(TRIANGLE, buildEmitterConnection())).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ await settle()
+
+ expect(error.mock.calls).toEqual([
+ [
+ expect.stringContaining(`The motionZones function failed to apply a write of the motion zones of video sensor ${FIRST}: Error: The detector failed.`),
+ ],
+ ])
+ expect(zones.value).toBe(DEFAULT_ZONES)
+ expect(management.serialize()).toEqual(DEFAULT_STATE)
+ expect(saves).not.toHaveBeenCalled()
+ expect(await zones.handleGetRequest()).toBe(DEFAULT_ZONES)
+ expect(unhandled).toEqual([])
+ })
+
+ it('fails a write the delegate never settles at the delegate call bound with one warning, and runs the next write', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const { management, motionZones, saves, active, zones } = harness()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ motionZones.mockReturnValueOnce(deferred().promise)
+
+ const write = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection()))
+ await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT - 1)
+
+ expect(write.answer).toBeUndefined()
+
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect(write.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(warn.mock.calls[0][0]).toContain(FIRST)
+ expect(warn.mock.calls[0][0]).toContain(`within ${DELEGATE_CALL_TIMEOUT / 1000} seconds`)
+ expect(zones.value).toBe(DEFAULT_ZONES)
+ expect(management.serialize()).toEqual(DEFAULT_STATE)
+ expect(saves).not.toHaveBeenCalled()
+ expect(await zones.handleGetRequest()).toBe(DEFAULT_ZONES)
+
+ await active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())
+
+ expect(motionZones).toHaveBeenCalledTimes(2)
+ expect(management.serialize()).toEqual({ active: false, zones: DEFAULT_ZONES })
+ expect(saves).toHaveBeenCalledTimes(1)
+ })
+
+ it('hands the delegate a zones write and an active write behind it in arrival order, the second seeing the first\'s zones', async () => {
+ const { motionZones, active, zones } = harness()
+ const held = deferred()
+ motionZones.mockReturnValueOnce(held.promise)
+
+ const first = zones.handleSetRequest(TRIANGLE, buildEmitterConnection())
+ const second = active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())
+ await settle()
+
+ expect(motionZones).toHaveBeenCalledTimes(1)
+
+ held.resolve()
+ await first
+ await second
+
+ expect(motionZones.mock.calls).toEqual([
+ [
+ { active: true, zoneData: TRIANGLE_DATA },
+ 'write',
+ expect.any(AbortSignal),
+ ],
+ [
+ { active: false, zoneData: TRIANGLE_DATA },
+ 'write',
+ expect.any(AbortSignal),
+ ],
+ ])
+ })
+
+ it('saves nothing for an accepted write once the state-change delegate is cleared', async () => {
+ const { management, saves, zones } = harness()
+ management.setupStateChangeDelegate(undefined)
+
+ await zones.handleSetRequest(TRIANGLE, buildEmitterConnection())
+
+ expect(management.serialize()).toEqual({ active: true, zones: TRIANGLE })
+ expect(saves).not.toHaveBeenCalled()
+ })
+
+ it('applies a write whose delegate settles after the accessory would have answered it as timed out and inside the bound', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const { motionZones, saves, zones } = harness()
+ const held = deferred()
+ motionZones.mockReturnValueOnce(held.promise)
+
+ // The accessory answers a write it is still waiting on as timed out once its warning and its timeout after the warning have passed.
+ const write = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection()))
+ await vi.advanceTimersByTimeAsync(10 * 1000)
+
+ expect(write.answer).toBeUndefined()
+
+ held.resolve()
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(write.answer).toBe('resolved')
+ expect(zones.value).toBe(TRIANGLE)
+ expect(saves).toHaveBeenCalledTimes(1)
+ })
+
+ it('applies a write whose connection closes while the delegate holds it and saves once', async () => {
+ const { motionZones, saves, zones } = harness()
+ const connection = buildEmitterConnection()
+ const held = deferred()
+ motionZones.mockReturnValueOnce(held.promise)
+
+ const write = answerOf(zones.handleSetRequest(TRIANGLE, connection))
+ await settle()
+ connection.emit(HAPConnectionEvent.CLOSED)
+ held.resolve()
+ await settle()
+
+ expect(write.answer).toBe('resolved')
+ expect(zones.value).toBe(TRIANGLE)
+ expect(saves).toHaveBeenCalledTimes(1)
+ })
+
+ it('refuses a write behind a held one at once, before the held write settles, with no delegate call', async () => {
+ const { motionZones, zones } = harness()
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const held = deferred()
+ motionZones.mockReturnValueOnce(held.promise)
+
+ const first = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection()))
+ await settle()
+ const refused = answerOf(zones.handleSetRequest(zonesValue(polygon(ZONE, [
+ [0, 0],
+ [10, 10],
+ ])), buildEmitterConnection()))
+ await settle()
+
+ expect(refused.answer).toBe(HAPStatus.INVALID_VALUE_IN_REQUEST)
+ expect(first.answer).toBeUndefined()
+ expect(motionZones).toHaveBeenCalledTimes(1)
+
+ held.resolve()
+ await settle()
+
+ expect(first.answer).toBe('resolved')
+ })
+
+ it('gives a write queued behind one the delegate holds for most of the bound its own whole bound, counted from its delegate call', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const { management, motionZones, saves, active, zones } = harness()
+ const firstHeld = deferred()
+ const secondHeld = deferred()
+ motionZones.mockReturnValueOnce(firstHeld.promise).mockReturnValueOnce(secondHeld.promise)
+
+ const first = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection()))
+ const second = answerOf(active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection()))
+ await vi.advanceTimersByTimeAsync(25 * 1000)
+ firstHeld.resolve()
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(first.answer).toBe('resolved')
+ expect(motionZones).toHaveBeenCalledTimes(2)
+
+ // The second write arrived with the first, and a bound counted from its arrival would have cut it here.
+ await vi.advanceTimersByTimeAsync(10 * 1000)
+
+ expect(second.answer).toBeUndefined()
+
+ secondHeld.resolve()
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(second.answer).toBe('resolved')
+ expect(management.serialize()).toEqual({ active: false, zones: TRIANGLE })
+ expect(saves).toHaveBeenCalledTimes(2)
+ })
+ })
+
+ describe('owner surface', () => {
+ it('restores a valid slice without a save, telling the delegate unawaited, and keeps the defaults with one warning for a slice it refuses', async () => {
+ const { management, motionZones, saves, active, zones } = harness()
+ motionZones.mockReturnValueOnce(deferred().promise)
+ const slice: MotionZonesManagementState = { active: false, zones: TRIANGLE }
+
+ management.deserialize(slice)
+
+ expect(active.value).toBe(Characteristic.Active.INACTIVE)
+ expect(zones.value).toBe(TRIANGLE)
+ expect(management.serialize()).toEqual(slice)
+ expect(saves).not.toHaveBeenCalled()
+ expect(motionZones.mock.calls).toEqual([
+ [
+ { active: false, zoneData: TRIANGLE_DATA },
+ 'restore',
+ expect.any(AbortSignal),
+ ],
+ ])
+
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+
+ for (const refused of [
+ { active: 'false', zones: TRIANGLE },
+ {
+ active: true,
+ zones: Buffer.from([0x01, 0x05, 0x02]).toString('base64'),
+ },
+ {
+ active: true,
+ zones: zonesValue(polygon(ZONE, [
+ [0, 0],
+ [2000, 0],
+ [0, 10],
+ ])),
+ },
+ ]) {
+ const restored = harness()
+ warn.mockClear()
+
+ restored.management.deserialize(refused as unknown as MotionZonesManagementState)
+
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(warn.mock.calls[0][0]).toContain(FIRST)
+ expect(restored.management.serialize()).toEqual(DEFAULT_STATE)
+ expect(restored.active.value).toBe(Characteristic.Active.ACTIVE)
+ expect(restored.zones.value).toBe(DEFAULT_ZONES)
+ expect(restored.saves).not.toHaveBeenCalled()
+ expect(restored.motionZones.mock.calls).toEqual([
+ [
+ { active: true, zoneData: [] },
+ 'restore',
+ expect.any(AbortSignal),
+ ],
+ ])
+ }
+
+ const failing = harness()
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ failing.motionZones.mockRejectedValueOnce(new Error('The detector failed to restore.'))
+
+ failing.management.deserialize(slice)
+ await settle()
+
+ expect(error.mock.calls).toEqual([
+ [
+ expect.stringContaining(`The motionZones function failed to apply the restored motion zones of video sensor ${FIRST}: Error: The detector failed to restore.`),
+ ],
+ ])
+ expect(unhandled).toEqual([])
+ })
+
+ it('keeps the defaults with one warning for saved zones that are not canonical base64, though the bytes they decode to hold zones it accepts', () => {
+ const { management, motionZones, saves, active, zones } = harness()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+
+ // A line feed after the triangle's value, which Node's decoder skips: only the canonical check refuses it.
+ management.deserialize({ active: false, zones: `${TRIANGLE}\n` })
+
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(warn.mock.calls[0][0]).toContain(FIRST)
+ expect(warn.mock.calls[0][0]).toContain('not canonical base64')
+ expect(management.serialize()).toEqual(DEFAULT_STATE)
+ expect(active.value).toBe(Characteristic.Active.ACTIVE)
+ expect(zones.value).toBe(DEFAULT_ZONES)
+ expect(saves).not.toHaveBeenCalled()
+ expect(motionZones.mock.calls).toEqual([
+ [
+ { active: true, zoneData: [] },
+ 'restore',
+ expect.any(AbortSignal),
+ ],
+ ])
+ })
+
+ it('puts the defaults in force at a factory reset, saving once and telling the delegate, whose rejection is logged once', async () => {
+ const { management, motionZones, saves, active, zones } = harness()
+ await zones.handleSetRequest(TRIANGLE, buildEmitterConnection())
+ await active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())
+ motionZones.mockClear()
+ saves.mockClear()
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ motionZones.mockRejectedValueOnce(new Error('The detector failed to reset.'))
+
+ management.handleFactoryReset()
+ await settle()
+
+ expect(active.value).toBe(Characteristic.Active.ACTIVE)
+ expect(zones.value).toBe(DEFAULT_ZONES)
+ expect(management.serialize()).toEqual(DEFAULT_STATE)
+ expect(saves).toHaveBeenCalledTimes(1)
+ expect(motionZones.mock.calls).toEqual([
+ [
+ { active: true, zoneData: [] },
+ 'reset',
+ expect.any(AbortSignal),
+ ],
+ ])
+ expect(error.mock.calls).toEqual([
+ [
+ expect.stringContaining(`The motionZones function failed to apply the reset motion zones of video sensor ${FIRST}: Error: The detector failed to reset.`),
+ ],
+ ])
+ expect(unhandled).toEqual([])
+ })
+
+ it('fails a held write, a write queued behind it and a later write at a destroy, each without a further delegate call, destroyed twice', async () => {
+ const { management, motionZones, saves, active, zones } = harness()
+ const held = deferred()
+ motionZones.mockReturnValueOnce(held.promise)
+
+ const first = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection()))
+ const queued = answerOf(active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection()))
+ await settle()
+ management.destroy()
+ await settle()
+ const later = answerOf(active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection()))
+ await settle()
+
+ expect(first.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(queued.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(later.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(motionZones).toHaveBeenCalledTimes(1)
+ expect(management.serialize()).toEqual(DEFAULT_STATE)
+ expect(saves).not.toHaveBeenCalled()
+ expect(() => management.destroy()).not.toThrow()
+ })
+
+ it('fails a held write and a write queued behind it at a factory reset, the defaults standing, and applies a write that arrives after it', async () => {
+ const { management, motionZones, active, zones } = harness()
+ const held = deferred()
+ motionZones.mockReturnValueOnce(held.promise)
+
+ const first = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection()))
+ const queued = answerOf(active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection()))
+ await settle()
+ management.handleFactoryReset()
+ await settle()
+
+ expect(first.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(queued.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(motionZones.mock.calls.map(([, reason]) => reason)).toEqual([
+ 'write',
+ 'reset',
+ ])
+ expect(zones.value).toBe(DEFAULT_ZONES)
+ expect(await zones.handleGetRequest()).toBe(DEFAULT_ZONES)
+ expect(await active.handleGetRequest()).toBe(Characteristic.Active.ACTIVE)
+
+ held.resolve()
+ await settle()
+
+ expect(management.serialize()).toEqual(DEFAULT_STATE)
+
+ await active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())
+
+ expect(motionZones).toHaveBeenCalledTimes(3)
+ expect(management.serialize()).toEqual({ active: false, zones: DEFAULT_ZONES })
+ })
+
+ // The depths run from a reset that lands while the write still waits on the call, through the turns its wait takes to resume, to one that lands after it.
+ const resetDepths = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+
+ it.each(resetDepths)('keeps the defaults at a factory reset hung at depth %i on a zones write\'s delegate call, which hears the reset last', async (depth) => {
+ const { management, motionZones, zones } = await writeWithResetAfterSettling(depth)
+
+ expect(management.serialize()).toEqual(DEFAULT_STATE)
+ expect(await zones.handleGetRequest()).toBe(DEFAULT_ZONES)
+ expect(motionZones.mock.calls.map(([, reason]) => reason)).toEqual([
+ 'write',
+ 'reset',
+ ])
+ })
+
+ it('fails a zones write whose delegate call settled when a factory reset ran before the write\'s turn resumed, saving the reset alone', async () => {
+ const { answer, management, saves } = await writeWithResetAfterSettling(3)
+
+ expect(answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(management.serialize()).toEqual(DEFAULT_STATE)
+ expect(saves).toHaveBeenCalledTimes(1)
+ })
+
+ it('fails a held active write and a camera zones write queued behind it at a factory reset, the default zones standing', async () => {
+ const { management, motionZones, active, zones } = harness()
+ const held = deferred()
+ motionZones.mockReturnValueOnce(held.promise)
+
+ const first = answerOf(active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection()))
+ const queued = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection()))
+ await settle()
+ management.handleFactoryReset()
+ held.resolve()
+ await settle()
+
+ expect(first.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(queued.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(management.serialize()).toEqual(DEFAULT_STATE)
+ expect(await zones.handleGetRequest()).toBe(DEFAULT_ZONES)
+ expect(motionZones.mock.calls.map(([, reason]) => reason)).toEqual([
+ 'write',
+ 'reset',
+ ])
+ })
+ })
+
+ describe('a call\'s signal', () => {
+ // The listeners the management's current generation holds on its abort signal.
+ function generationListeners(management: MotionZonesManagement): number {
+ // @ts-expect-error: private access
+ return getEventListeners(management.generation.signal, 'abort').length
+ }
+
+ // Each way a row ends a management: a factory reset and a destroy.
+ const ENDS: ((management: MotionZonesManagement) => void)[] = [
+ management => management.handleFactoryReset(),
+ management => management.destroy(),
+ ]
+
+ it('hands a write\'s call a signal of its own, aborted while the call is unsettled at its bound, a factory reset and a destroy, each failing the write, '
+ + 'and never once the call settled, a rejection after the abort writing no line', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+
+ // A call still unsettled at its bound.
+ const bounded = harness()
+ const boundedCall = deferred()
+ bounded.motionZones.mockReturnValueOnce(boundedCall.promise)
+ const boundedWrite = answerOf(bounded.zones.handleSetRequest(TRIANGLE, buildEmitterConnection()))
+ await settle()
+ const boundedSignal = bounded.motionZones.mock.calls[0][2]
+
+ await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT - 1)
+
+ expect(boundedSignal.aborted).toBe(false)
+
+ await vi.advanceTimersByTimeAsync(1)
+ boundedCall.reject(new Error('The detector stopped.'))
+ await settle()
+
+ expect(boundedSignal.aborted).toBe(true)
+ expect(boundedWrite.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(warn).toHaveBeenCalledTimes(1)
+
+ // A call still unsettled at a factory reset and at a destroy, the reset's own call of the function finding the write's signal aborted already and
+ // handed a signal of its own, which is not aborted.
+ const abortedAtResetCall: boolean[] = []
+ const resetCallSignals: [aborted: boolean, isTheWrites: boolean][] = []
+
+ for (const end of ENDS) {
+ const built = harness()
+ built.motionZones.mockReturnValueOnce(deferred().promise)
+ const write = answerOf(built.zones.handleSetRequest(TRIANGLE, buildEmitterConnection()))
+ await settle()
+ const signal = built.motionZones.mock.calls[0][2]
+
+ built.motionZones.mockImplementationOnce(async (_zones, _reason, own) => {
+ abortedAtResetCall.push(signal.aborted)
+ resetCallSignals.push([own.aborted, own === signal])
+ })
+
+ expect(signal.aborted).toBe(false)
+
+ end(built.management)
+ await settle()
+
+ expect(signal.aborted).toBe(true)
+ expect(write.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ }
+
+ expect(abortedAtResetCall).toEqual([true])
+ expect(resetCallSignals).toEqual([
+ [false, false],
+ ])
+
+ // A call that settles, by its value and by its rejection, before its bound, a factory reset or a destroy.
+ const settlings: ((call: Deferred) => void)[] = [
+ call => call.resolve(),
+ call => call.reject(new Error('The detector failed.')),
+ ]
+
+ for (const settles of settlings) {
+ const built = harness()
+ const call = deferred()
+ built.motionZones.mockReturnValueOnce(call.promise)
+ const write = built.zones.handleSetRequest(TRIANGLE, buildEmitterConnection()).catch(() => undefined)
+ await settle()
+ const signal = built.motionZones.mock.calls[0][2]
+
+ settles(call)
+ await write
+ await settle()
+
+ expect(generationListeners(built.management)).toBe(0)
+
+ await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT)
+ built.management.handleFactoryReset()
+ built.management.destroy()
+
+ expect(signal.aborted).toBe(false)
+ }
+
+ expect(error.mock.calls).toEqual([
+ [
+ expect.stringContaining(`The motionZones function failed to apply a write of the motion zones of video sensor ${FIRST}: Error: The detector failed.`),
+ ],
+ ])
+ expect(unhandled).toEqual([])
+ })
+
+ it('hands a restore\'s and a reset\'s call a signal of its own, which neither a later factory reset nor a destroy aborts, pending or settled, logging '
+ + 'each rejection', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const built = harness()
+ const restoreCall = deferred()
+ const resetCall = deferred()
+ built.motionZones.mockReturnValueOnce(restoreCall.promise).mockReturnValueOnce(resetCall.promise)
+
+ built.management.deserialize(DEFAULT_STATE)
+ built.management.handleFactoryReset()
+ built.management.handleFactoryReset()
+ built.management.destroy()
+ const [restoreSignal, resetSignal] = built.motionZones.mock.calls.map(([, , signal]) => signal)
+
+ expect([restoreSignal.aborted, resetSignal.aborted]).toEqual([false, false])
+
+ restoreCall.reject(new Error('The detector stopped restoring.'))
+ resetCall.reject(new Error('The detector stopped resetting.'))
+ await settle()
+
+ expect([restoreSignal.aborted, resetSignal.aborted]).toEqual([false, false])
+ expect(error.mock.calls).toEqual([
+ [
+ expect.stringContaining(`The motionZones function failed to apply the restored motion zones of video sensor ${FIRST}: Error: The detector stopped `
+ + 'restoring.'),
+ ],
+ [
+ expect.stringContaining(`The motionZones function failed to apply the reset motion zones of video sensor ${FIRST}: Error: The detector stopped `
+ + 'resetting.'),
+ ],
+ ])
+
+ const settled = harness()
+ settled.management.deserialize(DEFAULT_STATE)
+ await settle()
+ settled.management.handleFactoryReset()
+ await settle()
+ settled.management.handleFactoryReset()
+ await settle()
+ settled.management.destroy()
+
+ expect(settled.motionZones.mock.calls.map(([, , signal]) => signal.aborted)).toEqual([false, false, false])
+ expect(unhandled).toEqual([])
+ })
+
+ it('puts no listener on the generation\'s signal while a write\'s, a restore\'s and a reset\'s call are pending', async () => {
+ const built = harness()
+ built.motionZones.mockReturnValueOnce(deferred().promise).mockReturnValueOnce(deferred().promise).mockReturnValueOnce(deferred().promise)
+
+ built.management.deserialize(DEFAULT_STATE)
+ built.management.handleFactoryReset()
+ const write = answerOf(built.zones.handleSetRequest(TRIANGLE, buildEmitterConnection()))
+ await settle()
+
+ expect(built.motionZones.mock.calls.map(([, reason]) => reason)).toEqual([
+ 'restore',
+ 'reset',
+ 'write',
+ ])
+ expect(write.answer).toBeUndefined()
+ expect(generationListeners(built.management)).toBe(0)
+ })
+
+ it.each([
+ { end: 'a factory reset' },
+ { end: 'a destroy' },
+ ])('aborts a write\'s signal at $end the sensor\'s function sets off inside its own call, before it returns, the write failing and its rejection '
+ + 'writing no line', async ({ end }) => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const built = harness()
+ const call = deferred()
+ // What the write's signal reads as the reset's own call of the function is made, and as the reset or the destroy returns inside the write's call.
+ const read: { atResetCall?: boolean, atReturn?: boolean } = {}
+
+ built.motionZones.mockImplementationOnce(async (_zones, _reason, signal) => {
+ if (end === 'a factory reset') {
+ built.motionZones.mockImplementationOnce(async () => {
+ read.atResetCall = signal.aborted
+ })
+ built.management.handleFactoryReset()
+ } else {
+ built.management.destroy()
+ }
+
+ read.atReturn = signal.aborted
+
+ return call.promise
+ })
+
+ const write = answerOf(built.zones.handleSetRequest(TRIANGLE, buildEmitterConnection()))
+ await settle()
+ call.reject(new Error('The detector was stopped.'))
+ await settle()
+
+ expect({
+ answer: write.answer,
+ errors: error.mock.calls,
+ read,
+ }).toEqual({
+ answer: HAPStatus.SERVICE_COMMUNICATION_FAILURE,
+ errors: [],
+ read: (end === 'a factory reset')
+ ? { atResetCall: true, atReturn: true }
+ : { atReturn: true },
+ })
+ expect(unhandled).toEqual([])
+ })
+ })
+
+ describe('camera controller', () => {
+ const CAPABILITIES_KEY = 'cameraCapabilities:cameraCapabilities'
+ const GLOBAL_KEY = 'cameraCapabilities:globalOperatingMode'
+ const REMOVED_SENSOR = {
+ ...SECOND_VIDEO_SENSOR,
+ uuid: 'D3000003-0000-4000-8000-000000000003',
+ }
+ const REMOVED = REMOVED_SENSOR.uuid.toLowerCase()
+ const key = (family: string, sensorUUID: string): string => `cameraCapabilities:${family}:${sensorUUID}`
+
+ // The cameras a row builds, removed after it. No policy listener or management outlives its row.
+ const cameras: CameraController[] = []
+
+ afterEach(() => {
+ for (const camera of cameras.splice(0)) {
+ camera.handleControllerRemoved()
+ }
+ })
+
+ function cameraOf(options: CameraControllerOptions): CameraController {
+ const camera = new CameraController(options)
+
+ cameras.push(camera)
+ return camera
+ }
+
+ // The two-sensor camera's options with zones on the given sensors, by default every one, each through the function given for it.
+ function zonedOptions(sensorUUIDs = [FIRST, SECOND], first = motionZonesFunction(), second = motionZonesFunction()): CameraControllerCapabilitiesOptions {
+ return twoSensorCameraOptions({
+ first: sensorUUIDs.includes(FIRST)
+ ? first
+ : undefined,
+ second: sensorUUIDs.includes(SECOND)
+ ? second
+ : undefined,
+ })
+ }
+
+ // The given options with the block's webrtc member added.
+ function withWebRTC(options: CameraControllerCapabilitiesOptions): CameraControllerCapabilitiesOptions {
+ return {
+ ...options,
+ cameraCapabilities: {
+ ...options.cameraCapabilities!,
+ webrtc: webRTCStreamingOptions(),
+ },
+ }
+ }
+
+ // A camera's services, constructed and configured as a first run of the accessory configures them.
+ function configured(camera: CameraController): CameraControllerServiceMap {
+ const map = camera.constructServices()
+ camera.configureServices()
+
+ return map
+ }
+
+ function zonesKeys(map: CameraControllerServiceMap): string[] {
+ return Object.keys(map).filter(candidate => candidate.startsWith('cameraCapabilities:motionZones:') && map[candidate] !== undefined)
+ }
+
+ function zonesOf(map: CameraControllerServiceMap, sensorUUID: string): CameraMotionZones {
+ return map[key('motionZones', sensorUUID)] as CameraMotionZones
+ }
+
+ // Each multi-tier and WebRTC stream service's linked services, read as the map keys they stand under.
+ function streamLinks(map: CameraControllerServiceMap): Record {
+ const keyOf = (service: unknown): string | undefined => Object.keys(map).find(candidate => map[candidate] === service)
+
+ return Object.fromEntries(Object.keys(map)
+ .filter(candidate => candidate.startsWith('cameraCapabilities:multiTierStream:') || candidate.startsWith('cameraCapabilities:webRTCStream:'))
+ .map(candidate => [
+ candidate,
+ map[candidate]!.linkedServices.map(linked => keyOf(linked)!),
+ ]))
+ }
+
+ it('builds every configuration from the sensor list it validated, whatever the plugin changes in its list afterward', () => {
+ const options = zonedOptions([FIRST])
+ const camera = cameraOf(options)
+ const [first, second] = options.cameraCapabilities!.videoSensors
+
+ second.motionZones = motionZonesFunction()
+ delete first.motionZones
+
+ expect(zonesKeys(configured(camera))).toEqual([
+ key('motionZones', FIRST),
+ ])
+
+ camera.handleControllerRemoved()
+
+ expect(zonesKeys(configured(camera))).toEqual([
+ key('motionZones', FIRST),
+ ])
+ })
+
+ it('constructs one zones service per listed sensor in registry order whatever the list\'s order, none for an unlisted sensor and none without the member', () => {
+ const map = configured(cameraOf(zonedOptions([SECOND, FIRST])))
+
+ expect(zonesKeys(map)).toEqual([
+ key('motionZones', FIRST),
+ key('motionZones', SECOND),
+ ])
+
+ for (const sensorUUID of [FIRST, SECOND]) {
+ expect(zonesOf(map, sensorUUID).UUID).toBe(Service.CameraMotionZones.UUID)
+ expect(zonesOf(map, sensorUUID).subtype).toBe(sensorUUID)
+ }
+
+ expect(zonesKeys(configured(cameraOf(zonedOptions([SECOND]))))).toEqual([
+ key('motionZones', SECOND),
+ ])
+ expect(zonesKeys(configured(cameraOf(twoSensorCameraOptions())))).toEqual([])
+ })
+
+ it('gives a sensor with a motionZones function a zones service and one without none, and calls the function with the zones, the reason and a signal '
+ + 'and no receiver at a write, a restore and a reset', async () => {
+ const motionZones = motionZonesFunction()
+ const camera = cameraOf(zonedOptions([FIRST], motionZones))
+ const map = configured(camera)
+
+ expect(zonesKeys(map)).toEqual([
+ key('motionZones', FIRST),
+ ])
+
+ await zonesOf(map, FIRST).getCharacteristic(Characteristic.CameraZones).handleSetRequest(TRIANGLE, buildEmitterConnection())
+ camera.deserialize({
+ streamManagements: [],
+ motionZonesManagements: {
+ [FIRST]: { active: false, zones: TRIANGLE },
+ },
+ })
+ camera.handleFactoryReset()
+
+ expect(motionZones.mock.calls).toEqual([
+ [
+ { active: true, zoneData: TRIANGLE_DATA },
+ 'write',
+ expect.any(AbortSignal),
+ ],
+ [
+ { active: false, zoneData: TRIANGLE_DATA },
+ 'restore',
+ expect.any(AbortSignal),
+ ],
+ [
+ { active: true, zoneData: [] },
+ 'reset',
+ expect.any(AbortSignal),
+ ],
+ ])
+ expect(motionZones.mock.contexts).toEqual([undefined, undefined, undefined])
+ })
+
+ it('leads a constructed map with the block, the zones keys after the webrtc keys, then every key outside the block', () => {
+ const map = cameraOf(withWebRTC(zonedOptions())).constructServices()
+
+ expect(Object.keys(map)).toEqual([
+ CAPABILITIES_KEY,
+ GLOBAL_KEY,
+ key('multiTierStream', FIRST),
+ key('multiTierStream', SECOND),
+ key('webRTCStream', FIRST),
+ key('webRTCStream', SECOND),
+ key('motionZones', FIRST),
+ key('motionZones', SECOND),
+ 'cameraCapabilities:cameraBufferManagement',
+ 'cameraCapabilities:cameraKeyManagement',
+ 'cameraCapabilities:cameraClientCertificateManagement',
+ 'microphone',
+ 'speaker',
+ 'motionService',
+ 'occupancyService',
+ 'cameraEventRecordingManagement',
+ 'cameraOperatingMode',
+ 'dataStreamTransportManagement',
+ ])
+ expect(map.speaker).toBeUndefined()
+ })
+
+ it('links each zones service to its sensor\'s multi-tier stream service alone, leaving the stream services\' links as a camera without zones has them', () => {
+ const zoned = configured(cameraOf(withWebRTC(zonedOptions())))
+ const plain = configured(cameraOf(withWebRTC(twoSensorCameraOptions())))
+
+ for (const sensorUUID of [FIRST, SECOND]) {
+ expect(zonesOf(zoned, sensorUUID).linkedServices).toEqual([zoned[key('multiTierStream', sensorUUID)]])
+ }
+
+ expect(streamLinks(zoned)).toEqual(streamLinks(plain))
+ expect(Object.keys(streamLinks(zoned))).toHaveLength(4)
+ })
+
+ it('adopts each saved zones service, creates a missing one and sweeps a removed sensor\'s key at a restore', () => {
+ const motionZones = motionZonesFunction()
+ const saved = savedMapOf(cameraOf(capabilitiesCameraOptions({
+ videoSensors: [
+ { ...FIRST_VIDEO_SENSOR, motionZones },
+ { ...REMOVED_SENSOR, motionZones },
+ ],
+ streaming: idleStreaming(),
+ })))
+ const adopted = saved[key('motionZones', FIRST)]
+
+ const restored = cameraOf(zonedOptions([FIRST, SECOND], motionZones, motionZones)).initWithServices(saved)!
+
+ expect(restored).toBe(saved)
+ expect(restored[key('motionZones', FIRST)]).toBe(adopted)
+ expect(restored[key('motionZones', SECOND)]!.UUID).toBe(Service.CameraMotionZones.UUID)
+ expect(restored[key('motionZones', REMOVED)]).toBeUndefined()
+ expect(zonesKeys(restored)).toEqual([
+ key('motionZones', FIRST),
+ key('motionZones', SECOND),
+ ])
+ })
+
+ it('serializes and restores each sensor\'s zones slice, carries a removed sensor\'s and a record without the block, and drops it at a reset', async () => {
+ expect(cameraOf(zonedOptions()).serialize()!.motionZonesManagements).toBeUndefined()
+
+ const camera = cameraOf(zonedOptions())
+ const map = configured(camera)
+ await zonesOf(map, FIRST).getCharacteristic(Characteristic.CameraZones).handleSetRequest(TRIANGLE, buildEmitterConnection())
+
+ expect(camera.serialize()!.motionZonesManagements).toEqual({
+ [FIRST]: { active: true, zones: TRIANGLE },
+ [SECOND]: DEFAULT_STATE,
+ })
+
+ const restored = cameraOf(zonedOptions([FIRST]))
+ const restoredMap = configured(restored)
+ restored.deserialize({
+ streamManagements: [],
+ motionZonesManagements: {
+ [FIRST]: { active: false, zones: TRIANGLE },
+ [SECOND]: { active: false, zones: DEFAULT_ZONES },
+ },
+ })
+
+ expect(zonesOf(restoredMap, FIRST).getCharacteristic(Characteristic.CameraZones).value).toBe(TRIANGLE)
+ expect(restored.serialize()!.motionZonesManagements).toEqual({
+ [FIRST]: { active: false, zones: TRIANGLE },
+ [SECOND]: { active: false, zones: DEFAULT_ZONES },
+ })
+
+ restored.handleFactoryReset()
+
+ expect(restored.serialize()!.motionZonesManagements).toEqual({
+ [FIRST]: DEFAULT_STATE,
+ })
+
+ const plain = cameraOf(createCameraControllerOptions())
+ const record = {
+ [SECOND]: { active: false, zones: TRIANGLE },
+ }
+ plain.deserialize({
+ streamManagements: [],
+ motionZonesManagements: record,
+ })
+
+ expect(plain.serialize()!.motionZonesManagements).toEqual(record)
+
+ plain.handleFactoryReset()
+
+ expect(plain.serialize()!.motionZonesManagements).toBeUndefined()
+
+ // A record or a slice that is no plain object restores nothing and throws nothing.
+ for (const motionZonesManagements of [
+ [],
+ { [FIRST]: null },
+ ]) {
+ expect(() => restored.deserialize({
+ streamManagements: [],
+ motionZonesManagements: motionZonesManagements as unknown as Record,
+ })).not.toThrow()
+ }
+
+ expect(restored.serialize()!.motionZonesManagements).toEqual({
+ [FIRST]: DEFAULT_STATE,
+ })
+ })
+
+ it('hands the state-change delegate to every zones management, which is how each one\'s accepted write saves the camera', async () => {
+ const camera = cameraOf(zonedOptions())
+ const map = configured(camera)
+ const saves = vi.fn()
+ camera.setupStateChangeDelegate(saves)
+
+ await zonesOf(map, FIRST).getCharacteristic(Characteristic.CameraZones).handleSetRequest(TRIANGLE, buildEmitterConnection())
+ await zonesOf(map, SECOND).getCharacteristic(Characteristic.Active).handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())
+
+ expect(saves).toHaveBeenCalledTimes(2)
+
+ camera.setupStateChangeDelegate(undefined)
+ await zonesOf(map, SECOND).getCharacteristic(Characteristic.Active).handleSetRequest(Characteristic.Active.ACTIVE, buildEmitterConnection())
+
+ expect(saves).toHaveBeenCalledTimes(2)
+ })
+
+ it('resets every zones management at a factory reset, telling each, and fails a held write at a removal that clears the managements', async () => {
+ const first = motionZonesFunction()
+ const second = motionZonesFunction()
+ const camera = cameraOf(zonedOptions([FIRST, SECOND], first, second))
+ const map = configured(camera)
+ const firstZones = zonesOf(map, FIRST).getCharacteristic(Characteristic.CameraZones)
+ await firstZones.handleSetRequest(TRIANGLE, buildEmitterConnection())
+ first.mockClear()
+
+ camera.handleFactoryReset()
+
+ expect(firstZones.value).toBe(DEFAULT_ZONES)
+
+ for (const motionZones of [first, second]) {
+ expect(motionZones.mock.calls).toEqual([
+ [
+ { active: true, zoneData: [] },
+ 'reset',
+ expect.any(AbortSignal),
+ ],
+ ])
+ }
+
+ const held = deferred()
+ first.mockReturnValueOnce(held.promise)
+ const write = answerOf(firstZones.handleSetRequest(TRIANGLE, buildEmitterConnection()))
+ await settle()
+
+ camera.handleControllerRemoved()
+ await settle()
+
+ expect(write.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ // @ts-expect-error: private access
+ expect(camera.motionZonesManagements.size).toBe(0)
+ })
+
+ it('fails a write to a removed camera\'s zones service without a delegate call', async () => {
+ const motionZones = motionZonesFunction()
+ const camera = cameraOf(zonedOptions([FIRST, SECOND], motionZones))
+ const active = zonesOf(configured(camera), FIRST).getCharacteristic(Characteristic.Active)
+
+ camera.handleControllerRemoved()
+ motionZones.mockClear()
+
+ await expect(active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(motionZones).not.toHaveBeenCalled()
+ })
+
+ it('reports no update and keeps every zones key at a restore of an unchanged zoned map', () => {
+ const motionZones = motionZonesFunction()
+ const saved = savedMapOf(cameraOf(withWebRTC(zonedOptions([FIRST, SECOND], motionZones, motionZones))))
+ const order = Object.keys(saved)
+
+ expect(cameraOf(withWebRTC(zonedOptions([FIRST, SECOND], motionZones, motionZones))).initWithServices(saved)).toBeUndefined()
+ expect(Object.keys(saved)).toEqual(order)
+ expect(zonesKeys(saved)).toEqual([
+ key('motionZones', FIRST),
+ key('motionZones', SECOND),
+ ])
+ })
+ })
+})
diff --git a/src/lib/camera/MotionZonesManagement.ts b/src/lib/camera/MotionZonesManagement.ts
new file mode 100644
index 000000000..0abf6e5dd
--- /dev/null
+++ b/src/lib/camera/MotionZonesManagement.ts
@@ -0,0 +1,451 @@
+import type { CharacteristicValue } from '../../types.js'
+import type { ControllerServiceMap, StateChangeDelegate } from '../controller/index.js'
+import type { CameraMotionZones } from '../definitions/index.js'
+import type { SensorDimensions } from './capabilities/cameraSensors.js'
+import type { CameraZoneData, CameraZonesPayload } from './capabilities/zones.js'
+import type { CameraReporter } from './diagnostics/CameraReporter.js'
+import type { CameraChangeReason } from './OperatingModePolicy.js'
+import type { CameraVideoSensor } from './StreamingOptions.js'
+
+import { Characteristic } from '../Characteristic.js'
+import { HAPStatus } from '../HAPServer.js'
+import { Service } from '../Service.js'
+import { counted } from '../util/counted.js'
+import { HapStatusError } from '../util/hapStatusError.js'
+import { CAMERA_SPECIFICATION_VERSION } from './capabilities/cameraSensors.js'
+import { decodeCameraZones, encodeCameraZones, ZONE_DATA_VERSION } from './capabilities/zones.js'
+import { reconcileSensorServices, sensorServiceKey } from './capabilityKeys.js'
+import { CommandQueue } from './session/CommandQueue.js'
+import { DELEGATE_CALL_TIMEOUT, settleWithinBound } from './session/settleWithin.js'
+
+/**
+ * One video sensor's motion zones: whether the Camera Motion Zones service's `Active` is on, and the Zone Data entries of its Camera Zones.
+ *
+ * @group Camera
+ */
+export interface MotionZones {
+ /**
+ * Whether the service's `Active` is on.
+ */
+ readonly active: boolean
+ /**
+ * Each Zone Data entry of the service's Camera Zones, in the order the hub wrote them, each vertex within the sensor's dimensions.
+ */
+ readonly zoneData: readonly CameraZoneData[]
+}
+
+/**
+ * The persisted state of one video sensor's Camera Motion Zones service.
+ */
+export interface MotionZonesManagementState {
+ /**
+ * Whether the service's `Active` is on.
+ */
+ active: boolean
+ /**
+ * The Camera Zones value as the hub wrote it.
+ */
+ zones: string
+}
+
+/**
+ * The options of one video sensor's motion zones management, which the camera controller builds from the validated block.
+ */
+export interface MotionZonesManagementOptions {
+ /**
+ * The sensor's `motionZones` function, called as a plain function.
+ */
+ motionZones: NonNullable
+ /**
+ * The camera's reporter, through which zones the sensor refuses are refused values of the camera's, and a rejection of the sensor's function or a write
+ * it does not settle within its bound is the plugin's failure.
+ */
+ reporter: CameraReporter
+ /**
+ * The video sensor's UUID, in lowercase.
+ */
+ sensorUUID: string
+ /**
+ * The video sensor's dimensions, which bound every vertex of its zones.
+ */
+ sensorDimensions: SensorDimensions
+}
+
+// The zones a service starts with and a factory reset restores: Active on and Zone Data of the version the spec has implementations write, with no entry.
+const DEFAULT_ZONES = encodeCameraZones({ zoneDataVersion: ZONE_DATA_VERSION, zoneData: [] })
+const DEFAULT_STATE: Readonly = { active: true, zones: DEFAULT_ZONES }
+
+// The reasons the class calls the sensor's function under, a write's awaited and a restore's or a reset's not.
+type ToldReason = Exclude
+
+// How each reason's failure of the sensor's function is reported, the delegate helpers adding the failure itself.
+const FAILURES: Readonly> = {
+ write: 'The motionZones function failed to apply a write of the motion zones of video sensor',
+ restore: 'The motionZones function failed to apply the restored motion zones of video sensor',
+ reset: 'The motionZones function failed to apply the reset motion zones of video sensor',
+}
+
+/* Why a decoded Camera Zones value does not fit the sensor, as a clause naming the rule, or undefined for a value it takes. The spec forms each zone from a
+ * polygon in the sensor's coordinate space and names each zone by its identifier: a polygon needs three vertices, every vertex lies within the sensor's
+ * width and height, and an identifier names one zone across the whole value. An empty list and a Zone Data entry with no polygons clear the zones, and a
+ * self-intersecting polygon is left to the plugin.
+ */
+function refusal(payload: CameraZonesPayload, dimensions: SensorDimensions): string | undefined {
+ const identifiers = new Set()
+
+ for (const { polygons } of payload.zoneData) {
+ for (const { identifier, vertices } of polygons) {
+ if (vertices.length < 3) {
+ return `the zone ${identifier} has ${counted(vertices.length, 'vertex', 'vertices')}, where a polygon needs at least three`
+ }
+
+ for (const [x, y] of vertices) {
+ if (x > dimensions.width || y > dimensions.height) {
+ return `the zone ${identifier} has the vertex (${x}, ${y}) outside the sensor's ${dimensions.width} by ${dimensions.height} pixels`
+ }
+ }
+
+ if (identifiers.has(identifier)) {
+ return `the zone identifier ${identifier} appears more than once`
+ }
+
+ identifiers.add(identifier)
+ }
+ }
+
+ return undefined
+}
+
+// A failure's message as a clause, its closing period dropped, because the problem that carries it has one sentence.
+function messageOf(error: unknown): string {
+ return ((error as Error | undefined)?.message ?? String(error)).replace(/\.$/, '')
+}
+
+/**
+ * Serves one video sensor's Camera Motion Zones service: it holds the zones in force and whether they are active, hands each change a write asks for to
+ * the sensor's `motionZones` function and keeps it once the function accepts it. The service runs its writes one at a time, in the order they arrive.
+ * A write of `Active` behind a write of Camera Zones hands the function the zones that write left in force.
+ *
+ * A Camera Zones write is refused with `INVALID_VALUE_IN_REQUEST` before it waits, with one value-refused problem naming the sensor and the rule, when its
+ * value does not decode, a polygon has fewer than three vertices, a vertex lies beyond the sensor's width or height, or an identifier repeats within the
+ * value. The refusal is a problem rather than a debug event, because it means zones a user drew are not in force. A write the function rejects or leaves
+ * unsettled at the bound fails with `SERVICE_COMMUNICATION_FAILURE` and keeps the zones in force, and a read answers those zones rather than the failed
+ * write's status.
+ *
+ * The accessory answers a hub's write as timed out well before the delegate call bound, while the wait runs on to the bound: a write the hub saw time out
+ * still applies when the function settles within the bound, and the hub reads the zones in force back. Camera Zones carries no notify permission, and a hub
+ * learns of the zones a restore or a factory reset put in force at its next read. A saved slice a restore refuses stays saved until the camera's next save.
+ */
+export class MotionZonesManagement {
+ /**
+ * The service's key in the camera's service map.
+ * @private
+ */
+ readonly serviceKey: string
+ private readonly motionZones: NonNullable
+ private readonly reporter: CameraReporter
+ private readonly sensorUUID: string
+ private readonly sensorDimensions: SensorDimensions
+ private readonly service: CameraMotionZones
+ private readonly queue = new CommandQueue()
+ private stateChangeDelegate?: StateChangeDelegate
+
+ /**
+ * The zones in force, which answer reads, the sensor's function and `serialize`; the characteristics' values follow them.
+ */
+ private state: Readonly = DEFAULT_STATE
+
+ /**
+ * The abort controller of the current generation of writes. A factory reset aborts it and starts a new one, and a destroy aborts it alone. A write
+ * that arrived under an aborted controller fails at its turn, one the sensor's function holds is cut, and one whose call settled fails when the
+ * controller it arrived under was aborted before its turn resumed. No call of the function listens on it: a write's call's signal is aborted through
+ * the write in flight, and a restore's or a reset's never is.
+ */
+ private generation = new AbortController()
+
+ /**
+ * The controller of the write whose call of the sensor's function the class is making or waiting on: set before the write's call is made, since the
+ * function can set off a factory reset or the camera's removal inside its own call, and cleared as its wait ends, by the call's settling, its bound or the
+ * generation. It holds no other write's, since a later write's turn begins only once the one before it has returned. The write's own bound aborts it,
+ * and a factory reset and a destroy abort it before anything else: a pending write's signal reads aborted before a reset's own call of the function is
+ * made, a reset made inside the write's own call among them.
+ */
+ private writeInFlight?: AbortController
+
+ /**
+ * Adopts the saved service or builds one, and writes its version and the defaults to it. Its characteristics and the zones in force agree before a
+ * restore.
+ * @param options - The sensor's options.
+ * @param service - A saved service to adopt.
+ */
+ constructor(options: MotionZonesManagementOptions, service?: CameraMotionZones) {
+ this.motionZones = options.motionZones
+ this.reporter = options.reporter
+ this.sensorUUID = options.sensorUUID.toLowerCase()
+ this.sensorDimensions = options.sensorDimensions
+ this.serviceKey = MotionZonesManagement.serviceKey(this.sensorUUID)
+ this.service = service ?? new Service.CameraMotionZones('', this.sensorUUID)
+
+ this.service.updateCharacteristic(Characteristic.Version, CAMERA_SPECIFICATION_VERSION)
+ this.project()
+ this.setupServiceHandlers()
+ }
+
+ /**
+ * The key a video sensor's service carries in the camera's service map.
+ * @param sensorUUID - The video sensor's UUID.
+ * @returns The capability prefix, `motionZones:` and the UUID in lowercase.
+ * @private
+ */
+ static serviceKey(sensorUUID: string): string {
+ return sensorServiceKey('motionZones', sensorUUID)
+ }
+
+ /**
+ * Reconciles every listed video sensor's service in a restored service map, in the order given: a sensor's saved service under its key is adopted, and a
+ * sensor without one gets a new service, inserted. The key of a sensor the camera does not list is left to the capability key sweep.
+ * @param serviceMap - The camera's service map, changed in place.
+ * @param sensors - Each listed video sensor's options, in the camera's order.
+ * @param create - Builds a sensor's management over its saved service, or over a new one when it is given none.
+ * @returns Whether the map changed.
+ * @private
+ */
+ static reconcile(
+ serviceMap: ControllerServiceMap,
+ sensors: readonly MotionZonesManagementOptions[],
+ create: (options: MotionZonesManagementOptions, service?: CameraMotionZones) => MotionZonesManagement,
+ ): boolean {
+ return reconcileSensorServices(
+ serviceMap,
+ sensors,
+ options => MotionZonesManagement.serviceKey(options.sensorUUID),
+ (options, service?: CameraMotionZones) => create(options, service).getService(),
+ )
+ }
+
+ /**
+ * The Camera Motion Zones service.
+ * @returns The service.
+ */
+ getService(): CameraMotionZones {
+ return this.service
+ }
+
+ /**
+ * The state to persist.
+ * @returns Whether `Active` is on and the Camera Zones value in force.
+ * @private
+ */
+ serialize(): MotionZonesManagementState {
+ return { ...this.state }
+ }
+
+ /**
+ * Restores persisted state: a slice whose `active` is a boolean and whose `zones` decodes and fits the sensor's current dimensions is put in force, and
+ * any other leaves the defaults in force, with one value-refused problem. Active and Camera Zones take the zones in force, no save is requested, and the
+ * sensor's function is called with them under `'restore'` without being awaited.
+ * @param state - The persisted state.
+ * @private
+ */
+ deserialize(state: MotionZonesManagementState): void {
+ const refused = this.refusalOfSaved(state)
+
+ if (refused === undefined) {
+ this.state = { active: state.active, zones: state.zones }
+ } else {
+ this.reporter.problem({
+ kind: 'value-refused',
+ level: 'warning',
+ sensorUUID: this.sensorUUID,
+ sentence: `The saved motion zones of video sensor ${this.sensorUUID} cannot be restored because ${refused}. The defaults apply.`,
+ })
+ this.state = DEFAULT_STATE
+ }
+
+ this.project()
+ this.tell('restore')
+ }
+
+ /**
+ * Sets the delegate an accepted write and a factory reset call, which is how the owner persists the zones.
+ * @param delegate - The delegate, or `undefined` to clear it.
+ * @private
+ */
+ setupStateChangeDelegate(delegate?: StateChangeDelegate): void {
+ this.stateChangeDelegate = delegate
+ }
+
+ /**
+ * Puts the defaults in force: the signal of the write whose call the class is making or waiting on is aborted first, which is why the plugin hears that the
+ * write is not wanted before it hears the defaults. Every write still waiting fails, a write the sensor's function holds included, the
+ * characteristics take the defaults, the owner is asked to save, and the function is called with them under `'reset'` without being awaited, with a
+ * signal nothing aborts. A restore's or an earlier reset's call still unsettled is not aborted.
+ */
+ handleFactoryReset(): void {
+ this.writeInFlight?.abort()
+ this.generation.abort()
+ this.generation = new AbortController()
+ this.state = DEFAULT_STATE
+ this.project()
+ this.stateChangeDelegate?.()
+ this.tell('reset')
+ }
+
+ /**
+ * Aborts the signal of the write whose call the class is making or waiting on, then fails every write still waiting, a write the sensor's function
+ * holds included, and every write that arrives later, before the service is dropped. A restore's or a reset's call still unsettled is not aborted.
+ * The write handlers stay, and a later write fails at its turn rather than writing the characteristic. Safe to call more than once.
+ */
+ destroy(): void {
+ this.writeInFlight?.abort()
+ this.generation.abort()
+ }
+
+ // Each write takes the generation it arrived under before it queues, and a read answers the zones in force, because a refused or failed write leaves its
+ // status on the characteristic and a plain read would answer that status.
+ private setupServiceHandlers(): void {
+ const active = this.service.getCharacteristic(Characteristic.Active)
+ const zones = this.service.getCharacteristic(Characteristic.CameraZones)
+
+ active.onGet(() => this.activeValue())
+ zones.onGet(() => this.state.zones)
+
+ active.onSet(async (value) => {
+ const { generation } = this
+
+ await this.queue.run(async () => this.apply(generation, { active: !!value }))
+ })
+
+ zones.onSet(async (value) => {
+ this.refuseWrite(value)
+
+ const { generation } = this
+
+ await this.queue.run(async () => this.apply(generation, { zones: value as string }))
+ })
+ }
+
+ // A Camera Zones value that does not decode or does not fit the sensor is refused before it waits, and a refusal never holds the queue.
+ private refuseWrite(value: CharacteristicValue): void {
+ let refused: string | undefined
+
+ try {
+ refused = refusal(decodeCameraZones(value as string), this.sensorDimensions)
+ } catch (error) {
+ refused = `its value does not decode as Camera Zones (${messageOf(error)})`
+ }
+
+ if (refused !== undefined) {
+ this.reporter.problem({
+ kind: 'value-refused',
+ level: 'warning',
+ sensorUUID: this.sensorUUID,
+ sentence: `A write of the motion zones of video sensor ${this.sensorUUID} was refused because ${refused}. The zones in force stand.`,
+ })
+ throw new HapStatusError(HAPStatus.INVALID_VALUE_IN_REQUEST)
+ }
+ }
+
+ /* A write's turn. A write a factory reset or a destroy overtook fails without reaching the sensor's function. Otherwise the function is called with the
+ * zones the write asks for, read over the zones in force at this turn, and awaited within the delegate call bound counted from this call: time spent
+ * queued takes nothing from it. Only a call that settles puts the zones in force and asks the owner to save, and the characteristic takes the written
+ * value after. A call that settled fails its write all the same when a factory reset or a destroy passed before the turn resumed, as a call still
+ * pending does. A reset's defaults, which the function hears last, stay in force. The call's controller is made here and is the write in flight from
+ * before the function is called until the wait ends, which is why a factory reset or a destroy aborts the call's signal, one the function sets off inside its own
+ * call among them. The zones are read before the field is set: nothing between the set and the wait can throw and leave it held. A call cut at its
+ * bound is unsettled there, and its signal is aborted.
+ */
+ private async apply(generation: AbortController, change: Partial): Promise {
+ if (generation.signal.aborted) {
+ throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ }
+
+ const next = {
+ ...this.state,
+ ...change,
+ }
+ const zones = this.zonesOf(next)
+ const call = new AbortController()
+
+ this.writeInFlight = call
+
+ const pending = this.call('write', zones, call)
+ const { cutAtBound, outcome } = await settleWithinBound(pending, generation.signal)
+
+ this.writeInFlight = undefined
+
+ if (!outcome || generation.signal.aborted) {
+ if (cutAtBound) {
+ call.abort()
+ this.reporter.problem({
+ kind: 'plugin-failure',
+ level: 'warning',
+ sensorUUID: this.sensorUUID,
+ sentence: `The motionZones function did not settle a write of the motion zones of video sensor ${this.sensorUUID} within `
+ + `${DELEGATE_CALL_TIMEOUT / 1000} seconds: the write fails and the zones in force stand.`,
+ })
+ }
+
+ throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ }
+
+ this.state = next
+ this.stateChangeDelegate?.()
+ }
+
+ // Why a saved slice cannot be put in force, as a clause, or undefined for one that can, checked against the sensor's current dimensions.
+ private refusalOfSaved(state: MotionZonesManagementState): string | undefined {
+ if (typeof state.active !== 'boolean') {
+ return 'its active flag is no boolean'
+ }
+
+ try {
+ return refusal(decodeCameraZones(state.zones), this.sensorDimensions)
+ } catch (error) {
+ return `its zones do not decode as Camera Zones (${messageOf(error)})`
+ }
+ }
+
+ /* Calls the sensor's function with the zones in force without awaiting it, its failure a plugin-failure problem under the reason's sentence, under a
+ * controller of its own that nothing aborts: only a write's controller is the write in flight, set before its call is made.
+ */
+ private tell(reason: 'restore' | 'reset'): void {
+ void this.call(reason, this.zonesOf(this.state), new AbortController())
+ }
+
+ /* One call of the sensor's function, a write's, a restore's or a reset's, under the controller its caller made, whose signal listens on nothing, and
+ * answers the call's promise. A write's controller is the write in flight from before this call, since the function can set off a factory reset or the
+ * camera's removal inside its own call, which aborts it there as at any later moment of the write's wait; its bound aborts it too. A restore's or a
+ * reset's is never aborted, and every rejection of theirs is reported. A timeout signal or the generation's own, handed to the function, would abort long
+ * after a call that settled. A rejection is reported under the reason's sentence unless the call's signal was aborted first. The function is called with no
+ * receiver.
+ */
+ private call(reason: ToldReason, zones: MotionZones, call: AbortController): Promise {
+ const motionZones = this.motionZones
+ const pending = (async () => motionZones(zones, reason, call.signal))()
+
+ this.reporter.rejection('plugin-failure', pending, `${FAILURES[reason]} ${this.sensorUUID}`, call.signal, { sensorUUID: this.sensorUUID })
+
+ return pending
+ }
+
+ // Writes the zones in force to Active and Camera Zones through updateCharacteristic, never a set path. No write of the class's own reaches a handler.
+ private project(): void {
+ this.service.updateCharacteristic(Characteristic.Active, this.activeValue())
+ this.service.updateCharacteristic(Characteristic.CameraZones, this.state.zones)
+ }
+
+ private activeValue(): number {
+ return this.state.active
+ ? Characteristic.Active.ACTIVE
+ : Characteristic.Active.INACTIVE
+ }
+
+ // The zones a state holds, decoded afresh: a function that changes what it was handed changes nothing the class keeps.
+ private zonesOf(state: MotionZonesManagementState): MotionZones {
+ return {
+ active: state.active,
+ zoneData: decodeCameraZones(state.zones).zoneData,
+ }
+ }
+}
diff --git a/src/lib/camera/MultiTierStreamManagement.spec.ts b/src/lib/camera/MultiTierStreamManagement.spec.ts
new file mode 100644
index 000000000..8623fc78a
--- /dev/null
+++ b/src/lib/camera/MultiTierStreamManagement.spec.ts
@@ -0,0 +1,6781 @@
+import type { Socket } from 'node:dgram'
+import type { Mock } from 'vitest'
+
+import type { ScriptedTierDelegate } from '../../test-utils/cameraFixtures.js'
+import type { SampleFixture, WrittenFrame } from '../../test-utils/mp4Fixtures.js'
+import type { RTPVectorStream } from '../../test-utils/rtpVectors.js'
+import type { Deferred } from '../../test-utils/settle.js'
+import type { KeepingSink } from '../../test-utils/talkbackSink.js'
+import type { CameraControllerServiceMap, CameraLiveView, CameraRecordingEnd } from '../controller/index.js'
+import type { AccessoryInformation, CameraGlobalOperatingMode, CameraMultiTierRTPStreamManagement } from '../definitions/index.js'
+import type { HAPConnection } from '../util/eventedhttp.js'
+import type { RTPStreamingControlRequest, RTPStreamingControlResponse } from './capabilities/rtpStreaming.js'
+import type { SetupEndpointsResponse, SRTPParameters } from './capabilities/setupEndpoints.js'
+import type { CameraDebugEvent } from './diagnostics/debugChannels.js'
+import type { CameraProblem } from './diagnostics/problems.js'
+import type { MultiTierStreamManagementOptions, MultiTierStreamManagementState } from './MultiTierStreamManagement.js'
+import type { StreamingEnabledChange } from './OperatingModePolicy.js'
+import type { RecordingPacket } from './RecordingManagement.js'
+import type {
+ CameraVideoSensor,
+ MultiTierStreamingDelegate,
+ SensorStreamTiers,
+ StreamTierMedium,
+ TalkbackSink,
+ TierFrame,
+ TierStream,
+} from './StreamingOptions.js'
+import type { FrameConsumer, TierDemand, TierHolder } from './TierTable.js'
+import type { WebRTCStreamManagementOptions } from './WebRTCStreamManagement.js'
+
+import { Buffer } from 'node:buffer'
+import crypto from 'node:crypto'
+import dgram from 'node:dgram'
+
+import tweetnacl from 'tweetnacl'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ advanceAsync,
+ buildEmitterConnection,
+ capabilitiesCameraOptions,
+ createCameraControllerOptions,
+ disposableFor,
+ disposedOf,
+ endsOf,
+ frames,
+ handPublishedContext,
+ idleStreaming,
+ keepStreaming,
+ NUMBERED_ACCESSORY_UUID,
+ openingStamp,
+ pendingStart,
+ savedMapOf,
+ scriptedTierDelegate,
+ signalOf,
+ streamsOf,
+ tierSetOf,
+ videoSensor,
+ webRTCStreamingOptions,
+} from '../../test-utils/cameraFixtures.js'
+import { captureDebug, captureDebugEvents } from '../../test-utils/engineDebug.js'
+import { HAPHTTPClient } from '../../test-utils/HAPHTTPClient.js'
+import {
+ hvcC,
+ initializationSegment,
+ opusSampleEntry,
+ pictureSample,
+ soundSample,
+ TIER_STREAM_PARAMETER_SETS,
+ tierStreamFragment,
+ tierStreamInitialization,
+ visualSampleEntry,
+ withParameterSets,
+ writeTierFrame,
+} from '../../test-utils/mp4Fixtures.js'
+import { PairVerifyClient } from '../../test-utils/PairVerifyClient.js'
+import { ReferenceSRTP } from '../../test-utils/ReferenceSRTP.js'
+import { detachedReporter, problemsOf } from '../../test-utils/reporterFixtures.js'
+import { nalUnit, RTP_VECTORS, tierFrameData, vectorFrameData } from '../../test-utils/rtpVectors.js'
+import { deferred, fakeTimeoutSignals, settle, until } from '../../test-utils/settle.js'
+import { keepingSink } from '../../test-utils/talkbackSink.js'
+import { Accessory, AccessoryEventTypes, Categories, MDNSAdvertiser } from '../Accessory.js'
+import { Bridge } from '../Bridge.js'
+import { Characteristic, CharacteristicEventTypes } from '../Characteristic.js'
+import { CameraController, CameraControllerEvents } from '../controller/index.js'
+import { HAPStatus } from '../HAPServer.js'
+import { AccessoryInfo, PermissionTypes } from '../model/AccessoryInfo.js'
+import { Service, ServiceEventTypes } from '../Service.js'
+import { awaitEventOnce } from '../util/promise-utils.js'
+import * as uuid from '../util/uuid.js'
+import { TierBuffer } from './buffer/CameraBuffer.js'
+import { CameraSensorIntent, CameraSensorType, decodeCameraCapabilities } from './capabilities/cameraSensors.js'
+import { decodeRTPStreamingControlResponse, encodeRTPStreamingControlRequest, RTPStreamingCommand, RTPStreamingStatus } from './capabilities/rtpStreaming.js'
+import { decodeSetupEndpointsResponse, encodeSetupEndpointsRequest, SetupEndpointsStatus, SRTPCryptoSuites } from './capabilities/setupEndpoints.js'
+import { encodeSupportedAudioStreamTiers, encodeSupportedVideoStreamTiers } from './capabilities/streamTiers.js'
+import { GlobalOperatingMode } from './GlobalOperatingMode.js'
+import { MultiTierStreamManagement } from './MultiTierStreamManagement.js'
+import { OperatingModePolicy } from './OperatingModePolicy.js'
+import { FrameCutter } from './rtp/FrameCutter.js'
+import { SEQUENCE_RANGE } from './rtp/packetRules.js'
+import { DELEGATE_CALL_TIMEOUT } from './session/settleWithin.js'
+import { SRTPContext } from './srtp/SRTPContext.js'
+import { bestStreamTier } from './StreamingOptions.js'
+import { TierPacer } from './TierPacer.js'
+import { TierHold, TierTable } from './TierTable.js'
+
+import '../definitions/index.js'
+
+const SENSOR_UUID = 'A1B2C3D4-0000-4000-8000-000000000001'
+const SERVICE_KEY = 'cameraCapabilities:multiTierStream:a1b2c3d4-0000-4000-8000-000000000001'
+const UNKNOWN_SESSION = 'e7f1c3a2-5b4d-4e6f-9a8b-0c1d2e3f4a5b'
+
+const SENSOR = videoSensor(SENSOR_UUID)
+
+// The fixture's tiers: video tiers 1 to 3 at payload type 99 and audio tier 1 at payload type 110.
+const TIERS = tierSetOf(SENSOR)
+
+// The master keys and salts the controller writes for its own streams, and the SSRCs its Start names.
+const CONTROLLER_KEYS: Record = {
+ video: {
+ cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80,
+ masterKey: Buffer.alloc(16, 0x11),
+ masterSalt: Buffer.alloc(14, 0x22),
+ },
+ audio: {
+ cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80,
+ masterKey: Buffer.alloc(16, 0x33),
+ masterSalt: Buffer.alloc(14, 0x44),
+ },
+}
+const CONTROLLER_SSRCS: Record = { video: 0xAABBCCDD, audio: 0x11223344 }
+
+// The RTCP packets a controller sends: a receiver report with one report block, a picture loss indication and a full intra request.
+const RECEIVER_REPORT = '81c90007aabbccdd112233440000000000000064000000000000000000000000'
+const PICTURE_LOSS = '81ce0002aabbccdd11223344'
+const FULL_INTRA_REQUEST = '84ce0004aabbccdd000000001122334407000000'
+
+interface Harness {
+ delegate: ScriptedTierDelegate
+ policy: OperatingModePolicy
+ global: CameraGlobalOperatingMode
+ management: MultiTierStreamManagement
+ service: CameraMultiTierRTPStreamManagement
+ table: TierTable
+ changes: StreamingEnabledChange[]
+}
+
+// The controller's end of a session's media: one socket per medium on loopback port 0, each recording every datagram the accessory sends it.
+interface Endpoint {
+ sockets: Record
+ ports: Record
+ received: Record
+}
+
+type Prepared = Extract & { sessionIdentifier: string }
+
+// The managements and sockets a row creates, ended and closed after it.
+const managements: MultiTierStreamManagement[] = []
+const sockets: Socket[] = []
+
+/* A management over a policy that projects the camera's state through a Camera Global Operating Mode service alone: HomeKit Camera Active has one
+ * projection, configured as the camera controller configures it unless a row configures it itself. Its tier table is built from the delegate and the tiers
+ * a row hands it, the fixture's by default, as the camera controller builds a sensor's table, and a row's delegate reaches every demand call. It holds the
+ * specification's floor of five sessions unless a row hands its own bound, as the camera controller hands the bound its options boundary defaulted, and
+ * reads the Speaker unmuted unless a row hands its own reader.
+ */
+function harness(options: Partial> & {
+ configure?: boolean
+ service?: CameraMultiTierRTPStreamManagement
+ tiers?: SensorStreamTiers
+} = {}): Harness {
+ const scripted = scriptedTierDelegate()
+ const { configure = true, delegate = scripted, reporter = detachedReporter(), service, speakerMuted = () => false, tiers = TIERS, ...overrides } = options
+ const policy = new OperatingModePolicy()
+ const global = new GlobalOperatingMode(policy).service
+ const changes: StreamingEnabledChange[] = []
+ const table = new TierTable(delegate, tiers, tier => new TierBuffer(tier), reporter)
+ const management = new MultiTierStreamManagement({
+ delegate,
+ table,
+ maxSessions: 5,
+ onStreamingEnabledChange: change => changes.push(change),
+ reporter,
+ speakerMuted,
+ ...overrides,
+ }, policy, service)
+
+ managements.push(management)
+
+ if (configure) {
+ management.configureServices()
+ }
+
+ return {
+ delegate: scripted,
+ policy,
+ global,
+ management,
+ service: management.getService(),
+ table,
+ changes,
+ }
+}
+
+// The UDP sockets the process holds open.
+function udpSockets(): number {
+ return process.getActiveResourcesInfo().filter(name => name === 'UDPWrap').length
+}
+
+async function endpoint(): Promise {
+ const bound = async (): Promise => new Promise((resolve) => {
+ const socket = dgram.createSocket('udp4')
+ sockets.push(socket)
+ socket.bind(0, '127.0.0.1', () => resolve(socket))
+ })
+ const video = await bound()
+ const audio = await bound()
+ const received: Record = { video: [], audio: [] }
+
+ video.on('message', datagram => received.video.push(datagram))
+ audio.on('message', datagram => received.audio.push(datagram))
+
+ return {
+ sockets: { video, audio },
+ ports: { video: video.address().port, audio: audio.address().port },
+ received,
+ }
+}
+
+function setupRequest(from: Endpoint, sessionIdentifier: string, keys: Record = CONTROLLER_KEYS): string {
+ return encodeSetupEndpointsRequest({
+ sessionIdentifier,
+ controllerAddress: {
+ addressVersion: 'ipv4',
+ address: '127.0.0.1',
+ videoRTPPort: from.ports.video,
+ audioRTPPort: from.ports.audio,
+ },
+ videoSRTPParameters: keys.video,
+ audioSRTPParameters: keys.audio,
+ })
+}
+
+async function readSetupEndpoints(service: CameraMultiTierRTPStreamManagement, connection?: HAPConnection): Promise {
+ return service.getCharacteristic(Characteristic.SetupEndpoints).handleGetRequest(connection)
+}
+
+// Writes Setup Endpoints for a new session and answers the write's own settlement, for a row that reads a write the management fails.
+async function writeSetup(service: CameraMultiTierRTPStreamManagement, connection: HAPConnection, from: Endpoint): Promise {
+ return await service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest(setupRequest(from, crypto.randomUUID()), connection)
+}
+
+// Writes Setup Endpoints and reads the writer's answer back on its connection, as a hub does.
+async function prepare(service: CameraMultiTierRTPStreamManagement, connection: HAPConnection, from: Endpoint, sessionIdentifier: string, request?: string):
+Promise {
+ await service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest(request ?? setupRequest(from, sessionIdentifier), connection)
+
+ return decodeSetupEndpointsResponse(await readSetupEndpoints(service, connection) as string)
+}
+
+async function control(service: CameraMultiTierRTPStreamManagement, connection: HAPConnection, request: RTPStreamingControlRequest):
+Promise {
+ return decodeRTPStreamingControlResponse(await service.getCharacteristic(Characteristic.RTPStreamingControl)
+ .handleSetRequest(encodeRTPStreamingControlRequest(request), connection) as string)
+}
+
+async function start(service: CameraMultiTierRTPStreamManagement, connection: HAPConnection, sessionIdentifier: string, videoTier = 1, audioTier = 1):
+Promise {
+ return (await control(service, connection, {
+ sessionIdentifier,
+ command: RTPStreamingCommand.START,
+ videoTier,
+ videoSSRC: CONTROLLER_SSRCS.video,
+ audioTier,
+ audioSSRC: CONTROLLER_SSRCS.audio,
+ })).status
+}
+
+async function end(service: CameraMultiTierRTPStreamManagement, connection: HAPConnection, sessionIdentifier: string): Promise {
+ return (await control(service, connection, { sessionIdentifier, command: RTPStreamingCommand.END })).status
+}
+
+// The accessory's answer for a session the row prepares and starts, which every packet the controller receives is verified under.
+async function streaming(service: CameraMultiTierRTPStreamManagement, connection: HAPConnection, from: Endpoint, videoTier = 1): Promise {
+ const sessionIdentifier = crypto.randomUUID()
+ const answer = await prepare(service, connection, from, sessionIdentifier)
+
+ if (answer.status !== SetupEndpointsStatus.SUCCESS) {
+ throw new Error(`The Setup Endpoints answered status ${answer.status}.`)
+ }
+
+ expect(await start(service, connection, sessionIdentifier, videoTier)).toBe(RTPStreamingStatus.SUCCESS)
+
+ return answer as Prepared
+}
+
+// The stream the delegate was handed for a video tier's demand, the latest when the tier had several.
+function streamOf(delegate: ScriptedTierDelegate, tierId = 1): TierStream {
+ return streamsOf(delegate, tierId).at(-1)!
+}
+
+// A holder that holds a tier on the table itself rather than through a session, with a route for a failed tier the row reads.
+function scriptedHolder(): TierHolder & { tierFailed: Mock<() => void> } {
+ return {
+ tierFailed: vi.fn<() => void>(),
+ }
+}
+
+// One frame a frame consumer took: the frame as handed over, a copy of its bytes at the hand-over, its timestamp and whether it opened a run.
+interface TakenFrame {
+ readonly frame: TierFrame
+ readonly data: Buffer
+ readonly timestamp: number
+ readonly opensRun: boolean
+}
+
+// A frame consumer that keeps each frame it takes, its bytes copied before the hand-over returns as the contract asks.
+function scriptedFrameConsumer(): FrameConsumer & { taken: TakenFrame[] } {
+ const taken: TakenFrame[] = []
+
+ return {
+ taken,
+ take: (frame, timestamp, opensRun) => {
+ taken.push({
+ frame,
+ data: Buffer.from(frame.data),
+ timestamp,
+ opensRun,
+ })
+ },
+ }
+}
+
+// The ends of a video tier's demands: each release of the disposable a start registered, one at each end, a withdrawal's among them.
+function endedCalls(delegate: ScriptedTierDelegate, tierId = 1): number {
+ return endsOf(delegate, tierId)
+}
+
+// Each demand the delegate started has ended once, through the disposable its start registered on the very stream its start handed out, released once
+// whether its start settled or was withdrawn while pending.
+function expectEndsNameTheirStreams(delegate: ScriptedTierDelegate, demands: number): void {
+ const streams = streamsOf(delegate)
+
+ expect([
+ streams.length,
+ endsOf(delegate),
+ ]).toEqual([demands, demands])
+
+ for (const stream of streams) {
+ expect(disposedOf(delegate, stream)).toBe(1)
+ }
+}
+
+// The vectors' HEVC stream, whose frames the rows write, cut at the 1228 octets a demand under the fixture's IPv6 connection cuts.
+const HEVC = RTP_VECTORS.stream
+const CUT = 1228
+
+// The NAL unit header of an HEVC picture slice, TRAIL_R in the lowest temporal sub-layer, which a row's own units open with.
+const SLICE = Buffer.from([0x02, 0x01])
+
+// A frame of one vector frame's units, at a time in microseconds.
+function vectorFrame(stream: RTPVectorStream, index: number, time = 0): TierFrame {
+ return {
+ data: vectorFrameData(stream.frames[index]),
+ time,
+ }
+}
+
+// A frame of one HEVC slice of a given length, at a time in microseconds.
+function sliceFrame(length: number, time = 0, discontinuity = false): WrittenFrame {
+ return {
+ data: tierFrameData([
+ nalUnit(SLICE, length),
+ ]),
+ time,
+ discontinuity,
+ }
+}
+
+// A frame written as a keyframe that opens its stream or its run, HEVC's parameter sets in band before its units: a consumer of the live pictures, which
+// is sent no picture before a keyframe, is sent it first, and its demand raises no parameter-set problem.
+function keyframeWithSets(frame: WrittenFrame): WrittenFrame {
+ return {
+ ...frame,
+ data: withParameterSets(frame.data),
+ keyframe: true,
+ }
+}
+
+// A picture sample of a keyframe of one 300-octet slice, its parameter sets in band, which opens its stream or its run.
+function keyframeSample(): SampleFixture {
+ return pictureSample(keyframeWithSets(sliceFrame(300)).data, true)
+}
+
+// The payload of the one aggregation packet a keyframe of a slice of a given length cuts into with its parameter sets: the packet's header, and each unit
+// behind its length in two octets.
+function setsAggregated(length: number): number {
+ return 2 + TIER_STREAM_PARAMETER_SETS.reduce((total, unit) => total + 2 + unit.length, 0) + 2 + length
+}
+
+// Each RTP packet a session's medium received, in the order it arrived and unprotected under the session's keys, its sender reports passed over.
+function unprotected(answer: Prepared, from: Endpoint, medium: StreamTierMedium): Buffer[] {
+ const reference = new ReferenceSRTP(medium === 'video'
+ ? answer.videoSRTPParameters
+ : answer.audioSRTPParameters)
+
+ return from.received[medium].filter(datagram => datagram[1] !== 200).map(datagram => reference.unprotect(datagram)!)
+}
+
+// The payload a fragmentation unit carries after its three octets of headers at the vectors' size: a unit two octets of header longer than a whole
+// number of them is cut into exactly that number of packets.
+const FRAGMENT_PAYLOAD = CUT - 12 - 3
+
+// A frame of one HEVC slice the cutter makes into exactly the given number of packets, at a time in microseconds.
+function burstFrame(packets: number, time = 0): TierFrame {
+ return {
+ data: tierFrameData([
+ nalUnit(SLICE, SLICE.length + packets * FRAGMENT_PAYLOAD),
+ ]),
+ time,
+ }
+}
+
+// A keyframe the cutter makes into exactly the given number of packets, at a time in microseconds: an aggregation packet of its parameter sets, and the
+// fragments of one slice after it.
+function burstKeyframe(packets: number, time = 0): WrittenFrame {
+ return keyframeWithSets(burstFrame(packets - 1, time))
+}
+
+// One datagram an accessory's socket was handed: the view it was handed, a copy of the view's bytes at the send, and the send's completion, which reports
+// no error or the one a row hands it.
+interface HeldSend {
+ readonly view: Buffer
+ readonly sent: Buffer
+ readonly complete: () => void
+ readonly fail: (error: Error) => void
+}
+
+// Holds every packet an accessory's socket is handed with a completion, rather than sending it. A row decides when each send completes and fills a
+// sender's pool with sends in flight. A sender report, which takes no completion, is passed over.
+function holdSends(socket: Socket): HeldSend[] {
+ const held: HeldSend[] = []
+
+ vi.spyOn(socket, 'send').mockImplementation(((view: Buffer, completion?: unknown) => {
+ if (typeof completion === 'function') {
+ held.push({
+ view,
+ sent: Buffer.from(view),
+ complete: () => completion(null),
+ fail: error => completion(error),
+ })
+ }
+ }) as unknown as Socket['send'])
+
+ return held
+}
+
+// Completes the first held sends in the order they were made, answering how many of their datagrams still held their bytes from the send at their completion.
+function complete(held: HeldSend[], count = held.length): number {
+ let intact = 0
+
+ for (const send of held.splice(0, count)) {
+ intact += send.view.equals(send.sent)
+ ? 1
+ : 0
+ send.complete()
+ }
+
+ return intact
+}
+
+// Completes every send a socket holds, in the order they were made, answering the datagrams they sent.
+function flush(held: HeldSend[]): Buffer[] {
+ const sent = held.map(send => send.sent)
+
+ complete(held)
+
+ return sent
+}
+
+// Holds every packet each of a session's sockets is handed, as holdSends holds one socket's.
+function heldSockets(sessionSockets: Record): Record {
+ return {
+ video: holdSends(sessionSockets.video),
+ audio: holdSends(sessionSockets.audio),
+ }
+}
+
+// Whether a medium's packets, in the order a session sent them, carry sequence numbers that run on one at a time from the first, wrapping as RTP's do.
+function unbroken(packets: readonly Buffer[]): boolean {
+ return packets.every((packet, index) => ((packet.readUInt16BE(2) - packets[0].readUInt16BE(2)) & 0xFFFF) === index)
+}
+
+// A plain RTP packet: version 2, a payload type of 96 and an SSRC of its own, which a talkback row rewrites as a controller's.
+function rtpPacket(sequence: number, payloadLength: number): Buffer {
+ const packet = Buffer.alloc(12 + payloadLength)
+ packet[0] = 0x80
+ packet[1] = 96
+ packet.writeUInt16BE(sequence, 2)
+ packet.writeUInt32BE((sequence * 3000) >>> 0, 4)
+ packet.writeUInt32BE(0x01020304, 8)
+
+ for (let octet = 12; octet < packet.length; octet++) {
+ packet[octet] = (octet * 7 + sequence) & 0xFF
+ }
+
+ return packet
+}
+
+// Sends a datagram, already protected, from the controller's socket for a medium to the accessory's port for it.
+function sendDatagram(from: Endpoint, answer: Prepared, medium: StreamTierMedium, packet: Buffer): void {
+ const port = medium === 'video'
+ ? answer.accessoryAddress.videoRTPPort
+ : answer.accessoryAddress.audioRTPPort
+
+ from.sockets[medium].send(packet, port, '127.0.0.1')
+}
+
+// A plain talkback packet as a controller sends it: by default the fixture's audio payload type, 110, and the SSRC the controller's Start names for audio.
+function talkbackPacket(sequence: number, { payloadType = 110, ssrc = CONTROLLER_SSRCS.audio } = {}): Buffer {
+ const packet = rtpPacket(sequence, 40)
+ packet[1] = payloadType
+ packet.writeUInt32BE(ssrc, 8)
+
+ return packet
+}
+
+// The accessory's sockets for the session a row prepared last, as a createSocket spy saw them made: its last two, video then audio.
+function accessorySockets(createSocket: { mock: { results: { value: unknown }[] } }): Record {
+ const [video, audio] = createSocket.mock.results.slice(-2).map(result => result.value as Socket)
+
+ return { video, audio }
+}
+
+// The mocks are restored before the real timers return, which is why a row that spies on a mock timer leaves the real one in place for the rows after it.
+afterEach(async () => {
+ vi.restoreAllMocks()
+ vi.useRealTimers()
+
+ await Promise.all(managements.splice(0).map(async management => management.destroy()))
+ await Promise.all(sockets.splice(0).map(async socket => new Promise(resolve => socket.close(() => resolve()))))
+ // A closed socket leaves the process's resources a turn or two after its close callback: the next row reads its base only once every one has gone, and a
+ // socket a row leaves open holds this hook until it fails.
+ await until(() => udpSockets() === 0)
+})
+
+// Lets two turns of the event loop run, which a closed socket takes to leave the process's resources after its close callback returns.
+async function released(): Promise {
+ await settle()
+ await settle()
+}
+
+describe('multiTierStreamManagement', () => {
+ describe('construction and status active', () => {
+ it('builds the service under its sensor with streaming enabled and its static characteristics, and adopts a saved one with its streaming enabled', () => {
+ const { management, service } = harness()
+
+ expect(service.UUID).toBe(Service.CameraMultiTierRTPStreamManagement.UUID)
+ expect(service.subtype).toBe(SENSOR_UUID.toLowerCase())
+ expect(management.serviceKey).toBe(SERVICE_KEY)
+ expect(MultiTierStreamManagement.serviceKey(SENSOR_UUID)).toBe(SERVICE_KEY)
+ expect(service.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(true)
+ expect(service.getCharacteristic(Characteristic.SensorUUID).value).toBe(uuid.write(SENSOR_UUID).toString('base64'))
+ expect(service.getCharacteristic(Characteristic.SupportedVideoStreamTiers).value).toBe(encodeSupportedVideoStreamTiers(TIERS.videoStreamTiers))
+ expect(service.getCharacteristic(Characteristic.SupportedAudioStreamTiers).value).toBe(encodeSupportedAudioStreamTiers(TIERS.audioStreamTiers))
+ expect(service.getCharacteristic(Characteristic.SupportedRTPConfiguration).value).toBe('AgEA')
+ expect(service.getCharacteristic(Characteristic.SetupEndpoints).props).toMatchObject({ transient: true, sensitive: true })
+ expect(service.getCharacteristic(Characteristic.RTPStreamingControl).props.transient).toBe(true)
+
+ const saved = new Service.CameraMultiTierRTPStreamManagement('', 'saved')
+ saved.updateCharacteristic(Characteristic.StreamingEnabled, false)
+ const adopted = harness({ service: saved })
+
+ expect(adopted.service).toBe(saved)
+ expect(saved.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(false)
+ expect(saved.getCharacteristic(Characteristic.SupportedRTPConfiguration).value).toBe('AgEA')
+ })
+
+ it('writes status active from the policy at writeStatusActive, on for a camera that is on and off for one turned off before it, its configure services '
+ + 'writing none', () => {
+ const on = harness()
+ const saved = new Service.CameraMultiTierRTPStreamManagement('', 'saved')
+ saved.updateCharacteristic(Characteristic.StatusActive, true)
+ const off = harness({ configure: false, service: saved })
+ const read = (): unknown[] => [on, off].map(({ service }) => service.getCharacteristic(Characteristic.StatusActive).value)
+ off.global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+
+ off.management.configureServices()
+
+ const configured = read()
+
+ on.management.writeStatusActive()
+ off.management.writeStatusActive()
+
+ expect([
+ configured,
+ read(),
+ ]).toEqual([
+ [false, true],
+ [true, false],
+ ])
+ })
+
+ it('reads status active through the policy and refuses a start for a direct assignment the derivation never hears', async () => {
+ const { global, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const sessionIdentifier = crypto.randomUUID()
+ expect(await prepare(service, connection, from, sessionIdentifier)).toMatchObject({ status: SetupEndpointsStatus.SUCCESS })
+
+ global.getCharacteristic(Characteristic.HomeKitCameraActive).value = Characteristic.HomeKitCameraActive.OFF
+
+ expect(await start(service, connection, sessionIdentifier)).toBe(RTPStreamingStatus.ERROR)
+ await expect(service.getCharacteristic(Characteristic.StatusActive).handleGetRequest()).resolves.toBe(false)
+ })
+ })
+
+ describe('setup endpoints', () => {
+ it('answers success with the accessory\'s address, its two bound ports, its own keys and two 32-bit SSRCs, for the writer\'s read alone', async () => {
+ const { service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const sessionIdentifier = crypto.randomUUID()
+
+ const answer = await prepare(service, connection, from, sessionIdentifier)
+
+ expect(answer).toMatchObject({
+ status: SetupEndpointsStatus.SUCCESS,
+ sessionIdentifier,
+ accessoryAddress: { addressVersion: 'ipv4', address: '127.0.0.1' },
+ })
+
+ const { accessoryAddress, audioSRTPParameters, audioSSRC, videoSRTPParameters, videoSSRC } = answer as Prepared
+
+ expect(accessoryAddress.videoRTPPort).toBeGreaterThan(0)
+ expect(accessoryAddress.audioRTPPort).toBeGreaterThan(0)
+ expect(accessoryAddress.videoRTPPort).not.toBe(accessoryAddress.audioRTPPort)
+ for (const parameters of [videoSRTPParameters, audioSRTPParameters]) {
+ expect(parameters.cryptoSuite).toBe(SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80)
+ expect(parameters.masterKey).toHaveLength(16)
+ expect(parameters.masterSalt).toHaveLength(14)
+ expect(parameters.masterKey.equals(CONTROLLER_KEYS.video.masterKey)).toBe(false)
+ }
+ for (const ssrc of [videoSSRC, audioSSRC]) {
+ expect(Number.isInteger(ssrc) && ssrc >= 0 && ssrc < 0x100000000).toBe(true)
+ }
+ expect(videoSSRC).not.toBe(audioSSRC)
+ await expect(readSetupEndpoints(service, buildEmitterConnection())).resolves.toBe('AgEC')
+ await expect(readSetupEndpoints(service)).resolves.toBe('AgEC')
+ })
+
+ it('answers error naming the session for a refused suite, a short key, status active off and no local address, binding nothing', async () => {
+ const { service } = harness()
+ const from = await endpoint()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const refusedAs = async (connection: HAPConnection, request: string, sessionIdentifier: string): Promise => {
+ expect(await prepare(service, connection, from, sessionIdentifier, request)).toEqual({ status: SetupEndpointsStatus.ERROR, sessionIdentifier })
+ }
+
+ const suite = crypto.randomUUID()
+ await refusedAs(buildEmitterConnection(), setupRequest(from, suite, {
+ ...CONTROLLER_KEYS,
+ video: { ...CONTROLLER_KEYS.video, cryptoSuite: SRTPCryptoSuites.AES_CM_256_HMAC_SHA1_80 },
+ }), suite)
+
+ const key = crypto.randomUUID()
+ await refusedAs(buildEmitterConnection(), setupRequest(from, key, {
+ ...CONTROLLER_KEYS,
+ audio: {
+ ...CONTROLLER_KEYS.audio,
+ masterKey: Buffer.alloc(15, 0x33),
+ },
+ }), key)
+
+ const addressless = buildEmitterConnection()
+ vi.spyOn(addressless, 'getLocalAddress').mockImplementation(() => {
+ throw new Error('The interface has no IPv4 address.')
+ })
+ const local = crypto.randomUUID()
+ await refusedAs(addressless, setupRequest(from, local), local)
+
+ service.updateCharacteristic(Characteristic.StreamingEnabled, false)
+ const disabled = crypto.randomUUID()
+ await refusedAs(buildEmitterConnection(), setupRequest(from, disabled), disabled)
+
+ expect(createSocket).not.toHaveBeenCalled()
+ })
+
+ it('answers busy once prepared sessions over five connections fill the service, and admits a sixth at a maxSessions of 6', async () => {
+ const from = await endpoint()
+ const sessionIdentifier = crypto.randomUUID()
+ const filled = async (service: CameraMultiTierRTPStreamManagement): Promise => {
+ for (let index = 0; index < 5; index++) {
+ expect(await prepare(service, buildEmitterConnection(), from, crypto.randomUUID())).toMatchObject({ status: SetupEndpointsStatus.SUCCESS })
+ }
+ }
+
+ const { service } = harness()
+ await filled(service)
+
+ expect(await prepare(service, buildEmitterConnection(), from, sessionIdentifier)).toEqual({ status: SetupEndpointsStatus.BUSY, sessionIdentifier })
+
+ const wider = harness({ maxSessions: 6 })
+ await filled(wider.service)
+
+ expect(await prepare(wider.service, buildEmitterConnection(), from, sessionIdentifier)).toMatchObject({ status: SetupEndpointsStatus.SUCCESS })
+ })
+
+ it('answers error to another connection naming a held identifier, and unknown session identifier to its start and its end', async () => {
+ const { service } = harness()
+ const from = await endpoint()
+ const owner = buildEmitterConnection()
+ const other = buildEmitterConnection()
+ const sessionIdentifier = crypto.randomUUID()
+ await prepare(service, owner, from, sessionIdentifier)
+
+ expect(await prepare(service, other, from, sessionIdentifier)).toEqual({ status: SetupEndpointsStatus.ERROR, sessionIdentifier })
+ expect(await start(service, other, sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(await end(service, other, sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(await start(service, owner, sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ })
+
+ it('replaces a connection\'s prepared session at its next write, closing its sockets, and refuses a streaming session\'s identifier', async () => {
+ const { service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const first = crypto.randomUUID()
+ const second = crypto.randomUUID()
+
+ const replaced = await prepare(service, connection, from, first)
+ const again = await prepare(service, connection, from, first)
+ await released()
+
+ expect(again).toMatchObject({ status: SetupEndpointsStatus.SUCCESS, sessionIdentifier: first })
+ expect(again).not.toEqual(replaced)
+ expect(udpSockets()).toBe(base + 2)
+
+ expect(await prepare(service, connection, from, second)).toMatchObject({ status: SetupEndpointsStatus.SUCCESS })
+ await released()
+
+ expect(udpSockets()).toBe(base + 2)
+ expect(await start(service, connection, first)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(await start(service, connection, second)).toBe(RTPStreamingStatus.SUCCESS)
+ expect(await prepare(service, connection, from, second)).toEqual({ status: SetupEndpointsStatus.ERROR, sessionIdentifier: second })
+ })
+
+ it('ends a prepared session at the prepare timeout and releases its answer, and never a started one', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const base = udpSockets()
+ const idle = buildEmitterConnection()
+ const active = buildEmitterConnection()
+ const abandoned = crypto.randomUUID()
+ await prepare(service, idle, from, abandoned)
+ const started = await streaming(service, active, from)
+
+ // The started session's tier hands over pictures through the wait, which keeps its demand inside its silence bounds.
+ await keepStreaming([
+ streamOf(delegate),
+ ], 59999, { advance: advanceAsync })
+
+ expect(decodeSetupEndpointsResponse(await readSetupEndpoints(service, idle) as string)).toMatchObject({ status: SetupEndpointsStatus.SUCCESS })
+
+ await vi.advanceTimersByTimeAsync(1)
+ await until(() => udpSockets() === base + 2)
+
+ await expect(readSetupEndpoints(service, idle)).resolves.toBe('AgEC')
+ expect(await start(service, idle, abandoned)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(await end(service, active, started.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ await until(() => udpSockets() === base)
+ })
+
+ it('refuses an undecodable write to either control point and a plugin\'s write with invalid value in request, holding nothing', async () => {
+ const { service } = harness()
+ const connection = buildEmitterConnection()
+
+ for (const type of [Characteristic.SetupEndpoints, Characteristic.RTPStreamingControl]) {
+ const characteristic = service.getCharacteristic(type)
+ const plugin = encodeRTPStreamingControlRequest({ sessionIdentifier: UNKNOWN_SESSION, command: RTPStreamingCommand.END })
+
+ await expect(characteristic.handleSetRequest('AAAA', connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST)
+ await expect(characteristic.handleSetRequest(plugin)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST)
+ }
+
+ await expect(readSetupEndpoints(service, connection)).resolves.toBe('AgEC')
+ await expect(service.getCharacteristic(Characteristic.RTPStreamingControl).handleGetRequest(connection)).resolves.toBe('')
+ expect(connection.listenerCount('closed')).toBe(0)
+ })
+
+ it('writes the key and salt lengths in its debug events and never their bytes, in a sentence or in any detail', async () => {
+ const { service } = harness()
+ const from = await endpoint()
+ const events = captureDebugEvents('HAP-NodeJS:Camera:MultiTier')
+ const answer = await prepare(service, buildEmitterConnection(), from, crypto.randomUUID())
+ const { audioSRTPParameters, videoSRTPParameters } = answer as Prepared
+
+ // Each debug event is read whole, its sentence and every detail it carries, as a subscriber of the channel hears it.
+ const written = events.map(event => JSON.stringify(event))
+
+ expect(events.map(({ sentence }) => sentence).join('\n')).toContain('controller key lengths 16 and 16 and salt lengths 14 and 14')
+
+ for (const event of written) {
+ for (const secret of [
+ CONTROLLER_KEYS.video.masterKey,
+ CONTROLLER_KEYS.video.masterSalt,
+ CONTROLLER_KEYS.audio.masterKey,
+ CONTROLLER_KEYS.audio.masterSalt,
+ videoSRTPParameters.masterKey,
+ videoSRTPParameters.masterSalt,
+ audioSRTPParameters.masterKey,
+ audioSRTPParameters.masterSalt,
+ ]) {
+ expect(event).not.toContain(secret.toString('hex'))
+ expect(event).not.toContain(secret.toString('base64'))
+ }
+
+ expect(event).not.toContain('"type":"Buffer"')
+ }
+ })
+ })
+
+ describe('start and the tier demands', () => {
+ it('starts one demand for the video tier a Start joins, its picture and its sound alike, calling the delegate with the sensor, the tier and the '
+ + 'stream', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ await streaming(service, buildEmitterConnection(), from)
+
+ expect(delegate.tierDemandStarted.mock.calls).toEqual([
+ [
+ streamOf(delegate),
+ expect.any(AbortSignal),
+ ],
+ ])
+ expect(streamOf(delegate).tier).toMatchObject({
+ id: 1,
+ sensorUUID: SENSOR_UUID.toLowerCase(),
+ })
+ expect(streamOf(delegate).statistics().consumers).toBe(2)
+
+ // The plugin writes a keyframe, which the first session is sent, before a second session's Start joins the same demand.
+ writeTierFrame(streamOf(delegate), 'video', keyframeWithSets(sliceFrame(300)))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.video.length === 1)
+ await streaming(service, buildEmitterConnection(), from)
+
+ expect(delegate.tierDemandStarted).toHaveBeenCalledOnce()
+ })
+
+ it('calls the delegate once for each video tier a consumer raises, picture or sound, with the stream its demand hands out, and never for the audio tier',
+ async () => {
+ const { delegate, table } = harness()
+ const tiers = [
+ ...table.videoTiers.values(),
+ ]
+ const holds = tiers.map((tier, index) => table.joinFrames(tier, index === 0
+ ? 'audio'
+ : 'video', scriptedHolder(), scriptedFrameConsumer()))
+
+ expect(tiers.length).toBeGreaterThan(1)
+ expect(delegate.tierDemandStarted.mock.calls).toEqual(tiers.map(({ demand }) => [
+ demand,
+ expect.any(AbortSignal),
+ ]))
+ expect(streamsOf(delegate).map(({ tier }) => [tier.sensorUUID, tier.id])).toEqual(tiers.map(({ tierId }) => [
+ SENSOR_UUID.toLowerCase(),
+ tierId,
+ ]))
+
+ for (const hold of holds) {
+ hold.release()
+ }
+
+ await settle()
+ })
+
+ it('cuts a demand\'s frames at the size the listening family decides, a 1300-octet unit whole under IPv4 and in two fragments under the default', async () => {
+ const unit = nalUnit(SLICE, 1300)
+
+ for (const [family, types] of [
+ [
+ 'IPv4',
+ [1],
+ ],
+ [
+ 'IPv6',
+ [49, 49],
+ ],
+ ] as const) {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, family === 'IPv4'
+ ? buildEmitterConnection('IPv4')
+ : buildEmitterConnection(), from)
+
+ // The stream opens on a keyframe of one aggregation packet, and the unit's frame a frame's length after it is the one the row reads.
+ writeTierFrame(streamOf(delegate), 'video', keyframeWithSets(sliceFrame(300)))
+ writeTierFrame(streamOf(delegate), 'video', {
+ data: tierFrameData([unit]),
+ time: 33333,
+ })
+ await vi.advanceTimersByTimeAsync(34)
+ await until(() => from.received.video.length === 1 + types.length)
+ await settle()
+
+ const packets = unprotected(answer, from, 'video').slice(1)
+
+ // A single NAL unit packet carries the unit with its own header, and a fragmentation unit carries the bytes after that header behind three octets.
+ const data = packets.map(packet => packet.subarray(types.length === 1
+ ? 14
+ : 15))
+
+ expect({
+ family,
+ types: packets.map(packet => (packet[12] >> 1) & 0x3F),
+ }).toEqual({ family, types })
+ expect(Buffer.concat(data).equals(unit.subarray(SLICE.length))).toBe(true)
+ }
+ })
+
+ it('sends the session whose Start raises a demand the stream written inside its tierDemandStarted, timed and counted, throwing nothing from the write',
+ async () => {
+ // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone.
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const moment = performance.now()
+ const thrown: unknown[] = []
+ // A fragment of one picture sample of a 300-octet slice at a decode time, each run's first a keyframe carrying its parameter sets.
+ const picture = (decodeTime: bigint, keyframe = false): Buffer => tierStreamFragment({
+ picture: [
+ keyframe
+ ? keyframeSample()
+ : pictureSample(sliceFrame(300).data),
+ ],
+ pictureTime: decodeTime,
+ })
+
+ delegate.tierDemandStarted.mockImplementationOnce(async (stream) => {
+ const now = vi.spyOn(performance, 'now').mockReturnValue(moment)
+
+ try {
+ stream.write(tierStreamInitialization())
+ stream.write(picture(0n, true))
+ } catch (error) {
+ thrown.push(error)
+ } finally {
+ now.mockRestore()
+ }
+ })
+
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+ const opening = vi.spyOn(performance, 'now').mockReturnValue(moment)
+
+ await vi.advanceTimersByTimeAsync(0)
+ opening.mockRestore()
+
+ // A sample one interval after the first, five seconds later, is placed by its time's distance from the first, and the sample after a discontinuity at
+ // that moment at the moment's own timestamp: the reopened run stands 450000 ticks after the first sample, and the later sample one interval after it.
+ const later = vi.spyOn(performance, 'now').mockReturnValue(moment + 5000)
+ stream.write(picture(3000n))
+ stream.discontinuity()
+ stream.write(picture(0n, true))
+ await vi.advanceTimersByTimeAsync(0)
+ later.mockRestore()
+ await until(() => from.received.video.length === 3)
+
+ const [inside, placed, reopened] = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4))
+
+ expect(thrown).toEqual([])
+ expect([(placed - inside) >>> 0, (reopened - inside) >>> 0]).toEqual([3000, 450000])
+ expect(stream.statistics()).toEqual({
+ packets: 3,
+ bytes: 2 * (12 + setsAggregated(300)) + (12 + 300),
+ drops: 0,
+ consumers: 2,
+ })
+ })
+
+ it('sends the session whose Start raises a demand the picture and the sound its plugin writes inside tierDemandStarted, in a turn after the Start\'s '
+ + 'joins', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+
+ delegate.tierDemandStarted.mockImplementationOnce(async (stream) => {
+ stream.write(tierStreamInitialization())
+ stream.write(tierStreamFragment({
+ picture: [
+ keyframeSample(),
+ ],
+ sound: [
+ soundSample(Buffer.alloc(60, 0x78)),
+ ],
+ }))
+ })
+
+ const answer = await streaming(service, buildEmitterConnection(), from)
+
+ // Nothing is sent inside the plugin's call: the pacer sends the picture and the sound in its own turn.
+ expect(streamOf(delegate).statistics().packets).toBe(0)
+
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => (from.received.video.length === 1) && (from.received.audio.length === 1))
+
+ expect(unprotected(answer, from, 'video').map(packet => packet.subarray(12).length)).toEqual([
+ setsAggregated(300),
+ ])
+ expect(unprotected(answer, from, 'audio').map(packet => packet.subarray(12))).toEqual([
+ Buffer.alloc(60, 0x78),
+ ])
+ })
+
+ it('answers busy for a demand whose start rejects or never settles, the refused stream ignoring every write with no end sent, and one cut at its bound '
+ + 'withdrawn and ended once', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const refused = crypto.randomUUID()
+ await prepare(service, connection, from, refused)
+ delegate.tierDemandStarted.mockImplementation(async () => {
+ throw new Error('The encoder is busy.')
+ })
+
+ expect(await start(service, connection, refused)).toBe(RTPStreamingStatus.BUSY)
+ await settle()
+
+ // A stream of one picture sample and one sound sample larger than a payload, which a live demand would send and count as dropped.
+ const refusedStream = streamOf(delegate)
+ refusedStream.write(tierStreamInitialization())
+ refusedStream.write(tierStreamFragment({
+ picture: [
+ pictureSample(sliceFrame(300).data),
+ ],
+ sound: [
+ soundSample(Buffer.alloc(CUT)),
+ ],
+ }))
+
+ expect(endedCalls(delegate)).toBe(0)
+ expect(refusedStream.statistics()).toEqual({
+ packets: 0,
+ bytes: 0,
+ drops: 0,
+ consumers: 0,
+ })
+
+ delegate.tierDemandStarted.mockReset()
+ const pending = pendingStart(delegate)
+ const cut = start(service, connection, refused)
+ await vi.advanceTimersByTimeAsync(29999)
+
+ expect(warn).not.toHaveBeenCalled()
+
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect(await cut).toBe(RTPStreamingStatus.BUSY)
+ await settle()
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(warn.mock.calls[0][0]).toContain('did not settle tierDemandStarted for the video tier 1')
+ expect(endedCalls(delegate)).toBe(1)
+ expect(signalOf(delegate, streamOf(delegate)).aborted).toBe(true)
+
+ // The withdrawal released what the start registered, and its later settling releases nothing more.
+ pending.resolve()
+ await settle()
+
+ expect(disposedOf(delegate, streamOf(delegate))).toBe(1)
+ })
+
+ it('waits the delegate call bound for a start that never settles, answering the Start nothing before it, then answers busy with one warning', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const identifier = crypto.randomUUID()
+ await prepare(service, connection, from, identifier)
+ delegate.tierDemandStarted.mockImplementation(async () => new Promise(() => undefined))
+
+ let answered = false
+ const cut = start(service, connection, identifier).then((status) => {
+ answered = true
+
+ return status
+ })
+ await vi.advanceTimersByTimeAsync(29999)
+
+ expect(answered).toBe(false)
+ expect(warn).not.toHaveBeenCalled()
+
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect(await cut).toBe(RTPStreamingStatus.BUSY)
+ await settle()
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(warn.mock.calls[0][0]).toContain('did not settle tierDemandStarted for the video tier 1')
+ })
+
+ it('answers busy at the bound for a start that never settles, withdrawing the one demand it waited on for both media with one warning and ending it once',
+ async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const identifier = crypto.randomUUID()
+ await prepare(service, connection, from, identifier)
+ const pending = pendingStart(delegate)
+
+ const cut = start(service, connection, identifier)
+ await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT)
+
+ expect(await cut).toBe(RTPStreamingStatus.BUSY)
+ await settle()
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(delegate.tierDemandStarted).toHaveBeenCalledOnce()
+ expect(endedCalls(delegate)).toBe(1)
+ expect(signalOf(delegate, streamOf(delegate)).aborted).toBe(true)
+
+ // The withdrawal released what the start registered, and its later settling releases nothing more.
+ pending.resolve()
+ await settle()
+
+ expect(disposedOf(delegate, streamOf(delegate))).toBe(1)
+ })
+
+ it('answers busy at 30 seconds from the start\'s call, and nothing before, to a Start that joins at 20 seconds a pending demand whose earlier Start\'s '
+ + 'session closed at 10 seconds, with the demand\'s one warning and no other line, its session left prepared', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const earlierEndpoint = await endpoint()
+ const laterEndpoint = await endpoint()
+ const earlier = buildEmitterConnection()
+ const later = buildEmitterConnection()
+ const earlierIdentifier = crypto.randomUUID()
+ const laterIdentifier = crypto.randomUUID()
+ await prepare(service, earlier, earlierEndpoint, earlierIdentifier)
+ await prepare(service, later, laterEndpoint, laterIdentifier)
+ pendingStart(delegate)
+
+ // The earlier Start raises the demand and waits on it until its connection closes at 10 seconds, which leaves the demand ending.
+ const leaving = start(service, earlier, earlierIdentifier)
+ await vi.advanceTimersByTimeAsync(10000)
+ earlier.emit('closed')
+
+ expect(await leaving).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+
+ await vi.advanceTimersByTimeAsync(10000)
+
+ let answered = false
+ const joining = start(service, later, laterIdentifier).then((status) => {
+ answered = true
+
+ return status
+ })
+ await vi.advanceTimersByTimeAsync(9999)
+ await settle()
+
+ expect([answered, warn.mock.calls.length]).toEqual([false, 0])
+
+ await vi.advanceTimersByTimeAsync(1)
+ await settle()
+
+ expect(answered).toBe(true)
+ expect(await joining).toBe(RTPStreamingStatus.BUSY)
+ expect(warn.mock.calls).toEqual([
+ [
+ `MultiTierStreamingDelegate did not settle tierDemandStarted for the video tier 1 of the video sensor "${SENSOR_UUID.toLowerCase()}" within 30 `
+ + 'seconds: the demand is withdrawn and every join waiting on it is refused.',
+ ],
+ ])
+ expect(error).not.toHaveBeenCalled()
+
+ // The session stays prepared, and a Start retried on it raises a new demand, which starts.
+ expect(await start(service, later, laterIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2)
+ })
+
+ it('ends a demand whose last session leaves while its start is pending '
+ + 'once the start resolves or rejects, releasing what the start registered once', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+
+ for (const outcome of ['resolves', 'rejects'] as const) {
+ const connection = buildEmitterConnection()
+ const sessionIdentifier = crypto.randomUUID()
+ await prepare(service, connection, from, sessionIdentifier)
+ const pending = pendingStart(delegate)
+
+ const starting = start(service, connection, sessionIdentifier)
+ await settle()
+ connection.emit('closed')
+
+ expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ await settle()
+ expect(disposedOf(delegate, streamOf(delegate))).toBe(0)
+ expect(signalOf(delegate, streamOf(delegate)).aborted).toBe(false)
+
+ if (outcome === 'resolves') {
+ pending.resolve()
+ } else {
+ pending.reject(new Error('The video encoder failed to start.'))
+ }
+ await settle()
+
+ // A start that resolves ends its demand, and one that rejects is refused, each releasing once what the start registered.
+ expect({
+ outcome,
+ ended: disposedOf(delegate, streamOf(delegate)),
+ }).toEqual({
+ outcome,
+ ended: 1,
+ })
+ }
+ })
+
+ it('withdraws a demand whose start never settles at a reset or a destroy with one debug event and no warning or problem, and ends it no more at a later '
+ + 'reset or destroy', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+
+ for (const ending of ['reset', 'destroy'] as const) {
+ const { problems, reporter } = problemsOf()
+ const { delegate, management, service } = harness({ reporter })
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const sessionIdentifier = crypto.randomUUID()
+ await prepare(service, connection, from, sessionIdentifier)
+ const pending = pendingStart(delegate)
+ const events = captureDebugEvents('HAP-NodeJS:Camera:Tier')
+ warn.mockClear()
+
+ // The Start waits on its tier's demand, whose start never settles, until the reset or the destroy ends its session.
+ const starting = start(service, connection, sessionIdentifier)
+ await settle()
+
+ if (ending === 'reset') {
+ management.handleFactoryReset()
+ } else {
+ await management.destroy()
+ }
+
+ // The library withdraws the start for its own reasons, the plugin having done nothing wrong, which is why it writes a debug event and raises no problem.
+ const withdrawn = (): CameraDebugEvent[] => events.filter(({ kind }) => kind === 'start-withdrawn')
+
+ expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect({
+ ending,
+ ended: endedCalls(delegate),
+ problems: problems.length,
+ warnings: warn.mock.calls.length,
+ withdrawn: withdrawn().length,
+ }).toEqual({
+ ending,
+ ended: 1,
+ problems: 0,
+ warnings: 0,
+ withdrawn: 1,
+ })
+ expect(withdrawn().map(({ sensorUUID, sentence, tierId }) => ({
+ sensorUUID,
+ sentence,
+ tierId,
+ }))).toEqual([
+ {
+ sensorUUID: SENSOR_UUID.toLowerCase(),
+ sentence: `The library withdrew the pending start of the video tier 1 of the video sensor "${SENSOR_UUID.toLowerCase()}" when its service ended `
+ + 'every session: the demand is withdrawn and every join waiting on it is refused.',
+ tierId: 1,
+ },
+ ])
+
+ management.handleFactoryReset()
+ await management.destroy()
+ await settle()
+
+ expect({
+ ending,
+ ended: endedCalls(delegate),
+ problems: problems.length,
+ warnings: warn.mock.calls.length,
+ withdrawn: withdrawn().length,
+ }).toEqual({
+ ending,
+ ended: 1,
+ problems: 0,
+ warnings: 0,
+ withdrawn: 1,
+ })
+
+ // The withdrawal released what the start registered, and its later settling releases nothing more.
+ pending.resolve()
+ await settle()
+
+ expect(disposedOf(delegate, streamOf(delegate))).toBe(1)
+ }
+ })
+
+ it('releases what a streaming session\'s tier registered once, in its demand\'s end, at a reset that ends the session', async () => {
+ const { delegate, management, service, table } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+
+ await streaming(service, connection, from)
+
+ const stream = streamOf(delegate)
+ const tier = table.videoTiers.get(1)!
+ const inside: unknown[] = []
+
+ // A cleanup registered once the start settled, which reads where the release runs: the demand ended while its tier still holds it.
+ stream.defer(() => {
+ inside.push([(stream as TierDemand).state, tier.demand === stream])
+ })
+ management.handleFactoryReset()
+ await settle()
+ management.handleFactoryReset()
+ await settle()
+
+ expect([
+ inside,
+ disposedOf(delegate, stream),
+ tier.demand,
+ ]).toEqual([
+ [
+ [
+ 'ended',
+ true,
+ ],
+ ],
+ 1,
+ undefined,
+ ])
+ })
+
+ it('hands each demand\'s end the stream its start received, at its last consumer\'s leave and at a withdrawal', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, management, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expectEndsNameTheirStreams(delegate, 1)
+
+ // A second Start waits on video tier 2, whose start never settles, until a reset withdraws that demand.
+ const waiting = crypto.randomUUID()
+ await prepare(service, connection, from, waiting)
+ const pending = pendingStart(delegate)
+ const starting = start(service, connection, waiting, 2)
+ await settle()
+ management.handleFactoryReset()
+
+ // The reset's withdrawal is the library's own, which is why it prints no warning.
+ expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(warn).not.toHaveBeenCalled()
+ expectEndsNameTheirStreams(delegate, 2)
+
+ // The withdrawal released what the start registered, and its later settling releases nothing more.
+ pending.resolve()
+ await settle()
+
+ expect(disposedOf(delegate, streamOf(delegate, 2))).toBe(1)
+ })
+
+ it('keeps a busy start\'s joins off its session, which is why its prepare timeout leaves another session\'s tier alone, and joins anew at a retried '
+ + 'start', async () => {
+ // The steady clock is faked beside the timers, which keeps the pacer on the clock the other session's kept stream keeps step with.
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const other = await endpoint()
+ const busy = buildEmitterConnection()
+ const busyIdentifier = crypto.randomUUID()
+ await prepare(service, busy, from, busyIdentifier)
+ const rejectOnce = (): void => {
+ delegate.tierDemandStarted.mockImplementationOnce(async () => {
+ throw new Error('The encoder is busy.')
+ })
+ }
+
+ rejectOnce()
+ expect(await start(service, busy, busyIdentifier)).toBe(RTPStreamingStatus.BUSY)
+ await settle()
+
+ const streamer = buildEmitterConnection()
+ const streamed = await streaming(service, streamer, other)
+ const endedBefore = endedCalls(delegate)
+ // The other session's tier hands over pictures that are no keyframe through the busy session's prepare timeout, which keeps its demand inside its
+ // silence bounds and sends the session nothing before the keyframe after.
+ await keepStreaming([
+ streamOf(delegate),
+ ], 60000, { advance: advanceAsync })
+ await settle()
+
+ writeTierFrame(streamOf(delegate), 'video', {
+ ...vectorFrame(HEVC, 0, 60000000),
+ keyframe: true,
+ })
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => other.received.video.length === 1)
+
+ expect(endedCalls(delegate)).toBe(endedBefore)
+ expect(await end(service, streamer, streamed.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ await settle()
+
+ const retried = buildEmitterConnection()
+ const retriedIdentifier = crypto.randomUUID()
+ await prepare(service, retried, from, retriedIdentifier)
+ rejectOnce()
+
+ expect(await start(service, retried, retriedIdentifier)).toBe(RTPStreamingStatus.BUSY)
+ expect(await start(service, retried, retriedIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+
+ const endedRetried = endedCalls(delegate)
+ expect(await end(service, retried, retriedIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ await settle()
+
+ expect(endedCalls(delegate) - endedRetried).toBe(1)
+ })
+
+ it('keeps a demand whose only session left while its start was pending for a session that joins it, which it starts and serves with no end sent', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const leavingEndpoint = await endpoint()
+ const joiningEndpoint = await endpoint()
+ const closing = buildEmitterConnection()
+ const joining = buildEmitterConnection()
+ const left = crypto.randomUUID()
+ const joined = crypto.randomUUID()
+ const pending = deferred()
+ await prepare(service, closing, leavingEndpoint, left)
+ const answer = await prepare(service, joining, joiningEndpoint, joined) as Prepared
+ pendingStart(delegate, pending)
+
+ // The first Start waits on its tier's demand until its connection closes, which leaves the demand with no session while its start is still pending.
+ const leaving = start(service, closing, left)
+ await settle()
+ closing.emit('closed')
+
+ expect(await leaving).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+
+ const joiningStart = start(service, joining, joined)
+ await settle()
+ pending.resolve()
+
+ expect(await joiningStart).toBe(RTPStreamingStatus.SUCCESS)
+
+ const stream = streamOf(delegate)
+ writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300)))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => joiningEndpoint.received.video.length === 1)
+
+ expect(delegate.tierDemandStarted).toHaveBeenCalledOnce()
+ expect(endedCalls(delegate)).toBe(0)
+ expect(unprotected(answer, joiningEndpoint, 'video')).toHaveLength(1)
+ expect(stream.statistics()).toMatchObject({ packets: 1, consumers: 2 })
+ })
+
+ it('ends a session waiting on a demand whose stream fails after its start returned a pending promise, and ends the demand once its start settles', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const identifier = crypto.randomUUID()
+ const pending = deferred()
+ await prepare(service, connection, from, identifier)
+ pendingStart(delegate, pending)
+
+ const starting = start(service, connection, identifier)
+ await settle()
+ streamOf(delegate).fail('The encoder crashed.')
+
+ expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ await settle()
+ expect(endedCalls(delegate)).toBe(0)
+
+ pending.resolve()
+ await settle()
+
+ expect(endedCalls(delegate)).toBe(1)
+ expect(warn).toHaveBeenCalledOnce()
+ })
+
+ it('logs a rejected tierDemandStarted once under its sentence', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const identifier = crypto.randomUUID()
+ await prepare(service, connection, from, identifier)
+ delegate.tierDemandStarted.mockImplementationOnce(async () => {
+ throw new Error('The video encoder is busy.')
+ })
+
+ expect(await start(service, connection, identifier)).toBe(RTPStreamingStatus.BUSY)
+ await settle()
+
+ expect(error).toHaveBeenCalledOnce()
+ expect(String(error.mock.calls[0][0])).toMatch(/^MultiTierStreamingDelegate failed to start a tier demand: /)
+ })
+
+ it('refuses a demand whose tierDemandStarted throws in the calling turn as a rejection refuses it, answering busy and logging the throw once', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const identifier = crypto.randomUUID()
+ await prepare(service, connection, from, identifier)
+ delegate.tierDemandStarted.mockImplementationOnce(() => {
+ throw new Error('The video encoder is busy.')
+ })
+
+ expect(await start(service, connection, identifier)).toBe(RTPStreamingStatus.BUSY)
+ await settle()
+
+ const stream = streamOf(delegate)
+ writeTierFrame(stream, 'video', sliceFrame(300))
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(error).toHaveBeenCalledOnce()
+ expect(String(error.mock.calls[0][0])).toMatch(/^MultiTierStreamingDelegate failed to start a tier demand: /)
+ expect(stream.statistics()).toEqual({
+ packets: 0,
+ bytes: 0,
+ drops: 0,
+ consumers: 0,
+ })
+ expect(endedCalls(delegate)).toBe(0)
+ })
+
+ it('leaves no sender of a session whose Start is answered busy on its tier, none on its media, and the tier another session streams as it was', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, management, service } = harness()
+ const streamingEndpoint = await endpoint()
+ const refusedEndpoint = await endpoint()
+ await streaming(service, buildEmitterConnection(), streamingEndpoint)
+ const connection = buildEmitterConnection()
+ const refused = crypto.randomUUID()
+ await prepare(service, connection, refusedEndpoint, refused)
+
+ // The refused Start raises video tier 2, whose start rejects, beside tier 1, which the first session streams.
+ delegate.tierDemandStarted.mockImplementationOnce(async () => {
+ throw new Error('The second encoder is busy.')
+ })
+
+ expect(await start(service, connection, refused, 2)).toBe(RTPStreamingStatus.BUSY)
+
+ // @ts-expect-error: private access
+ const { media } = management.sessions.get(refused)
+
+ expect(streamOf(delegate, 1).statistics().consumers).toBe(2)
+ expect(streamOf(delegate, 2).statistics().consumers).toBe(0)
+ expect([media.video.sender, media.audio.sender]).toEqual([undefined, undefined])
+ })
+
+ it('sends a session waiting on its pending video demand each frame the plugin writes during the wait, and streams it on once the demand starts', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const identifier = crypto.randomUUID()
+ const pending = deferred()
+ const answer = await prepare(service, connection, from, identifier) as Prepared
+ pendingStart(delegate, pending)
+
+ const starting = start(service, connection, identifier)
+ await settle()
+ const stream = streamOf(delegate)
+
+ expect(stream.statistics().consumers).toBe(2)
+
+ writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0)))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.video.length === 1)
+ pending.resolve()
+
+ expect(await starting).toBe(RTPStreamingStatus.SUCCESS)
+
+ // Written at the first frame's moment, the frame a frame's length later is due that length after it.
+ writeTierFrame(stream, 'video', sliceFrame(300, 33333))
+ await vi.advanceTimersByTimeAsync(34)
+ await until(() => from.received.video.length === 2)
+
+ expect(unprotected(answer, from, 'video').map(packet => packet.subarray(12).length)).toEqual([
+ setsAggregated(300),
+ 300,
+ ])
+ expect(stream.statistics()).toMatchObject({ packets: 2, consumers: 2 })
+ })
+
+ it('ends the session whose Start raised a demand its plugin fails inside tierDemandStarted, answering the Start unknown', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const base = udpSockets()
+ const connection = buildEmitterConnection()
+ const identifier = crypto.randomUUID()
+ await prepare(service, connection, from, identifier)
+ delegate.tierDemandStarted.mockImplementationOnce((stream) => {
+ stream.use(disposableFor(delegate, stream))
+ stream.fail('The encoder failed to open.')
+ })
+
+ expect(await start(service, connection, identifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(delegate.tierDemandStarted).toHaveBeenCalledOnce()
+ expect(warn).toHaveBeenCalledOnce()
+ expect(endedCalls(delegate)).toBe(1)
+ expect(await end(service, connection, identifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ })
+
+ it('tells of no view for a Start answered busy, unknown session identifier or error, nor as each of those sessions ends', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const views: string[] = []
+ const { delegate, service } = harness({
+ onLiveViewEnded: () => views.push('ended'),
+ onLiveViewStarted: () => views.push('started'),
+ })
+ const from = await endpoint()
+ const base = udpSockets()
+ // Each session prepared on a connection of its own, which holds one prepared session at a time.
+ const sessions = Array.from({ length: 3 }, () => ({
+ connection: buildEmitterConnection(),
+ identifier: crypto.randomUUID(),
+ }))
+ const [busy, unknown, refused] = sessions
+
+ for (const { connection, identifier } of sessions) {
+ await prepare(service, connection, from, identifier)
+ }
+
+ // A demand whose start rejects answers busy, one whose plugin fails its stream inside its start answers unknown, and a Start naming a video tier the
+ // sensor does not offer answers error.
+ delegate.tierDemandStarted.mockImplementationOnce(async () => {
+ throw new Error('The encoder is busy.')
+ })
+
+ expect(await start(service, busy.connection, busy.identifier)).toBe(RTPStreamingStatus.BUSY)
+
+ await settle()
+ delegate.tierDemandStarted.mockImplementationOnce((stream) => {
+ stream.fail('The encoder failed to open.')
+ })
+
+ expect(await start(service, unknown.connection, unknown.identifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(await start(service, refused.connection, refused.identifier, 9)).toBe(RTPStreamingStatus.ERROR)
+
+ for (const { connection, identifier } of sessions) {
+ await end(service, connection, identifier)
+ }
+
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(views).toEqual([])
+ })
+ })
+
+ describe('the tier stream', () => {
+ it('sends each of two sessions at home on two tiers the sound of its own tier\'s stream under the audio tier\'s payload type, and none of the other\'s',
+ async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const firstEndpoint = await endpoint()
+ const secondEndpoint = await endpoint()
+ const first = await streaming(service, buildEmitterConnection(), firstEndpoint, 1)
+ const second = await streaming(service, buildEmitterConnection(), secondEndpoint, 2)
+
+ writeTierFrame(streamOf(delegate, 1), 'audio', {
+ data: Buffer.alloc(60, 1),
+ time: 0,
+ })
+ writeTierFrame(streamOf(delegate, 2), 'audio', {
+ data: Buffer.alloc(60, 2),
+ time: 0,
+ })
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => firstEndpoint.received.audio.length === 1 && secondEndpoint.received.audio.length === 1)
+ await settle()
+
+ for (const [answer, from, tag] of [
+ [first, firstEndpoint, 1],
+ [second, secondEndpoint, 2],
+ ] as const) {
+ const packets = unprotected(answer, from, 'audio')
+
+ expect(packets.map(packet => packet.subarray(12).toString('hex'))).toEqual([
+ Buffer.alloc(60, tag).toString('hex'),
+ ])
+ expect(packets.map(packet => packet[1] & 0x7F)).toEqual([110])
+ }
+ })
+
+ it('sends a stream with no Opus track as a tier without sound, its picture sent and nothing failed or warned', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ const stream = streamOf(delegate)
+
+ // A fragment carrying a run of a second track beside the picture, which a stream with no Opus track does not describe.
+ stream.write(tierStreamInitialization({ sound: false }))
+ stream.write(tierStreamFragment({
+ picture: [
+ keyframeSample(),
+ ],
+ sound: [
+ soundSample(Buffer.alloc(60, 7)),
+ ],
+ }))
+ await until(() => from.received.video.length === 1)
+ await settle()
+
+ expect(from.received.audio).toEqual([])
+ expect(warn).not.toHaveBeenCalled()
+ expect(stream.statistics()).toEqual({
+ packets: 1,
+ bytes: 12 + setsAggregated(300),
+ drops: 0,
+ consumers: 2,
+ })
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ })
+
+ it('counts both media in the stream\'s statistics: each packet of picture and of sound sent, their bytes, and each sample of either dropped', async () => {
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+
+ stream.write(tierStreamInitialization())
+ stream.write(tierStreamFragment({
+ picture: [
+ keyframeSample(),
+ pictureSample(Buffer.from('0000000a0201', 'hex')),
+ ],
+ sound: [
+ soundSample(Buffer.alloc(60, 7)),
+ soundSample(Buffer.alloc(0)),
+ ],
+ }))
+ await until(() => from.received.video.length === 1 && from.received.audio.length === 1)
+
+ expect(stream.statistics()).toEqual({
+ packets: 2,
+ bytes: (12 + setsAggregated(300)) + (12 + 60),
+ drops: 2,
+ consumers: 2,
+ })
+ })
+
+ it('fails the tier with one warning, every session on it ending, for a stream the library refuses: one with no video track, one whose video track has '
+ + 'a timescale of 0, and one holding a malformed box', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const opus = {
+ handler: 'soun',
+ id: 2,
+ sampleEntry: opusSampleEntry(),
+ timescale: 48000,
+ }
+ const refusals: [Buffer[], string][] = [
+ [
+ [
+ initializationSegment(opus),
+ ],
+ 'The stream\'s initialization segment holds no video track.',
+ ],
+ [
+ [
+ initializationSegment({
+ handler: 'vide',
+ id: 1,
+ sampleEntry: visualSampleEntry('hvc1', 64, 36, hvcC([])),
+ timescale: 0,
+ }, opus),
+ ],
+ 'The stream\'s initialization segment holds no video track.',
+ ],
+ [
+ [
+ tierStreamInitialization(),
+ Buffer.from('0000000466726565', 'hex'),
+ ],
+ 'The stream holds a malformed box, whose size is under its header\'s.',
+ ],
+ ]
+
+ for (const [chunks, reason] of refusals) {
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const base = udpSockets()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+
+ warn.mockClear()
+
+ for (const chunk of chunks) {
+ streamOf(delegate).write(chunk)
+ }
+
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(warn.mock.calls).toEqual([
+ [`The library refused the stream of the video tier 1 of the video sensor "${SENSOR_UUID.toLowerCase()}" (${reason}), and every session on the tier ends.`],
+ ])
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(endedCalls(delegate)).toBe(1)
+ }
+ })
+
+ it('fails the tier with one warning carrying the reader\'s sentence, every session on it ending, for a stream whose sound repeats a decode time', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const base = udpSockets()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ const stream = streamOf(delegate)
+
+ // A fragment and one a frame after it, whose sound stands at the decode time of the first one's.
+ stream.write(tierStreamInitialization())
+
+ for (const pictureTime of [0n, 3000n]) {
+ stream.write(tierStreamFragment({
+ picture: [
+ pictureSample(sliceFrame(300).data),
+ ],
+ pictureTime,
+ sound: [
+ soundSample(Buffer.alloc(60, 7)),
+ ],
+ }))
+ }
+
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(warn.mock.calls).toEqual([
+ [`The library refused the stream of the video tier 1 of the video sensor "${SENSOR_UUID.toLowerCase()}" (The stream's audio track's decode times do `
+ + 'not rise: a sample is timed at or before the one before it.), and every session on the tier ends.'],
+ ])
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(endedCalls(delegate)).toBe(1)
+ })
+
+ it('opens a new run of times for both media at the stream\'s discontinuity, each at its own rate', async () => {
+ // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds.
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+ const moment = performance.now()
+ // A fragment of one picture sample and one sound sample at the decode times given, its picture a keyframe where it opens a run.
+ const fragment = (pictureTime: bigint, soundTime: bigint, keyframe = false): Buffer => tierStreamFragment({
+ picture: [
+ keyframe
+ ? keyframeSample()
+ : pictureSample(sliceFrame(300).data),
+ ],
+ pictureTime,
+ sound: [
+ soundSample(Buffer.alloc(60, 7)),
+ ],
+ soundTime,
+ })
+ // Each medium's packets' timestamps, less its first.
+ const steps = (medium: StreamTierMedium): number[] => {
+ const timestamps = unprotected(answer, from, medium).map(packet => packet.readUInt32BE(4))
+
+ return timestamps.slice(1).map(timestamp => (timestamp - timestamps[0]) >>> 0)
+ }
+
+ // Five seconds after the first samples, a sample of each medium one step on keeps its run, and after the discontinuity each medium's next sample
+ // opens a run of its own at that moment's timestamp at its own rate.
+ const now = vi.spyOn(performance, 'now').mockReturnValue(moment)
+ stream.write(tierStreamInitialization())
+ stream.write(fragment(0n, 0n, true))
+ await vi.advanceTimersByTimeAsync(0)
+ now.mockReturnValue(moment + 5000)
+ stream.write(fragment(3000n, 960n))
+ stream.discontinuity()
+ stream.write(fragment(0n, 0n, true))
+ await vi.advanceTimersByTimeAsync(0)
+ now.mockRestore()
+ await until(() => from.received.video.length === 3 && from.received.audio.length === 3)
+
+ expect(steps('video')).toEqual([3000, 5000 * 90])
+ expect(steps('audio')).toEqual([960, 5000 * 48])
+ })
+
+ it('places a picture and a sound written a fragment after it on one run, each at its presentation time\'s distance from the run\'s origin at its own '
+ + 'rate, whatever its arrival', async () => {
+ // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds.
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const origin = performance.now()
+ const made = vi.spyOn(performance, 'now').mockReturnValue(origin)
+ const { delegate, service } = harness()
+ made.mockRestore()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+
+ // A fragment of a keyframe alone decoded at 1 s arrives a second after the clock's making, and half a second later a fragment of the next picture and
+ // a sound presented at 1.02 s.
+ const now = vi.spyOn(performance, 'now').mockReturnValue(origin + 1000)
+ stream.write(tierStreamInitialization())
+ stream.write(tierStreamFragment({
+ picture: [
+ keyframeSample(),
+ ],
+ pictureTime: 90000n,
+ }))
+ await vi.advanceTimersByTimeAsync(0)
+ now.mockReturnValue(origin + 1500)
+ stream.write(tierStreamFragment({
+ picture: [
+ pictureSample(sliceFrame(300).data),
+ ],
+ pictureTime: 93000n,
+ sound: [
+ soundSample(Buffer.alloc(60, 7)),
+ ],
+ soundTime: 48960n,
+ }))
+ await vi.advanceTimersByTimeAsync(0)
+ now.mockRestore()
+ await until(() => from.received.video.length === 2 && from.received.audio.length === 1)
+
+ const [picture, next] = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4))
+ const [sound] = unprotected(answer, from, 'audio').map(packet => packet.readUInt32BE(4))
+
+ // The run opened at the first picture's arrival, a second into the clock: the clock's offset stands 90,000 ticks before that picture, and the
+ // sound stands 20 ms of its own ticks after the second the run opened at, not at its own arrival half a second later.
+ expect((next - picture) >>> 0).toBe(3000)
+ expect((picture - 90000) >>> 0).toBe((sound - 48000 - 960) >>> 0)
+ })
+
+ it('sends a view at home no sound while the camera\'s Microphone is muted and its picture all the while, and unmuted the next sound at the timestamp the '
+ + 'clock gives it, unmarked, as if none were withheld', async () => {
+ // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds.
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const origin = performance.now()
+ const made = vi.spyOn(performance, 'now').mockReturnValue(origin)
+ const { delegate, service, table } = harness()
+ made.mockRestore()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+
+ table.muteMicrophone(true)
+
+ // A second after the clock's making, a fragment of a keyframe decoded at 1 s with sounds presented with it and 20 ms after it opens the run, the run's
+ // first sound among those the mute holds back, and once the mute is off a fragment of the next picture and a sound presented at 1.04 s.
+ const now = vi.spyOn(performance, 'now').mockReturnValue(origin + 1000)
+ stream.write(tierStreamInitialization())
+ stream.write(tierStreamFragment({
+ picture: [
+ keyframeSample(),
+ ],
+ pictureTime: 90000n,
+ sound: [
+ soundSample(Buffer.alloc(60, 1)),
+ soundSample(Buffer.alloc(60, 2)),
+ ],
+ soundTime: 48000n,
+ }))
+ await vi.advanceTimersByTimeAsync(0)
+ now.mockReturnValue(origin + 1500)
+ await vi.advanceTimersByTimeAsync(20)
+ await until(() => from.received.video.length === 1)
+ table.muteMicrophone(false)
+ stream.write(tierStreamFragment({
+ picture: [
+ pictureSample(sliceFrame(300).data),
+ ],
+ pictureTime: 93000n,
+ sound: [
+ soundSample(Buffer.alloc(60, 3)),
+ ],
+ soundTime: 49920n,
+ }))
+ // The sound falls due by its own decode time, 7 ms after the fragment's picture.
+ now.mockReturnValue(origin + 1510)
+ await vi.advanceTimersByTimeAsync(10)
+ now.mockRestore()
+ await until(() => from.received.video.length === 2 && from.received.audio.length === 1)
+ await settle()
+
+ const [picture] = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4))
+ const sounds = unprotected(answer, from, 'audio')
+
+ // The sound sent is the one written once the mute was off, 40 ms of its own ticks after the second the run opened at, and it carries no marker, since
+ // the run's first sound was placed as the mute held it back.
+ expect(sounds.map(packet => packet.subarray(12))).toEqual([
+ Buffer.alloc(60, 3),
+ ])
+ expect((picture - 90000) >>> 0).toBe((sounds[0].readUInt32BE(4) - 48000 - 1920) >>> 0)
+ expect(sounds[0][1] & 0x80).toBe(0)
+ })
+
+ it('opens each later run at a mark, an initialization segment and a forward jump past the highest timestamp placed for each medium, at one moment '
+ + 'for picture and sound, and marks each run\'s first sound where a picture opened the run', async () => {
+ // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds. Its
+ // origin is a whole millisecond, which is why the last run's latest samples fall due exactly 60 ms after its first picture: on a fractional origin that sum can
+ // round up, which arms the pacer's timer a millisecond past the row's 60 ms step and leaves them unsent.
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const origin = Math.ceil(performance.now())
+ const made = vi.spyOn(performance, 'now').mockReturnValue(origin)
+ const { delegate, service } = harness()
+ made.mockRestore()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+ // A run's fragment: pictures decoded a frame apart from the decode time given, the first a keyframe, each presented two frames after its decode time,
+ // and sounds a packet apart from that decode time, each presented before the first picture.
+ const run = (decodeTime: bigint): Buffer => tierStreamFragment({
+ picture: [0, 1].map(index => ({
+ ...(index === 0
+ ? keyframeSample()
+ : pictureSample(sliceFrame(300).data)),
+ compositionOffset: 6000,
+ })),
+ pictureTime: decodeTime,
+ sound: [0, 1, 2, 3].map(index => soundSample(Buffer.alloc(60, index + 1))),
+ soundTime: decodeTime * 48000n / 90000n,
+ })
+
+ // Every run arrives in one moment, a second into the clock: the first, one after a mark, one after a new initialization segment, and one whose decode
+ // times leap ten seconds ahead with no mark.
+ const now = vi.spyOn(performance, 'now').mockReturnValue(origin + 1000)
+ stream.write(tierStreamInitialization())
+ stream.write(run(0n))
+ stream.discontinuity()
+ stream.write(run(0n))
+ stream.write(tierStreamInitialization())
+ stream.write(run(0n))
+ stream.write(run(900000n))
+ await vi.advanceTimersByTimeAsync(0)
+
+ // The ended runs leave at once, and the last run's later samples at their decode times' distance from its first picture, the latest 60 ms on.
+ now.mockReturnValue(origin + 1060)
+ await vi.advanceTimersByTimeAsync(60)
+ now.mockRestore()
+ await until(() => from.received.video.length === 8 && from.received.audio.length === 16)
+
+ const sounds = unprotected(answer, from, 'audio')
+ // Each timestamp less the clock's offset, which the first run, opened a second into the clock, places its first picture two frames past.
+ const offset = (unprotected(answer, from, 'video')[0].readUInt32BE(4) - 90000 - 6000) >>> 0
+ const ticks = (packets: Buffer[]): number[] => packets.map(packet => (packet.readUInt32BE(4) - offset) >>> 0)
+ const pictureRuns = [0, 2, 4, 6].map(first => ticks(unprotected(answer, from, 'video')).slice(first, first + 2))
+ const soundRuns = [0, 4, 8, 12].map(first => ticks(sounds).slice(first, first + 4))
+
+ // Each run's samples stand past every earlier one of their medium, and the moment each run opened at, read from its first picture less its two frames
+ // and from its first sound, is one moment for picture and sound to within a tick.
+ for (const runs of [pictureRuns, soundRuns]) {
+ expect(runs.slice(1).every((samples, index) => Math.min(...samples) > Math.max(...runs.slice(0, index + 1).flat()))).toBe(true)
+ }
+
+ expect(pictureRuns.map(([first], index) => Math.abs((first - 6000) / 90 - soundRuns[index][0] / 48) < 1 / 48)).toEqual([true, true, true, true])
+ expect(sounds.map(packet => (packet[1] & 0x80) !== 0)).toEqual([0, 1, 2, 3].flatMap(() => [true, false, false, false]))
+ })
+
+ it('lets a sound timed before its run\'s origin go and counts it, places a picture timed before the origin of a run a sound opened at that run\'s '
+ + 'opening, and sends that run\'s sound with no picture written', async () => {
+ // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds.
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const origin = performance.now()
+ const made = vi.spyOn(performance, 'now').mockReturnValue(origin)
+ const { delegate, service } = harness()
+ made.mockRestore()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+
+ // A second into the clock, a run a keyframe decoded at 1 s opens, whose fragment carries a sound timed 20 ms before that keyframe and one timed with
+ // it.
+ const now = vi.spyOn(performance, 'now').mockReturnValue(origin + 1000)
+ stream.write(tierStreamInitialization())
+ stream.write(tierStreamFragment({
+ picture: [
+ keyframeSample(),
+ ],
+ pictureTime: 90000n,
+ sound: [
+ soundSample(Buffer.alloc(60, 1)),
+ soundSample(Buffer.alloc(60, 2)),
+ ],
+ soundTime: 47040n,
+ }))
+ await vi.advanceTimersByTimeAsync(0)
+
+ // A second later, after a mark, sounds timed from 5 s open a run, and a keyframe decoded at 4.9 s follows them.
+ now.mockReturnValue(origin + 2000)
+ stream.discontinuity()
+ stream.write(tierStreamFragment({
+ sound: [
+ soundSample(Buffer.alloc(60, 3)),
+ soundSample(Buffer.alloc(60, 4)),
+ ],
+ soundTime: 240000n,
+ }))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.audio.length === 3)
+
+ const sentAlone = from.received.video.length
+
+ stream.write(tierStreamFragment({
+ picture: [
+ keyframeSample(),
+ ],
+ pictureTime: 441000n,
+ }))
+ await vi.advanceTimersByTimeAsync(0)
+ now.mockRestore()
+ await until(() => from.received.video.length === 2)
+
+ const offset = (unprotected(answer, from, 'video')[0].readUInt32BE(4) - 90000) >>> 0
+ const ticks = (medium: StreamTierMedium): number[] => unprotected(answer, from, medium).map(packet => (packet.readUInt32BE(4) - offset) >>> 0)
+
+ expect([sentAlone, stream.statistics().drops]).toEqual([1, 1])
+ expect([
+ ticks('video'),
+ ticks('audio'),
+ ]).toEqual([
+ [90000, 180000],
+ [48000, 96000, 96960],
+ ])
+ })
+
+ it('sends a picture sample with a composition offset, written through the TierStream, at its decode time plus that offset, read from its packets\' RTP '
+ + 'timestamp beside samples with none', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+
+ // Pictures decoded 3000 ticks apart from zero from a keyframe, the second presented 6000 ticks after its decode time, each one packet.
+ stream.write(tierStreamInitialization())
+ stream.write(tierStreamFragment({
+ picture: [
+ keyframeSample(),
+ {
+ ...pictureSample(sliceFrame(300).data),
+ compositionOffset: 6000,
+ },
+ pictureSample(sliceFrame(300).data),
+ ],
+ }))
+ // The fragment's later pictures leave at their decode times' distance from its first, the last two frames on.
+ await vi.advanceTimersByTimeAsync(67)
+ await until(() => from.received.video.length === 3)
+
+ const timestamps = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4))
+
+ expect(timestamps.slice(1).map(timestamp => (timestamp - timestamps[0]) >>> 0)).toEqual([9000, 6000])
+ })
+
+ it('makes no frame form for a half no consumer is joined to, a keyframe copied for none, and places its run all the same', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, table } = harness()
+ const tier = table.videoTiers.get(1)!
+ const sound = scriptedFrameConsumer()
+ const picture = scriptedFrameConsumer()
+
+ expect(await table.joinFrames(tier, 'audio', scriptedHolder(), sound).answer()).toBe('started')
+
+ const stream = streamOf(delegate)
+
+ stream.write(tierStreamInitialization({
+ parameterSets: [32, 33, 34].map(type => nalUnit(Buffer.from([type << 1, 0x01]), 12)),
+ }))
+
+ // A keyframe of the picture, which no consumer takes, beside a sound sample, which one does: the frame form of the keyframe is the one copy a whole
+ // fragment's reading would make.
+ const fragment = tierStreamFragment({
+ picture: [
+ pictureSample(sliceFrame(300).data, true),
+ ],
+ sound: [
+ soundSample(Buffer.alloc(60, 7)),
+ ],
+ })
+ const concat = vi.spyOn(Buffer, 'concat')
+ stream.write(fragment)
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(concat).not.toHaveBeenCalled()
+ expect(sound.taken).toHaveLength(1)
+
+ concat.mockRestore()
+ table.joinFrames(tier, 'video', scriptedHolder(), picture)
+ stream.write(tierStreamFragment({
+ picture: [
+ pictureSample(sliceFrame(300).data),
+ ],
+ pictureTime: 3000n,
+ }))
+ await vi.advanceTimersByTimeAsync(34)
+
+ // The picture's consumer joins behind the keyframe the pacer released to no one: its opening hands it that keyframe first, at the next picture's
+ // release, with the run-opening flag unset, which a live release alone carries.
+ expect(picture.taken.map(({ frame, opensRun }) => [frame.time, opensRun])).toEqual([
+ [0, false],
+ [33333, false],
+ ])
+ })
+
+ it('writes the debug event of a withdrawn demand naming its video tier, and no warning', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, management, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ await streaming(service, connection, from)
+
+ // A second Start waits on video tier 2, whose start never settles, until a reset withdraws its demand.
+ const waiting = crypto.randomUUID()
+ await prepare(service, connection, from, waiting)
+ delegate.tierDemandStarted.mockImplementationOnce(async () => new Promise(() => undefined))
+ const lines = captureDebug('HAP-NodeJS:Camera:Tier')
+ const starting = start(service, connection, waiting, 2)
+ await settle()
+ management.handleFactoryReset()
+
+ expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(lines.filter(line => line.startsWith('The library withdrew'))).toEqual([
+ `The library withdrew the pending start of the video tier 2 of the video sensor "${SENSOR_UUID.toLowerCase()}" when its service ended every `
+ + 'session: the demand is withdrawn and every join waiting on it is refused.',
+ ])
+ expect(warn).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('a view at home of a shared sensor', () => {
+ // The fixture's sensor with its audio shared: its sound tier is the tier the camera records, its best, tier 1, and every other tier's Opus is ignored.
+ const SHARED_TIERS = tierSetOf(videoSensor(SENSOR_UUID, {
+ audio: {
+ bitrate: 24,
+ source: 'shared',
+ },
+ }))
+
+ // Scripts the first start of the video tier given to wait on the deferred it answers, every other start starting at once as the scripted delegate's does.
+ function pendingFirstStart(delegate: ScriptedTierDelegate, tierId: number, pending: Deferred = deferred()): Deferred {
+ const started = delegate.tierDemandStarted.getMockImplementation()!
+ let pended = false
+
+ delegate.tierDemandStarted.mockImplementation(async (stream, signal) => {
+ await started(stream, signal)
+
+ if ((stream.tier.id === tierId) && !pended) {
+ pended = true
+ await pending.promise
+ }
+ })
+
+ return pending
+ }
+
+ it('starts both tiers\' demands for a Start of a tier other than the sound tier, answers it once its own tier has started while the sound tier\'s '
+ + 'start is pending, and sends its session the sound tier\'s sound and none of its own tier\'s', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service, table } = harness({ tiers: SHARED_TIERS })
+ const pending = pendingFirstStart(delegate, 1)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const sessionIdentifier = crypto.randomUUID()
+ const answer = await prepare(service, connection, from, sessionIdentifier) as Prepared
+ let status: RTPStreamingStatus | undefined
+
+ void start(service, connection, sessionIdentifier, 2).then((answered) => {
+ status = answered
+ })
+ await until(() => status !== undefined)
+
+ expect(status).toBe(RTPStreamingStatus.SUCCESS)
+ expect(streamsOf(delegate).map(stream => stream.tier.id)).toEqual([2, 1])
+ expect(table.videoTiers.get(1)!.demand!.waiting).toBe(true)
+
+ // Each tier's stream carries a sound of its own, which only the sound tier's reaches the session.
+ for (const tierId of [1, 2]) {
+ writeTierFrame(streamOf(delegate, tierId), 'audio', {
+ data: Buffer.alloc(60, tierId),
+ time: 0,
+ })
+ }
+
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.audio.length === 1)
+ await settle()
+
+ expect(unprotected(answer, from, 'audio').map(packet => packet.subarray(12))).toEqual([
+ Buffer.alloc(60, 1),
+ ])
+
+ pending.resolve()
+
+ expect(await end(service, connection, sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ })
+
+ it('joins a Start of the sound tier once for both media, as a Start of a tier joins it on a sensor whose tiers each carry their own sound', async () => {
+ const joins = vi.spyOn(TierTable.prototype, 'join')
+ const { service } = harness({ tiers: SHARED_TIERS })
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from, 1)
+
+ expect(joins.mock.calls.map(call => ({
+ media: call[3],
+ tierId: call[0].tierId,
+ }))).toEqual([
+ {
+ media: ['video', 'audio'],
+ tierId: 1,
+ },
+ ])
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ })
+
+ it.each([
+ { cause: 'a refusal' },
+ { cause: 'a cut at its bound' },
+ ])('streams a view of another tier on with its own pictures and no sound after $cause of the sound tier\'s start, and sends it none when another '
+ + 'holder raises the sound tier again', async ({ cause }) => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, service, table } = harness({ tiers: SHARED_TIERS })
+ const pending = pendingFirstStart(delegate, 1)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from, 2)
+ const soundTier = table.videoTiers.get(1)!
+
+ expect(streamsOf(delegate).map(stream => stream.tier.id)).toEqual([2, 1])
+
+ // The view's own tier hands over pictures that are no keyframe through the sound tier's bound, which keeps its demand inside its silence bounds and
+ // sends the view nothing before its keyframe below.
+ if (cause === 'a refusal') {
+ pending.reject(new Error('The sound encoder is busy.'))
+ await settle()
+ } else {
+ await keepStreaming([
+ streamOf(delegate, 2),
+ ], DELEGATE_CALL_TIMEOUT, { advance: advanceAsync })
+ }
+
+ // The sound tier's start is told of as that tier's own problem, a rejection's or the bound's, and its demand has ended.
+ const reported = [
+ ...error.mock.calls,
+ ...warn.mock.calls,
+ ].map(([line]) => String(line))
+
+ expect(reported).toEqual([
+ expect.stringMatching((cause === 'a refusal')
+ ? /^MultiTierStreamingDelegate failed to start a tier demand: /
+ : /did not settle tierDemandStarted for the video tier 1 /),
+ ])
+ expect(soundTier.demand).toBeUndefined()
+
+ // Another holder raises the sound tier again, whose stream writes a sound, and the view's own tier writes a keyframe, timed past every picture it
+ // handed over through the bound.
+ const raised = table.hold(soundTier, scriptedHolder())
+
+ writeTierFrame(streamOf(delegate, 1), 'audio', {
+ data: Buffer.alloc(60, 1),
+ time: 0,
+ })
+ writeTierFrame(streamOf(delegate, 2), 'video', keyframeWithSets(sliceFrame(300, DELEGATE_CALL_TIMEOUT * 1000)))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => unprotected(answer, from, 'video').length === 1)
+ await settle()
+
+ expect(unprotected(answer, from, 'audio')).toEqual([])
+ expect(endsOf(delegate, 2)).toBe(0)
+
+ raised.release()
+
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ })
+
+ it('streams a view of another tier on silent once the sound tier\'s stream fails mid-view, and ends the sound tier\'s demand once, at the release its '
+ + 'other holder makes', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, service, table } = harness({ tiers: SHARED_TIERS })
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from, 2)
+ const other = table.hold(table.videoTiers.get(1)!, scriptedHolder())
+
+ writeTierFrame(streamOf(delegate, 1), 'audio', {
+ data: Buffer.alloc(60, 1),
+ time: 0,
+ })
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.audio.length === 1)
+
+ streamOf(delegate, 1).fail('The sound encoder crashed.')
+ await settle()
+
+ expect(endsOf(delegate, 1)).toBe(0)
+
+ // The view's own tier streams on, its keyframe sent.
+ writeTierFrame(streamOf(delegate, 2), 'video', keyframeWithSets(sliceFrame(300)))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => unprotected(answer, from, 'video').length === 1)
+
+ other.release()
+ await settle()
+
+ expect(endsOf(delegate, 1)).toBe(1)
+ expect(unprotected(answer, from, 'audio')).toHaveLength(1)
+ expect(warn).toHaveBeenCalledOnce()
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expect([1, 2].map(tierId => endsOf(delegate, tierId))).toEqual([1, 1])
+ })
+
+ it('releases a view\'s sound at its Start where the sound\'s tier holds a demand that failed already and another holder still keeps: the tier ends '
+ + 'as that holder releases and a later holder raises a demand of its own', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, service, table } = harness({ tiers: SHARED_TIERS })
+ const soundTier = table.videoTiers.get(1)!
+ // Another holder keeps the sound's tier past its failure, and the failed demand stands until that holder releases.
+ const other = table.hold(soundTier, scriptedHolder())
+
+ await settle()
+ streamOf(delegate, 1).fail('The sound encoder crashed.')
+ await settle()
+
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from, 2)
+
+ other.release()
+ await settle()
+
+ expect(endsOf(delegate, 1)).toBe(1)
+
+ // A later holder of the sound's tier, as the recorded tier's keeper asking again, raises a demand of its own.
+ const later = table.hold(soundTier, scriptedHolder())
+
+ await settle()
+
+ expect(streamsOf(delegate, 1)).toHaveLength(2)
+
+ later.release()
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ })
+
+ it('releases both holds of a view of another tier at its End, each tier\'s demand ending once', async () => {
+ const { delegate, service } = harness({ tiers: SHARED_TIERS })
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from, 2)
+
+ expect([1, 2].map(tierId => endsOf(delegate, tierId))).toEqual([0, 0])
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ await settle()
+
+ expect([1, 2].map(tierId => endsOf(delegate, tierId))).toEqual([1, 1])
+ })
+
+ it('releases both joins of a session that ends while its Start of another tier waits on that tier\'s pending start', async () => {
+ const { delegate, service } = harness({ tiers: SHARED_TIERS })
+ const pending = pendingFirstStart(delegate, 2)
+ const from = await endpoint()
+ const closing = buildEmitterConnection()
+ const sessionIdentifier = crypto.randomUUID()
+ await prepare(service, closing, from, sessionIdentifier)
+
+ const starting = start(service, closing, sessionIdentifier, 2)
+ await settle()
+
+ expect(streamsOf(delegate).map(stream => stream.tier.id)).toEqual([2, 1])
+
+ closing.emit('closed')
+
+ expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ await settle()
+
+ // The sound tier, started at once, ends with its one join released, and the view's own tier ends as its pending start settles.
+ expect([1, 2].map(tierId => endsOf(delegate, tierId))).toEqual([1, 0])
+
+ pending.resolve()
+ await settle()
+
+ expect([1, 2].map(tierId => endsOf(delegate, tierId))).toEqual([1, 1])
+ })
+
+ it('answers a keyframe request of a view of another tier from that tier\'s buffer, writing one keyframe-request debug event of outcome answered for '
+ + 'that tier', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP')
+ const { delegate, service } = harness({ tiers: SHARED_TIERS })
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from, 2)
+ const events = captureDebugEvents('HAP-NodeJS:Camera:MultiTier')
+
+ // The view holds its own tier for its picture and the sound tier for its sound.
+ expect(streamsOf(delegate).map(stream => stream.tier.id)).toEqual([2, 1])
+
+ writeTierFrame(streamOf(delegate, 2), 'video', keyframeWithSets(sliceFrame(300)))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => unprotected(answer, from, 'video').length === 1)
+
+ // The request opens the view again from the keyframe, which a live picture written after the turn a millisecond on hands it.
+ sendDatagram(from, answer, 'video', new ReferenceSRTP(CONTROLLER_KEYS.video).protectRTCP(Buffer.from(PICTURE_LOSS, 'hex')))
+ await until(() => unprotect.mock.calls.length === 1)
+ await vi.advanceTimersByTimeAsync(1)
+ writeTierFrame(streamOf(delegate, 2), 'video', sliceFrame(300, 33333))
+ await vi.advanceTimersByTimeAsync(200)
+ await until(() => unprotected(answer, from, 'video').length >= 2)
+
+ const [live, opened] = unprotected(answer, from, 'video')
+
+ expect(events.filter(({ kind }) => kind === 'keyframe-request').map(({ outcome, tierId }) => ({ outcome, tierId }))).toEqual([
+ { outcome: 'answered', tierId: 2 },
+ ])
+ expect(opened.subarray(12)).toEqual(live.subarray(12))
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ })
+
+ it('sends a view of another tier no sound of the sound tier while the camera\'s Microphone is muted, no consumer taking that tier\'s picture, and its '
+ + 'sound again once unmuted', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service, table } = harness({ tiers: SHARED_TIERS })
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from, 2)
+
+ expect(table.videoTiers.get(1)!.demand!.halves.video.joined).toBe(0)
+
+ table.muteMicrophone(true)
+ writeTierFrame(streamOf(delegate, 1), 'audio', {
+ data: Buffer.alloc(60, 1),
+ time: 0,
+ })
+ await vi.advanceTimersByTimeAsync(500)
+ await settle()
+
+ expect(from.received.audio).toEqual([])
+
+ table.muteMicrophone(false)
+ writeTierFrame(streamOf(delegate, 1), 'audio', {
+ data: Buffer.alloc(60, 2),
+ time: 20000,
+ })
+ await vi.advanceTimersByTimeAsync(500)
+ await until(() => from.received.audio.length === 1)
+
+ expect(unprotected(answer, from, 'audio').map(packet => packet.subarray(12))).toEqual([
+ Buffer.alloc(60, 2),
+ ])
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ })
+ })
+
+ describe('holds on the tier table', () => {
+ it('answers cut to both holders waiting on one pending demand when its bound withdraws it, though the delegate\'s start resolves after', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, table } = harness()
+ const pending = deferred()
+ pendingStart(delegate, pending)
+ const tier = table.videoTiers.get(1)!
+ const first = table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer())
+ const second = table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer())
+ const answers = Promise.all([
+ first.answer(),
+ second.answer(),
+ ])
+
+ expect([first.waiting, second.waiting]).toEqual([true, true])
+
+ await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT)
+ pending.resolve()
+
+ expect(await answers).toEqual(['cut', 'cut'])
+ expect(warn).toHaveBeenCalledOnce()
+ expect(signalOf(delegate, streamOf(delegate)).aborted).toBe(true)
+
+ // The withdrawal released what the start registered, and its later settling releases nothing more.
+ await settle()
+
+ expect(disposedOf(delegate, streamOf(delegate))).toBe(1)
+
+ first.release()
+ second.release()
+ await settle()
+
+ expect(delegate.tierDemandStarted).toHaveBeenCalledOnce()
+ expect(disposedOf(delegate, streamOf(delegate))).toBe(1)
+ })
+
+ it('answers refused to a join into a failed demand, and calls the route of a consumer waiting on the demand once when its stream fails', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, table } = harness()
+ const pending = deferred()
+ pendingStart(delegate, pending)
+ const tier = table.videoTiers.get(1)!
+ const waitingHolder = scriptedHolder()
+ const waiting = table.joinFrames(tier, 'video', waitingHolder, scriptedFrameConsumer())
+ const answer = waiting.answer()
+
+ streamOf(delegate).fail('The encoder crashed.')
+ streamOf(delegate).fail('The encoder crashed again.')
+
+ expect(waitingHolder.tierFailed).toHaveBeenCalledOnce()
+ expect(await answer).toBe('refused')
+
+ // The failed demand stands until its last join releases, and a join into it in the meantime is answered as refused, even once its start resolves.
+ const late = table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer())
+ pending.resolve()
+
+ expect(await late.answer()).toBe('refused')
+ expect(late.started).toBe(false)
+ expect(warn).toHaveBeenCalledOnce()
+
+ waiting.release()
+ late.release()
+ await settle()
+
+ expect(delegate.tierDemandStarted).toHaveBeenCalledOnce()
+ expect(endedCalls(delegate)).toBe(1)
+ })
+
+ it('hands a frame consumer joining a tier whose start is pending every frame written during the wait, and answers it started once the start resolves',
+ async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, table } = harness()
+ const pending = deferred()
+ pendingStart(delegate, pending)
+ const consumer = scriptedFrameConsumer()
+ const hold = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer)
+ const answer = hold.answer()
+ const stream = streamOf(delegate)
+
+ writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0)))
+ writeTierFrame(stream, 'video', sliceFrame(300, 33333))
+ await vi.advanceTimersByTimeAsync(34)
+
+ expect(hold.waiting).toBe(true)
+ expect(consumer.taken.map(({ frame }) => frame.time)).toEqual([0, 33333])
+ expect(stream.statistics().consumers).toBe(1)
+
+ pending.resolve()
+
+ expect(await answer).toBe('started')
+
+ hold.release()
+ await settle()
+ })
+
+ it('answers refused to a frame consumer joining a tier whose start rejects, sends no demand end and hands it no frame written after', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, table } = harness()
+ delegate.tierDemandStarted.mockImplementationOnce(async () => {
+ throw new Error('The video encoder is busy.')
+ })
+ const consumer = scriptedFrameConsumer()
+ const hold = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer)
+
+ expect(await hold.answer()).toBe('refused')
+
+ writeTierFrame(streamOf(delegate), 'video', sliceFrame(300))
+ await vi.advanceTimersByTimeAsync(0)
+ hold.release()
+ await settle()
+
+ expect(consumer.taken).toEqual([])
+ expect(endedCalls(delegate)).toBe(0)
+ })
+
+ it('answers refused to a frame consumer joining a demand whose stream has failed, and ends the demand once at its last release', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, table } = harness()
+ const tier = table.videoTiers.get(1)!
+ const first = table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer())
+
+ expect(await first.answer()).toBe('started')
+
+ streamOf(delegate).fail('The encoder crashed.')
+ const late = table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer())
+
+ expect(await late.answer()).toBe('refused')
+ expect(late.started).toBe(false)
+
+ first.release()
+ await settle()
+
+ expect(endedCalls(delegate)).toBe(0)
+
+ late.release()
+ await settle()
+
+ expect(delegate.tierDemandStarted).toHaveBeenCalledOnce()
+ expect(endedCalls(delegate)).toBe(1)
+ expect(warn).toHaveBeenCalledOnce()
+ })
+
+ it('calls the route of each of two frame consumers joining one pending demand once when its stream fails, and answers each refused', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, table } = harness()
+ const pending = deferred()
+ pendingStart(delegate, pending)
+ const tier = table.videoTiers.get(1)!
+ const holders = [
+ scriptedHolder(),
+ scriptedHolder(),
+ ]
+ const holds = holders.map(holder => table.joinFrames(tier, 'video', holder, scriptedFrameConsumer()))
+ const answers = Promise.all(holds.map(async hold => hold.answer()))
+
+ streamOf(delegate).fail('The encoder crashed.')
+
+ expect(holders.map(({ tierFailed }) => tierFailed.mock.calls.length)).toEqual([1, 1])
+ expect(await answers).toEqual(['refused', 'refused'])
+
+ pending.resolve()
+
+ for (const hold of holds) {
+ hold.release()
+ }
+
+ await settle()
+
+ expect(endedCalls(delegate)).toBe(1)
+ })
+
+ it('answers cut to both of two frame consumers joining one pending demand when its bound withdraws it, though the start resolves after',
+ async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, table } = harness()
+ const pending = deferred()
+ pendingStart(delegate, pending)
+ const tier = table.videoTiers.get(1)!
+ const holds = [
+ table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer()),
+ table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer()),
+ ]
+ const answers = Promise.all(holds.map(async hold => hold.answer()))
+
+ await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT)
+ pending.resolve()
+
+ expect(await answers).toEqual(['cut', 'cut'])
+ expect(warn).toHaveBeenCalledOnce()
+
+ for (const hold of holds) {
+ hold.release()
+ }
+
+ await settle()
+
+ // The withdrawal aborted the start's signal once and released what the start registered, and its later settling released nothing more.
+ expect(delegate.tierDemandStarted).toHaveBeenCalledOnce()
+ expect(signalOf(delegate, streamOf(delegate)).aborted).toBe(true)
+ expect(disposedOf(delegate, streamOf(delegate))).toBe(1)
+ })
+ })
+
+ describe('fan-out', () => {
+ it('sends each session the packets ffmpeg cuts written frames into as SRTP under its own key, SSRC and the tier\'s payload type, numbered on', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const firstEndpoint = await endpoint()
+ const secondEndpoint = await endpoint()
+ const first = await streaming(service, buildEmitterConnection(), firstEndpoint)
+ const second = await streaming(service, buildEmitterConnection(), secondEndpoint)
+ const stream = streamOf(delegate)
+ const cuts = [
+ ...HEVC.frames[0].cuts[CUT],
+ ...HEVC.frames[1].cuts[CUT],
+ ]
+
+ writeTierFrame(stream, 'video', {
+ ...vectorFrame(HEVC, 0, 0),
+ keyframe: true,
+ })
+ writeTierFrame(stream, 'video', vectorFrame(HEVC, 1, 66667))
+ await vi.advanceTimersByTimeAsync(67)
+ await until(() => firstEndpoint.received.video.length === cuts.length && secondEndpoint.received.video.length === cuts.length)
+
+ for (const [answer, from] of [
+ [first, firstEndpoint],
+ [second, secondEndpoint],
+ ] as const) {
+ const packets = unprotected(answer, from, 'video')
+
+ expect(packets.map(packet => packet.subarray(12).toString('hex'))).toEqual(cuts)
+ expect(packets.map(packet => packet[1])).toEqual(cuts.map(() => 0x80 | 99))
+ expect(packets.map(packet => packet.readUInt32BE(8))).toEqual(cuts.map(() => answer.videoSSRC))
+ expect(packets.map(packet => (packet.readUInt16BE(2) - packets[0].readUInt16BE(2)) & 0xFFFF)).toEqual(cuts.map((_cut, index) => index))
+ }
+
+ expect(stream.statistics()).toEqual({
+ packets: 2 * cuts.length,
+ bytes: 2 * cuts.reduce((total, cut) => total + 12 + cut.length / 2, 0),
+ drops: 0,
+ consumers: 4,
+ })
+ expect(firstEndpoint.received.audio).toEqual([])
+ })
+
+ it('drops and counts a malformed sample of the stream, a picture whose unit runs past its end and a sound of no octets, throwing nothing, and sends '
+ + 'every session the next', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const firstEndpoint = await endpoint()
+ const secondEndpoint = await endpoint()
+ const base = udpSockets()
+ const firstConnection = buildEmitterConnection()
+ const secondConnection = buildEmitterConnection()
+ const first = await streaming(service, firstConnection, firstEndpoint)
+ const second = await streaming(service, secondConnection, secondEndpoint)
+ const stream = streamOf(delegate)
+
+ // A picture whose unit's length runs past its end and a sound of no octets, each in a fragment of its own.
+ expect(() => {
+ stream.write(tierStreamInitialization())
+ stream.write(tierStreamFragment({
+ picture: [
+ pictureSample(Buffer.from('0000000a0201', 'hex')),
+ ],
+ }))
+ stream.write(tierStreamFragment({
+ sound: [
+ soundSample(Buffer.alloc(0)),
+ ],
+ }))
+ }).not.toThrow()
+
+ expect(stream.statistics()).toEqual({
+ packets: 0,
+ bytes: 0,
+ drops: 2,
+ consumers: 4,
+ })
+
+ // The next picture is the stream's keyframe, which every session is sent first.
+ stream.write(tierStreamFragment({
+ picture: [
+ pictureSample(vectorFrame(HEVC, 0).data, true),
+ ],
+ pictureTime: 3000n,
+ }))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => firstEndpoint.received.video.length === 1 && secondEndpoint.received.video.length === 1)
+
+ for (const [answer, from] of [
+ [first, firstEndpoint],
+ [second, secondEndpoint],
+ ] as const) {
+ expect(unprotected(answer, from, 'video').map(packet => packet.subarray(12).toString('hex'))).toEqual(HEVC.frames[0].cuts[CUT])
+ }
+
+ expect(stream.statistics()).toEqual({
+ packets: 2,
+ bytes: 2 * (12 + HEVC.frames[0].cuts[CUT][0].length / 2),
+ drops: 2,
+ consumers: 4,
+ })
+ expect(await end(service, firstConnection, first.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expect(await end(service, secondConnection, second.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ await until(() => udpSockets() === base)
+ })
+
+ it('grows a sender\'s pool for a frame of 300 packets and three of 700 written in one turn, which leave in three, sending each whole with every datagram '
+ + 'intact at its completion', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const held = holdSends(accessorySockets(createSocket).video)
+ const stream = streamOf(delegate)
+ const frames = [300, 400, 200, 100]
+ const sent: Buffer[] = []
+
+ writeTierFrame(stream, 'video', burstKeyframe(frames[0], 0))
+ await vi.advanceTimersByTimeAsync(0)
+ sent.push(...held.map(send => send.sent))
+
+ expect(complete(held)).toBe(frames[0])
+
+ for (const [index, packets] of frames.slice(1).entries()) {
+ writeTierFrame(stream, 'video', burstFrame(packets, (index + 1) * 66667))
+ }
+
+ // Written in one turn, each frame leaves at its time's distance from the first, with no send completing between them.
+ await vi.advanceTimersByTimeAsync(200)
+ sent.push(...held.map(send => send.sent))
+
+ expect(complete(held)).toBe(1000 - frames[0])
+
+ // Every packet goes out under the session's key and the tier's payload type, numbered on, the marker on each frame's last packet, and each frame's
+ // fragments carry its slice, the keyframe's after the aggregation packet of its parameter sets.
+ const reference = new ReferenceSRTP(answer.videoSRTPParameters)
+ const packets = sent.map(datagram => reference.unprotect(datagram)!)
+ const ends = frames.map((_count, index) => frames.slice(0, index + 1).reduce((total, count) => total + count, 0) - 1)
+ const fragments = frames.map((count, index) => (index === 0)
+ ? count - 1
+ : count)
+
+ expect(packets.map(packet => packet[1] & 0x7F)).toEqual(packets.map(() => TIERS.videoStreamTiers.payloadType))
+ expect(packets.every((packet, index) => ((packet.readUInt16BE(2) - packets[0].readUInt16BE(2)) & 0xFFFF) === index)).toBe(true)
+ expect(packets.flatMap((packet, index) => (packet[1] & 0x80) === 0
+ ? []
+ : [index])).toEqual(ends)
+ expect((packets[0][12] >> 1) & 0x3F).toBe(48)
+ expect(fragments.map((count, index) => Buffer.concat(packets.slice(ends[index] + 1 - count, ends[index] + 1).map(packet => packet.subarray(15)))
+ .equals(burstFrame(count).data.subarray(4 + SLICE.length)))).toEqual(frames.map(() => true))
+ expect(stream.statistics()).toMatchObject({ packets: 1000, drops: 0 })
+ })
+
+ it('keeps every datagram in flight intact and completing in order when its pool grows with its ring\'s oldest buffer the hundred-and-first', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ await streaming(service, buildEmitterConnection(), from)
+ const held = holdSends(accessorySockets(createSocket).video)
+ const stream = streamOf(delegate)
+
+ writeTierFrame(stream, 'video', burstKeyframe(100, 0))
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(complete(held)).toBe(100)
+
+ // The burst grows the pool past the ring's end, and the frame after part of it completes takes the buffers those completions free.
+ writeTierFrame(stream, 'video', burstFrame(450, 66667))
+ await vi.advanceTimersByTimeAsync(67)
+
+ expect(held).toHaveLength(450)
+ expect(complete(held, 200)).toBe(200)
+
+ writeTierFrame(stream, 'video', burstFrame(100, 133333))
+ await vi.advanceTimersByTimeAsync(67)
+
+ expect(held).toHaveLength(350)
+ expect(complete(held)).toBe(350)
+ expect(stream.statistics()).toMatchObject({ packets: 650, drops: 0 })
+ })
+
+ it('grows a video sender\'s pool for a burst of 300 packets in one allocation of as many buffers again as it holds, 256 buffers\' octets', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ await streaming(service, buildEmitterConnection(), from)
+ const held = holdSends(accessorySockets(createSocket).video)
+ const stream = streamOf(delegate)
+ // The stream's initialization segment and the burst's fragment are built before the spy, which reads the release's allocations alone.
+ const burst = tierStreamFragment({
+ picture: [
+ pictureSample(burstKeyframe(300).data, true),
+ ],
+ })
+
+ stream.write(tierStreamInitialization())
+
+ const alloc = vi.spyOn(Buffer, 'alloc')
+
+ stream.write(burst)
+ await vi.advanceTimersByTimeAsync(0)
+
+ // Each pooled buffer holds the largest packet the demand cuts and its SRTP tag.
+ expect(alloc.mock.calls).toEqual([
+ [256 * (CUT + 10)],
+ ])
+ expect(complete(held)).toBe(300)
+ })
+
+ it('counts each send whose completion reports an error, logging the first at debug and the rest as a count at the end, and streams on', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ const held = holdSends(accessorySockets(createSocket).video)
+ const stream = streamOf(delegate)
+ const lines = captureDebug('HAP-NodeJS:Camera:MultiTier')
+
+ writeTierFrame(stream, 'video', burstKeyframe(3))
+ await vi.advanceTimersByTimeAsync(0)
+
+ for (const send of held.splice(0)) {
+ send.fail(Object.assign(new Error('send EHOSTUNREACH 127.0.0.1'), { code: 'EHOSTUNREACH' }))
+ }
+
+ writeTierFrame(stream, 'video', sliceFrame(300, 33333))
+ await vi.advanceTimersByTimeAsync(34)
+
+ expect(held).toHaveLength(1)
+ expect(complete(held)).toBe(1)
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expect(lines.filter(line => line.includes('failed to send a packet: send EHOSTUNREACH'))).toHaveLength(1)
+ expect(lines.filter(line => line.includes('failed to send 2 more packets.'))).toHaveLength(1)
+ expect(stream.statistics()).toMatchObject({ packets: 4, drops: 0 })
+ })
+
+ it('refuses and counts each packet a burst sends past its pool\'s ceiling, and sends a later frame whole', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ await streaming(service, buildEmitterConnection(), from)
+ const held = holdSends(accessorySockets(createSocket).video)
+ const stream = streamOf(delegate)
+
+ writeTierFrame(stream, 'video', burstKeyframe(2100, 0))
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(held).toHaveLength(2048)
+ expect(stream.statistics()).toMatchObject({ packets: 2048, drops: 2100 - 2048 })
+ expect(complete(held)).toBe(2048)
+
+ writeTierFrame(stream, 'video', burstFrame(10, 66667))
+ await vi.advanceTimersByTimeAsync(67)
+
+ expect(held).toHaveLength(10)
+ expect(complete(held)).toBe(10)
+ expect(stream.statistics()).toMatchObject({ packets: 2058, drops: 2100 - 2048 })
+ })
+
+ it('numbers each packet a session\'s sender refuses at its pool\'s ceiling, and that session reads a gap of exactly the refused packets, while a session '
+ + 'beside it with room reads its numbering unbroken', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ const first = await endpoint()
+ const second = await endpoint()
+ const firstAnswer = await streaming(service, buildEmitterConnection(), first)
+ const firstHeld = holdSends(accessorySockets(createSocket).video)
+ const secondAnswer = await streaming(service, buildEmitterConnection(), second)
+ const secondHeld = holdSends(accessorySockets(createSocket).video)
+ const stream = streamOf(delegate)
+ const firstSent: Buffer[] = []
+ const secondSent: Buffer[] = []
+
+ // A keyframe of 2000 packets fills most of each session's pool, and the second session's sends complete while the first session's stay in flight.
+ writeTierFrame(stream, 'video', burstKeyframe(2000, 0))
+ await vi.advanceTimersByTimeAsync(0)
+ secondSent.push(...flush(secondHeld))
+
+ // A burst of 100 meets the first session's pool at its ceiling after 48 packets, which means its sender refuses the 52 after them, while the second session
+ // has room for all of them. A burst of 3 once every send has completed reaches each session whole.
+ writeTierFrame(stream, 'video', burstFrame(100, 66667))
+ await vi.advanceTimersByTimeAsync(67)
+ firstSent.push(...flush(firstHeld))
+ secondSent.push(...flush(secondHeld))
+ writeTierFrame(stream, 'video', burstFrame(3, 133333))
+ await vi.advanceTimersByTimeAsync(67)
+ firstSent.push(...flush(firstHeld))
+ secondSent.push(...flush(secondHeld))
+
+ // Each packet a session sent, in order, unprotected under its keys.
+ const read = (answer: Prepared, sent: Buffer[]): Buffer[] => {
+ const reference = new ReferenceSRTP(answer.videoSRTPParameters)
+
+ return sent.map(datagram => reference.unprotect(datagram)!)
+ }
+ const firstPackets = read(firstAnswer, firstSent)
+ const secondPackets = read(secondAnswer, secondSent)
+
+ expect(stream.statistics()).toMatchObject({ drops: 52 })
+ expect(firstPackets.map(packet => (packet.readUInt16BE(2) - firstPackets[0].readUInt16BE(2)) & 0xFFFF)).toEqual([
+ ...Array.from({ length: 2048 }, (_packet, index) => index),
+ 2100,
+ 2101,
+ 2102,
+ ])
+ expect([
+ secondPackets.length,
+ unbroken(secondPackets),
+ ]).toEqual([2103, true])
+ })
+ })
+
+ describe('a view opening from the buffer', () => {
+ const MEDIA: readonly StreamTierMedium[] = ['video', 'audio']
+
+ it('hands a session joining a running tier its opening across turns, more packets than its video pool\'s ceiling with none refused, its sound joining '
+ + 'the live releases, while the session streaming beside it reads its numbering unbroken', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ const first = await endpoint()
+ const second = await endpoint()
+ const firstAnswer = await streaming(service, buildEmitterConnection(), first)
+ const firstHeld = heldSockets(accessorySockets(createSocket))
+ const firstSent: Record = { video: [], audio: [] }
+ const stream = streamOf(delegate)
+
+ // A keyframe of 1300 packets and pictures of 500 behind it, past the 2048 a video pool holds, and 140 sounds of 20 ms, past the 128 a sound pool
+ // holds, each released to the first session, whose sends complete as each step ends.
+ writeTierFrame(stream, 'video', {
+ ...burstFrame(1300, 0),
+ keyframe: true,
+ })
+ writeTierFrame(stream, 'video', burstFrame(500, 66667))
+ writeTierFrame(stream, 'video', burstFrame(500, 133333))
+
+ for (let index = 0; index < 140; index++) {
+ writeTierFrame(stream, 'audio', {
+ data: Buffer.alloc(60, 0x78),
+ time: index * 20000,
+ })
+ }
+
+ for (let step = 0; step < 60; step++) {
+ await vi.advanceTimersByTimeAsync(50)
+
+ for (const medium of MEDIA) {
+ firstSent[medium].push(...flush(firstHeld[medium]))
+ }
+ }
+
+ expect([firstSent.video.length, firstSent.audio.length]).toEqual([2300, 140])
+
+ const secondAnswer = await streaming(service, buildEmitterConnection(), second)
+ const secondHeld = heldSockets(accessorySockets(createSocket))
+ const secondSent: Record = { video: [], audio: [] }
+
+ // The opening takes its start in its first turn, a millisecond after the join, past every picture placed, which means it hands nothing before a live picture
+ // moves the edge. The sound joins the live releases, sent none of the sound the buffer kept.
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect([secondHeld.video.length, secondHeld.audio.length]).toEqual([0, 0])
+
+ // A live picture moves the edge past the whole stretch, and its release reaches each session: the opening's turn hands the keyframe and the next
+ // picture, and the turns after it hand nothing while no send completes.
+ writeTierFrame(stream, 'video', sliceFrame(300, 3000000))
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect([secondHeld.video.length, secondHeld.audio.length]).toEqual([1800, 0])
+
+ await vi.advanceTimersByTimeAsync(5)
+
+ expect(secondHeld.video).toHaveLength(1800)
+
+ for (const medium of MEDIA) {
+ secondSent[medium].push(...flush(secondHeld[medium]))
+ }
+
+ await vi.advanceTimersByTimeAsync(20)
+
+ for (const medium of MEDIA) {
+ firstSent[medium].push(...flush(firstHeld[medium]))
+ secondSent[medium].push(...flush(secondHeld[medium]))
+ }
+
+ const read = (answer: Prepared, medium: StreamTierMedium, sent: Buffer[]): Buffer[] => {
+ const reference = new ReferenceSRTP(medium === 'video'
+ ? answer.videoSRTPParameters
+ : answer.audioSRTPParameters)
+
+ return sent.map(datagram => reference.unprotect(datagram)!)
+ }
+
+ expect(stream.statistics()).toMatchObject({ drops: 0 })
+
+ for (const [answer, sent, sounds] of [
+ [firstAnswer, firstSent, 140],
+ [secondAnswer, secondSent, 0],
+ ] as const) {
+ const video = read(answer, 'video', sent.video)
+ const audio = read(answer, 'audio', sent.audio)
+
+ expect([video.length, audio.length]).toEqual([2301, sounds])
+ expect([
+ unbroken(video),
+ unbroken(audio),
+ ]).toEqual([true, true])
+ }
+ })
+
+ it('numbers each session\'s packets from a start of its own, and a session streaming beside one that opens reads its numbering unbroken', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const first = await endpoint()
+ const second = await endpoint()
+ const firstAnswer = await streaming(service, buildEmitterConnection(), first)
+ const stream = streamOf(delegate)
+
+ writeTierFrame(stream, 'video', {
+ ...burstFrame(3, 0),
+ keyframe: true,
+ })
+ writeTierFrame(stream, 'video', burstFrame(2, 33333))
+ await vi.advanceTimersByTimeAsync(50)
+
+ // The second session opens on the keyframe and the picture after it while a live picture reaches each session.
+ const secondAnswer = await streaming(service, buildEmitterConnection(), second)
+
+ writeTierFrame(stream, 'video', burstFrame(2, 66667))
+ await vi.advanceTimersByTimeAsync(50)
+ writeTierFrame(stream, 'video', burstFrame(2, 100000))
+ await vi.advanceTimersByTimeAsync(50)
+ await until(() => (first.received.video.length === 9) && (second.received.video.length === 9))
+
+ for (const [answer, from] of [
+ [firstAnswer, first],
+ [secondAnswer, second],
+ ] as const) {
+ expect(unbroken(unprotected(answer, from, 'video'))).toBe(true)
+ }
+ })
+
+ it('numbers a session\'s packets on across frames from the start its sender holds, wrapping from 65535 to 0', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, management, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+ // @ts-expect-error: private access
+ const { media } = management.sessions.get(answer.sessionIdentifier)
+
+ // The sender's start stands three short of the range's end, and its fourth packet wraps.
+ media.video.sender.sequence = SEQUENCE_RANGE - 3
+
+ writeTierFrame(stream, 'video', burstKeyframe(4, 0))
+ writeTierFrame(stream, 'video', burstFrame(1, 33333))
+ await vi.advanceTimersByTimeAsync(50)
+ await until(() => from.received.video.length === 5)
+
+ expect(unprotected(answer, from, 'video').map(packet => packet.readUInt16BE(2))).toEqual([
+ SEQUENCE_RANGE - 3,
+ SEQUENCE_RANGE - 2,
+ SEQUENCE_RANGE - 1,
+ 0,
+ 1,
+ ])
+ })
+
+ it('sends a session behind the live releases its first sender report at its first report moment after its first packet, its opening still behind',
+ async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ const first = await endpoint()
+ const second = await endpoint()
+
+ await streaming(service, buildEmitterConnection(), first)
+
+ const firstHeld = heldSockets(accessorySockets(createSocket))
+ const stream = streamOf(delegate)
+
+ writeTierFrame(stream, 'video', {
+ ...burstFrame(1300, 0),
+ keyframe: true,
+ })
+ writeTierFrame(stream, 'video', burstFrame(1000, 66667))
+ await vi.advanceTimersByTimeAsync(50)
+ flush(firstHeld.video)
+ await vi.advanceTimersByTimeAsync(50)
+ flush(firstHeld.video)
+
+ // The second session's room takes the keyframe and not the picture after it: it stays behind past its first report's moment, 2.5 seconds after
+ // its Start, and a live picture written after its join moves the edge, whose release hands it the keyframe, its first packets.
+ await streaming(service, buildEmitterConnection(), second)
+
+ const secondSockets = accessorySockets(createSocket)
+ const secondHeld = heldSockets(secondSockets)
+ const reports = (): number => vi.mocked(secondSockets.video.send).mock.calls.filter(([, completion]) => typeof completion !== 'function').length
+
+ writeTierFrame(stream, 'video', sliceFrame(300, 200000))
+ await vi.advanceTimersByTimeAsync(2499)
+
+ expect(secondHeld.video).toHaveLength(1300)
+ expect(reports()).toBe(0)
+
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect(secondHeld.video).toHaveLength(1300)
+ expect(reports()).toBe(1)
+ })
+
+ it('sends a session behind the live releases a frame of its opening larger than its sender\'s pool at once, the packets past the pool\'s ceiling '
+ + 'counted as drops, then the frame after it, with no turn left to run', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, management, service, table } = harness()
+ const from = await endpoint()
+
+ // The library alone holds the tier while a keyframe of 2100 packets, past the 2048 a video pool holds, and a picture of 10 behind it fall due, which is why
+ // nothing is sent before the session joins.
+ table.hold(table.videoTiers.get(1)!, scriptedHolder())
+ await settle()
+
+ const stream = streamOf(delegate)
+
+ writeTierFrame(stream, 'video', {
+ ...burstFrame(2100, 0),
+ keyframe: true,
+ })
+ writeTierFrame(stream, 'video', burstFrame(10, 33333))
+ await vi.advanceTimersByTimeAsync(50)
+
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const held = heldSockets(accessorySockets(createSocket))
+ // @ts-expect-error: private access
+ const { media } = management.sessions.get(answer.sessionIdentifier)
+ const released = vi.spyOn(TierPacer.prototype, 'release')
+
+ expect([media.video.sender.capacity, media.audio.sender.capacity]).toEqual([2048, 128])
+
+ // A live picture written after the join moves the edge past the stretch at 67 ms, and that turn sends the keyframe's packets to the pool's ceiling
+ // and counts the rest as drops, and the picture behind it waits for room, which the turn after the sends complete hands it with the live picture.
+ writeTierFrame(stream, 'video', sliceFrame(300, 66667))
+ await vi.advanceTimersByTimeAsync(17)
+
+ expect(held.video).toHaveLength(2048)
+ expect(stream.statistics().drops).toBe(52)
+
+ flush(held.video)
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect(held.video).toHaveLength(11)
+
+ flush(held.video)
+ released.mockClear()
+ await vi.advanceTimersByTimeAsync(1000)
+
+ expect(released).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ { ending: 'reset' },
+ { ending: 'destroy' },
+ ])('ends a session\'s opening at a $ending, sending it nothing after and throwing nothing from a turn', async ({ ending }) => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, management, service } = harness()
+ const first = await endpoint()
+ const second = await endpoint()
+
+ await streaming(service, buildEmitterConnection(), first)
+
+ const firstHeld = heldSockets(accessorySockets(createSocket))
+ const stream = streamOf(delegate)
+
+ writeTierFrame(stream, 'video', {
+ ...burstFrame(1300, 0),
+ keyframe: true,
+ })
+ writeTierFrame(stream, 'video', burstFrame(1000, 66667))
+ await vi.advanceTimersByTimeAsync(50)
+ flush(firstHeld.video)
+ await vi.advanceTimersByTimeAsync(50)
+ flush(firstHeld.video)
+ await streaming(service, buildEmitterConnection(), second)
+
+ const secondHeld = heldSockets(accessorySockets(createSocket))
+
+ // A live picture written after the join moves the edge at 200 ms, which starts the opening before the ending, its room taking the keyframe alone.
+ writeTierFrame(stream, 'video', sliceFrame(300, 200000))
+ await vi.advanceTimersByTimeAsync(105)
+
+ expect(secondHeld.video).toHaveLength(1300)
+
+ if (ending === 'reset') {
+ management.handleFactoryReset()
+ } else {
+ await management.destroy()
+ }
+
+ await until(() => endedCalls(delegate) === 1)
+ flush(secondHeld.video)
+ await vi.advanceTimersByTimeAsync(1000)
+ await settle()
+
+ expect(secondHeld.video).toHaveLength(0)
+ })
+
+ it('opens the picture of the one session whose controller reports a lost picture again from the latest keyframe released, past every timestamp its tier '
+ + 'has placed, while its sound and a session beside it take the live releases alone', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP')
+ const { delegate, service } = harness()
+ const first = await endpoint()
+ const second = await endpoint()
+ const firstAnswer = await streaming(service, buildEmitterConnection(), first)
+ const firstHeld = heldSockets(accessorySockets(createSocket))
+ const secondAnswer = await streaming(service, buildEmitterConnection(), second)
+ const secondHeld = heldSockets(accessorySockets(createSocket))
+ const stream = streamOf(delegate)
+ const sent: Record<'first' | 'second', Record> = {
+ first: { video: [], audio: [] },
+ second: { video: [], audio: [] },
+ }
+ // Completes every send each session's sockets hold, keeping the datagrams sent.
+ const collect = (): void => {
+ for (const medium of MEDIA) {
+ sent.first[medium].push(...flush(firstHeld[medium]))
+ sent.second[medium].push(...flush(secondHeld[medium]))
+ }
+ }
+ // A medium's packets a session was sent, unprotected under its keys, each read by its timestamp or its length.
+ const read = (answer: Prepared, medium: StreamTierMedium, datagrams: Buffer[]): Buffer[] => {
+ const reference = new ReferenceSRTP(medium === 'video'
+ ? answer.videoSRTPParameters
+ : answer.audioSRTPParameters)
+
+ return datagrams.map(datagram => reference.unprotect(datagram)!)
+ }
+ // A sound of 20 ms, which each session takes live.
+ const sound = (time: number): void => writeTierFrame(stream, 'audio', {
+ data: Buffer.alloc(60, 0x78),
+ time,
+ })
+
+ // A keyframe and a picture after it, each one packet of a length of its own, and a sound beside each, which each session takes live.
+ writeTierFrame(stream, 'video', {
+ ...sliceFrame(300, 0),
+ keyframe: true,
+ })
+ sound(0)
+ writeTierFrame(stream, 'video', sliceFrame(301, 33333))
+ sound(20000)
+ await vi.advanceTimersByTimeAsync(50)
+ collect()
+
+ // The first session's controller reports a lost picture, and a picture written after the turn a millisecond on moves the live edge past the stretch.
+ sendDatagram(first, firstAnswer, 'video', new ReferenceSRTP(CONTROLLER_KEYS.video).protectRTCP(Buffer.from(PICTURE_LOSS, 'hex')))
+ await until(() => unprotect.mock.calls.length === 1)
+ writeTierFrame(stream, 'video', sliceFrame(302, 66667))
+ sound(40000)
+ await vi.advanceTimersByTimeAsync(50)
+ collect()
+
+ const stamp = (packet: Buffer): number => packet.readUInt32BE(4)
+ const firstVideo = read(firstAnswer, 'video', sent.first.video)
+ const secondVideo = read(secondAnswer, 'video', sent.second.video)
+ const highest = stamp(secondVideo[1])
+
+ // The first session is sent the keyframe and the picture after it live, and then the stretch again from that keyframe with the picture written after
+ // the request, each one millisecond past the highest picture placed before the request's turn plus its distance from the keyframe over fifty, at 90 kHz.
+ expect(firstVideo.map(packet => packet.length)).toEqual([
+ ...secondVideo.slice(0, 2),
+ ...secondVideo,
+ ].map(packet => packet.length))
+ expect(firstVideo.slice(2).map(stamp)).toEqual([0, 100 / 3, 200 / 3].map(distance => openingStamp(highest, distance) % 0x100000000))
+ expect(read(firstAnswer, 'audio', sent.first.audio).map(stamp)).toEqual(read(secondAnswer, 'audio', sent.second.audio).map(stamp))
+ expect(sent.first.audio).toHaveLength(3)
+ })
+
+ it('stamps the answer to a lost picture at home over a stretch past the heaviest maximum at the speed that holds its burst to fifty times it', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP')
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const held = heldSockets(accessorySockets(createSocket))
+ const stream = streamOf(delegate)
+ const sent: Buffer[] = []
+ // Completes every send the session's sockets hold, keeping the picture's datagrams.
+ const collect = (): void => {
+ sent.push(...flush(held.video))
+ flush(held.audio)
+ }
+ // A heavy keyframe and a light picture after it, whose octets, read as a second, run past the heaviest maximum.
+ const keyframe = {
+ ...sliceFrame(780946, 0),
+ keyframe: true,
+ }
+ const picture = sliceFrame(296, 33333)
+ const rate = (keyframe.data.length + picture.data.length) * 8 / 1000
+
+ writeTierFrame(stream, 'video', keyframe)
+ writeTierFrame(stream, 'video', picture)
+ await vi.advanceTimersByTimeAsync(50)
+ collect()
+
+ // The controller reports a lost picture, and a picture written after the turn a millisecond on moves the live edge past the stretch.
+ sendDatagram(from, answer, 'video', new ReferenceSRTP(CONTROLLER_KEYS.video).protectRTCP(Buffer.from(PICTURE_LOSS, 'hex')))
+ await until(() => unprotect.mock.calls.length === 1)
+ writeTierFrame(stream, 'video', sliceFrame(302, 66667))
+ await vi.advanceTimersByTimeAsync(50)
+ collect()
+
+ // Each frame's timestamp once, in the order its packets were sent: the keyframe and the picture live, and then the answer's stretch.
+ const reference = new ReferenceSRTP(answer.videoSRTPParameters)
+ const stamps = sent.map(datagram => reference.unprotect(datagram)!.readUInt32BE(4)).filter((stamp, index, all) => stamp !== all[index - 1])
+
+ expect(rate).toBe(6250)
+ expect(stamps.slice(2)).toEqual([0, 100 / 3, 200 / 3].map(distance => openingStamp(stamps[1], distance, 50 * 5000 / rate) % 0x100000000))
+ })
+
+ it('passes by a request while a session\'s own opening waits on its room, the opening running on unrestarted, and answers one once the session is level',
+ async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP')
+ const { delegate, service } = harness()
+ const first = await endpoint()
+ const second = await endpoint()
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.video)
+
+ await streaming(service, buildEmitterConnection(), first)
+
+ const firstHeld = heldSockets(accessorySockets(createSocket))
+ const stream = streamOf(delegate)
+
+ writeTierFrame(stream, 'video', {
+ ...burstFrame(1300, 0),
+ keyframe: true,
+ })
+ writeTierFrame(stream, 'video', burstFrame(1000, 66667))
+ await vi.advanceTimersByTimeAsync(50)
+ flush(firstHeld.video)
+ await vi.advanceTimersByTimeAsync(50)
+ flush(firstHeld.video)
+
+ // The second session's room takes the keyframe and not the picture after it, which a live picture written after its join moves the edge to.
+ const secondAnswer = await streaming(service, buildEmitterConnection(), second)
+ const secondHeld = heldSockets(accessorySockets(createSocket))
+
+ writeTierFrame(stream, 'video', sliceFrame(300, 200000))
+ await vi.advanceTimersByTimeAsync(105)
+
+ expect(secondHeld.video).toHaveLength(1300)
+
+ // A request while the opening waits on its room is passed by: the turn after the sends complete hands the opening on with the picture after the
+ // keyframe and the live picture, and no keyframe again.
+ sendDatagram(second, secondAnswer, 'video', reference.protectRTCP(Buffer.from(PICTURE_LOSS, 'hex')))
+ await until(() => unprotect.mock.calls.length === 1)
+ flush(secondHeld.video)
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect(secondHeld.video).toHaveLength(1001)
+
+ // A request once the session is level is answered: a live picture written after the turn a millisecond on moves the edge, and the session is sent the
+ // keyframe again.
+ flush(secondHeld.video)
+ sendDatagram(second, secondAnswer, 'video', reference.protectRTCP(Buffer.from(PICTURE_LOSS, 'hex')))
+ await until(() => unprotect.mock.calls.length === 2)
+ await vi.advanceTimersByTimeAsync(1)
+ writeTierFrame(stream, 'video', sliceFrame(301, 400000))
+ await vi.advanceTimersByTimeAsync(200)
+
+ expect(secondHeld.video).toHaveLength(1300)
+ })
+
+ it('writes one debug line for each authenticated picture loss indication, naming the session, its video tier and what the request came to', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP')
+ const { delegate, service } = harness()
+ const first = await endpoint()
+ const second = await endpoint()
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.video)
+ // A controller's picture loss indication on a session's video socket, waited on until the session has read it.
+ const request = async (from: Endpoint, answer: Prepared): Promise => {
+ const read = unprotect.mock.calls.length
+
+ sendDatagram(from, answer, 'video', reference.protectRTCP(Buffer.from(PICTURE_LOSS, 'hex')))
+ await until(() => unprotect.mock.calls.length > read)
+ }
+ // Each session streams video tier 3, an identifier no sensor's audio tier carries. The tier a line names is told apart from the audio tier's.
+ const firstAnswer = await streaming(service, buildEmitterConnection(), first, 3)
+ const lines = captureDebug('HAP-NodeJS:Camera:MultiTier')
+
+ // The first session asks before the stream writes a keyframe. The second, started once the keyframe is released, asks while its opening waits on a
+ // live picture nobody writes. The first then asks twice.
+ await request(first, firstAnswer)
+ writeTierFrame(streamOf(delegate, 3), 'video', {
+ ...sliceFrame(300, 0),
+ keyframe: true,
+ })
+ await vi.advanceTimersByTimeAsync(50)
+ const secondAnswer = await streaming(service, buildEmitterConnection(), second, 3)
+ await vi.advanceTimersByTimeAsync(1)
+ await request(second, secondAnswer)
+ await request(first, firstAnswer)
+ await request(first, firstAnswer)
+
+ // Each request's session and what it came to, in the order they were made.
+ const asked: [Prepared, string][] = [
+ [firstAnswer, 'no keyframe kept'],
+ [secondAnswer, 'in an opening'],
+ [firstAnswer, 'answered'],
+ [firstAnswer, 'answered from this keyframe already'],
+ ]
+
+ expect(lines.filter(line => line.includes('takes a keyframe request')).map(line => line.slice(line.indexOf('Multi-tier session')))).toEqual(
+ asked.map(([answer, outcome]) => `Multi-tier session ${answer.sessionIdentifier} takes a keyframe request on video tier 3: ${outcome}.`),
+ )
+ })
+ })
+
+ describe('session ends', () => {
+ it('ends a session and its tier\'s demand, ignores a stale stream, logs a throwing demand end, and answers no such stream and unknown', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const answer = await streaming(service, connection, from)
+ const firstStream = streamOf(delegate)
+ delegate.disposals.get(firstStream)!.mockImplementationOnce(() => {
+ throw new Error('The encoder would not stop.')
+ })
+
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ await settle()
+ await until(() => udpSockets() === base)
+
+ await expect(readSetupEndpoints(service, connection)).resolves.toBe('AgEC')
+ expect(endedCalls(delegate)).toBe(1)
+ expect(error.mock.calls.filter(([line]) => String(line).startsWith('MultiTierStreamingDelegate failed to end a tier demand: '))).toHaveLength(1)
+
+ const next = await endpoint()
+ const later = await streaming(service, buildEmitterConnection(), next)
+ const secondStream = streamOf(delegate)
+ firstStream.write(tierStreamInitialization())
+ firstStream.write(tierStreamFragment({
+ picture: [
+ pictureSample(vectorFrame(HEVC, 1).data),
+ ],
+ }))
+ writeTierFrame(secondStream, 'video', {
+ ...vectorFrame(HEVC, 0),
+ keyframe: true,
+ })
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => next.received.video.length === 1)
+ await settle()
+
+ expect(secondStream).not.toBe(firstStream)
+ expect(next.received.video).toHaveLength(1)
+ expect(unprotected(later, next, 'video').map(packet => packet.subarray(12).toString('hex'))).toEqual(HEVC.frames[0].cuts[CUT])
+ expect(firstStream.statistics()).toEqual({
+ packets: 0,
+ bytes: 0,
+ drops: 0,
+ consumers: 0,
+ })
+ expect(secondStream.statistics().packets).toBe(1)
+
+ const prepared = crypto.randomUUID()
+ await prepare(service, connection, from, prepared)
+
+ expect(await end(service, connection, prepared)).toBe(RTPStreamingStatus.NO_SUCH_STREAM)
+ expect(await start(service, connection, prepared)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(await end(service, connection, UNKNOWN_SESSION)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ })
+
+ it('ends every session of a closing connection, closing its sockets, ending its demands, releasing its answers and removing its listeners', async () => {
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const closing = buildEmitterConnection()
+ const listeners = closing.listenerCount('closed')
+ const base = udpSockets()
+ await streaming(service, closing, from)
+ await prepare(service, closing, from, crypto.randomUUID())
+
+ closing.emit('closed')
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(endedCalls(delegate)).toBe(1)
+ expect(closing.listenerCount('closed')).toBe(listeners)
+ })
+
+ it('ends every session and releases every answer, a sessionless busy among them, when the camera or the service\'s streaming enabled turns off', async () => {
+ for (const turnOff of [
+ (h: Harness): void => {
+ h.global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ },
+ (h: Harness): void => {
+ h.service.updateCharacteristic(Characteristic.StreamingEnabled, false)
+ },
+ ]) {
+ const h = harness({ maxSessions: 1 })
+ const from = await endpoint()
+ const base = udpSockets()
+ const owner = buildEmitterConnection()
+ const refused = buildEmitterConnection()
+ const answer = await streaming(h.service, owner, from)
+ const busy = crypto.randomUUID()
+ expect(await prepare(h.service, refused, from, busy)).toEqual({ status: SetupEndpointsStatus.BUSY, sessionIdentifier: busy })
+
+ turnOff(h)
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(h.service.getCharacteristic(Characteristic.StatusActive).value).toBe(false)
+ await expect(readSetupEndpoints(h.service, refused)).resolves.toBe('AgEC')
+ await expect(readSetupEndpoints(h.service, owner)).resolves.toBe('AgEC')
+ expect(await start(h.service, owner, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(await prepare(h.service, owner, from, busy)).toEqual({ status: SetupEndpointsStatus.ERROR, sessionIdentifier: busy })
+ }
+ })
+
+ it('ends every session and releases every answer before a state-change delegate that throws at streaming enabled off', async () => {
+ const { management, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const answer = await streaming(service, connection, from)
+ management.setupStateChangeDelegate(() => {
+ throw new Error('The state could not be saved.')
+ })
+
+ await expect(service.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, buildEmitterConnection())).rejects.toBeDefined()
+ await settle()
+ await until(() => udpSockets() === base)
+
+ await expect(readSetupEndpoints(service, connection)).resolves.toBe('AgEC')
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ })
+
+ it('ends every session on a tier its stream fails, with one warning', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const base = udpSockets()
+ const first = buildEmitterConnection()
+ const second = buildEmitterConnection()
+ const firstAnswer = await streaming(service, first, from)
+ const secondAnswer = await streaming(service, second, from)
+ const stream = streamOf(delegate)
+
+ stream.fail('The encoder crashed.')
+ stream.fail('The encoder crashed again.')
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(warn.mock.calls[0][0]).toBe(`The plugin failed the stream of the video tier 1 of the video sensor "${SENSOR_UUID.toLowerCase()}" (The encoder `
+ + 'crashed.), and every session on the tier ends.')
+ expect(await end(service, first, firstAnswer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(await end(service, second, secondAnswer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(endedCalls(delegate)).toBe(1)
+ })
+
+ it('clears each medium\'s sender as a streaming session ends', async () => {
+ const { management, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ // @ts-expect-error: private access
+ const { media } = management.sessions.get(answer.sessionIdentifier)
+
+ expect([media.video.sender, media.audio.sender].every(sender => sender !== undefined)).toBe(true)
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expect([media.video.sender, media.audio.sender]).toEqual([undefined, undefined])
+ })
+
+ it('warns nothing and ends no session for a stale stream\'s fail after its demand ended, a later session on the tier streaming on', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const next = await endpoint()
+ const ending = buildEmitterConnection()
+ const later = buildEmitterConnection()
+ const ended = await streaming(service, ending, from)
+ const stale = streamOf(delegate)
+
+ expect(await end(service, ending, ended.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+
+ const answer = await streaming(service, later, next)
+ stale.fail('The stopped encoder crashed.')
+ await settle()
+ writeTierFrame(streamOf(delegate), 'video', keyframeWithSets(sliceFrame(300)))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => next.received.video.length === 1)
+
+ expect(warn).not.toHaveBeenCalled()
+ expect(unprotected(answer, next, 'video')).toHaveLength(1)
+ expect(await end(service, later, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ })
+
+ it('throws nothing from a frame written at every turn while a streaming session\'s exit runs', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, management, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+ const thrown: unknown[] = []
+ let exited = false
+ // Each frame a frame's length after the one before it: the stream's decode times rise.
+ let time = 0
+ const write = (): void => {
+ try {
+ writeTierFrame(stream, 'video', sliceFrame(300, time))
+ time += 33333
+ } catch (error) {
+ thrown.push(error)
+ }
+ }
+
+ /* A frame goes in at each of the exit's microtask turns, and at each turn of the event loop between them, and the mock clock moves on a frame's
+ * length at each: a frame falls due in a turn of the pacer's, until the whole exit has resolved. The exit's steps after its first run within one
+ * drain of the microtask and tick queues, a socket's close completing on a tick, which means a pacer's turn falls between them only where the clock moves at a
+ * microtask turn.
+ */
+ const exiting = management.endSession(answer.sessionIdentifier).then(() => {
+ exited = true
+ })
+ const running = (): boolean => !exited
+
+ while (running()) {
+ for (let step = 0; step < 50 && running(); step++) {
+ write()
+ vi.advanceTimersByTime(33.333)
+ await Promise.resolve()
+ }
+
+ write()
+ await vi.advanceTimersByTimeAsync(33.333)
+ await settle()
+ }
+
+ await exiting
+
+ expect(thrown).toEqual([])
+ expect(logged.mock.calls.filter(([line]) => String(line).includes('consumer of the'))).toEqual([])
+ expect(stream.statistics().consumers).toBe(0)
+ })
+
+ it('throws nothing from a frame written at every turn while a session waiting on its pending demand exits', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, management, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const identifier = crypto.randomUUID()
+ const pending = deferred()
+ await prepare(service, connection, from, identifier)
+ pendingStart(delegate, pending)
+
+ const starting = start(service, connection, identifier)
+ await settle()
+ const stream = streamOf(delegate)
+ const thrown: unknown[] = []
+ let exited = false
+ // Each frame a frame's length after the one before it: the stream's decode times rise.
+ let time = 0
+ const write = (): void => {
+ try {
+ writeTierFrame(stream, 'video', sliceFrame(300, time))
+ time += 33333
+ } catch (error) {
+ thrown.push(error)
+ }
+ }
+
+ expect(stream.statistics().consumers).toBe(2)
+
+ // A frame goes in at each of the exit's microtask turns, and at each turn of the event loop between them, and the mock clock moves on a frame's
+ // length at each: a frame falls due in a turn of the pacer's, until the exit and the Start it cut have resolved, as the streaming exit's row reads.
+ const exiting = Promise.all([
+ management.endSession(identifier),
+ starting,
+ ]).then(() => {
+ exited = true
+ })
+ const running = (): boolean => !exited
+
+ while (running()) {
+ for (let step = 0; step < 50 && running(); step++) {
+ write()
+ vi.advanceTimersByTime(33.333)
+ await Promise.resolve()
+ }
+
+ write()
+ await vi.advanceTimersByTimeAsync(33.333)
+ await settle()
+ }
+
+ await exiting
+ pending.resolve()
+
+ expect(thrown).toEqual([])
+ expect(logged.mock.calls.filter(([line]) => String(line).includes('consumer of the'))).toEqual([])
+ expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(stream.statistics().consumers).toBe(0)
+ })
+
+ it('ends a session whose socket reports an error, with one debug line, the emit throwing nothing', async () => {
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const answer = await streaming(service, connection, from)
+ const { video } = accessorySockets(createSocket)
+ const lines = captureDebug('HAP-NodeJS:Camera:MultiTier')
+
+ expect(() => video.emit('error', Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' }))).not.toThrow()
+
+ // The lines the emit wrote, read apart from those the session's end writes as the row waits on it.
+ const emitted = lines.length
+
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(lines.slice(0, emitted).filter(line => line.includes('reports an error'))).toHaveLength(1)
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ })
+
+ it.each([
+ { ending: 'reset' },
+ { ending: 'destroy' },
+ ])('sends nothing a tier\'s pacer still holds after a $ending, and leaves it no timer to run', async ({ ending }) => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, management, service } = harness()
+ const from = await endpoint()
+
+ await streaming(service, buildEmitterConnection(), from)
+
+ const stream = streamOf(delegate)
+ const released = vi.spyOn(TierPacer.prototype, 'release')
+
+ // A keyframe sent at once and the next picture, written in the same moment, held a frame's length behind it when the session ends.
+ writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0)))
+ writeTierFrame(stream, 'video', sliceFrame(300, 33333))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.video.length === 1)
+
+ if (ending === 'reset') {
+ management.handleFactoryReset()
+ } else {
+ await management.destroy()
+ }
+
+ await until(() => endedCalls(delegate) === 1)
+ released.mockClear()
+ await vi.advanceTimersByTimeAsync(1000)
+ await settle()
+
+ expect(released).not.toHaveBeenCalled()
+ expect(stream.statistics().packets).toBe(1)
+ expect(from.received.video).toHaveLength(1)
+ })
+ })
+
+ describe('rtcp', () => {
+ it('reads authenticated reports for liveness and keyframe requests, and drops a tampered and a replayed one', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP')
+ const timeout = vi.spyOn(globalThis, 'setTimeout')
+ // The hold's entry each keyframe request the session reads goes to.
+ const requests = vi.spyOn(TierHold.prototype, 'answerKeyframeRequest')
+ const { service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.video)
+ const arrived = async (count: number): Promise => until(() => unprotect.mock.calls.length === count)
+ const livenessWindows = (): number => timeout.mock.calls.filter(([, delay]) => delay === 25000).length
+
+ sendDatagram(from, answer, 'video', reference.protectRTCP(Buffer.from(RECEIVER_REPORT, 'hex')))
+ await arrived(1)
+
+ expect(livenessWindows()).toBe(1)
+ expect(requests).not.toHaveBeenCalled()
+
+ const pictureLoss = reference.protectRTCP(Buffer.from(PICTURE_LOSS, 'hex'))
+ sendDatagram(from, answer, 'video', pictureLoss)
+ await arrived(2)
+ sendDatagram(from, answer, 'video', reference.protectRTCP(Buffer.from(FULL_INTRA_REQUEST, 'hex')))
+ await arrived(3)
+
+ expect(requests).toHaveBeenCalledTimes(2)
+
+ const tampered = reference.protectRTCP(Buffer.from(PICTURE_LOSS, 'hex'))
+ tampered[10] ^= 0x01
+ sendDatagram(from, answer, 'video', tampered)
+ sendDatagram(from, answer, 'video', pictureLoss)
+ await arrived(5)
+
+ expect(requests).toHaveBeenCalledTimes(2)
+ expect(livenessWindows()).toBe(1)
+
+ // A picture loss indication that authenticates on the audio socket asks for nothing.
+ sendDatagram(from, answer, 'audio', new ReferenceSRTP(CONTROLLER_KEYS.audio).protectRTCP(Buffer.from(PICTURE_LOSS, 'hex')))
+ await arrived(6)
+
+ expect(requests).toHaveBeenCalledTimes(2)
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ })
+
+ it('ends a session silent for the liveness window after one report, and keeps one that never reported at twice the window', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP')
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const reporting = buildEmitterConnection()
+ const silent = buildEmitterConnection()
+ const reported = await streaming(service, reporting, from)
+ const quiet = await streaming(service, silent, from)
+
+ // The sessions' one tier hands over pictures through each wait, which keeps its demand inside its silence bounds and leaves the liveness window
+ // alone to end a session.
+ sendDatagram(from, reported, 'audio', new ReferenceSRTP(CONTROLLER_KEYS.audio).protectRTCP(Buffer.from(RECEIVER_REPORT, 'hex')))
+ await until(() => unprotect.mock.calls.length === 1)
+ await keepStreaming([
+ streamOf(delegate),
+ ], 25000, { advance: advanceAsync })
+
+ expect(await end(service, reporting, reported.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+
+ await keepStreaming([
+ streamOf(delegate),
+ ], 25000, { advance: advanceAsync, from: 25000000 })
+
+ expect(await end(service, silent, quiet.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ })
+
+ it('sends a video sender report at 2.5 seconds with its SSRC and counts, none for silent audio, and wraps the NTP seconds in 2036', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const reports = (): Buffer[] => from.received.video.filter(datagram => datagram[1] === 200)
+
+ // One keyframe of a 300-octet slice and its parameter sets, which goes as one aggregation packet.
+ writeTierFrame(streamOf(delegate), 'video', keyframeWithSets(sliceFrame(300)))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.video.length === 1)
+ await vi.advanceTimersByTimeAsync(2499)
+ await settle()
+
+ expect(reports()).toEqual([])
+
+ await vi.advanceTimersByTimeAsync(1)
+ await until(() => reports().length === 1)
+
+ const reference = new ReferenceSRTP(answer.videoSRTPParameters)
+ const report = reference.unprotectRTCP(reports()[0])!
+
+ expect(report).toHaveLength(28)
+ expect(report.subarray(0, 4).toString('hex')).toBe('80c80006')
+ expect(report.readUInt32BE(4)).toBe(answer.videoSSRC)
+ expect(report.readUInt32BE(20)).toBe(1)
+ expect(report.readUInt32BE(24)).toBe(setsAggregated(300))
+ expect(from.received.audio).toEqual([])
+
+ // The clock answers 2036 only while the next report's timer fires, because the test runner reads Date.now too.
+ const in2036 = Date.UTC(2036, 1, 8)
+ const now = vi.spyOn(Date, 'now').mockReturnValue(in2036)
+ await vi.advanceTimersByTimeAsync(7000)
+ now.mockRestore()
+ await until(() => reports().length >= 2)
+
+ expect(reference.unprotectRTCP(reports()[1])!.readUInt32BE(8)).toBe((Math.floor(in2036 / 1000) + 2208988800) % 0x100000000)
+ expect(from.received.audio).toEqual([])
+ })
+
+ it('writes the video sender report\'s NTP fraction from the milliseconds past the clock\'s second', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const reports = (): Buffer[] => from.received.video.filter(datagram => datagram[1] === 200)
+
+ writeTierFrame(streamOf(delegate), 'video', keyframeWithSets(sliceFrame(300)))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.video.length === 1)
+
+ // The clock answers three milliseconds past a second only while the report's timer fires, because the test runner reads Date.now too.
+ const now = vi.spyOn(Date, 'now').mockReturnValue(Date.UTC(2036, 1, 8) + 3)
+ await vi.advanceTimersByTimeAsync(2500)
+ now.mockRestore()
+ await until(() => reports().length === 1)
+
+ // Three milliseconds are three thousandths of the fraction word's 2^32, floored.
+ expect(new ReferenceSRTP(answer.videoSRTPParameters).unprotectRTCP(reports()[0])!.readUInt32BE(12)).toBe(0x00C49BA5)
+ })
+
+ it('writes the video sender report\'s RTP timestamp as the last frame\'s, advanced by the time since its write at the clock\'s rate', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+ const reports = (): Buffer[] => from.received.video.filter(datagram => datagram[1] === 200)
+
+ // The steady clock moves only as the row advances it: the frames are written 1460 and 1500 milliseconds into the session, a second before its first
+ // report at 2.5 seconds.
+ await vi.advanceTimersByTimeAsync(1460)
+ writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0)))
+ await vi.advanceTimersByTimeAsync(0)
+ await vi.advanceTimersByTimeAsync(40)
+ writeTierFrame(stream, 'video', sliceFrame(300, 33333))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.video.length === 2)
+ await vi.advanceTimersByTimeAsync(1000)
+ await until(() => reports().length === 1)
+
+ const reference = new ReferenceSRTP(answer.videoSRTPParameters)
+ const [first, last] = from.received.video.filter(datagram => datagram[1] !== 200).map(datagram => reference.unprotect(datagram)!.readUInt32BE(4))
+
+ expect((last - first) >>> 0).toBe(3000)
+ expect(reference.unprotectRTCP(reports()[0])!.readUInt32BE(16)).toBe((last + 1000 * 90) >>> 0)
+ })
+
+ it('advances a report\'s RTP timestamp by the steady time since the write when the time of day steps back an hour, stating that time\'s NTP time', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const reports = (): Buffer[] => from.received.video.filter(datagram => datagram[1] === 200)
+
+ await vi.advanceTimersByTimeAsync(1500)
+ writeTierFrame(streamOf(delegate), 'video', keyframeWithSets(sliceFrame(300)))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.video.length === 1)
+
+ // The time of day stands an hour behind only while the report's timer fires, a second of the steady clock after the write, because the test runner
+ // reads Date.now too.
+ const stepped = Date.now() - 3600 * 1000
+ const now = vi.spyOn(Date, 'now').mockReturnValue(stepped)
+ await vi.advanceTimersByTimeAsync(1000)
+ now.mockRestore()
+ await until(() => reports().length === 1)
+
+ const reference = new ReferenceSRTP(answer.videoSRTPParameters)
+ const [placed] = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4))
+ const report = reference.unprotectRTCP(reports()[0])!
+
+ expect(report.readUInt32BE(16)).toBe((placed + 1000 * 90) >>> 0)
+ expect(report.readUInt32BE(8)).toBe((Math.floor(stepped / 1000) + 2208988800) % 0x100000000)
+ })
+ })
+
+ describe('frame consumers', () => {
+ it('hands a frame consumer beside a session every frame the session is sent, whole with its flags, timestamp and run, and no malformed one', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service, table } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const consumer = scriptedFrameConsumer()
+ table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer)
+ const stream = streamOf(delegate)
+ const keyframe: TierFrame = {
+ ...sliceFrame(300, 0),
+ keyframe: true,
+ }
+ // The run the discontinuity opens starts on a keyframe as the first run does.
+ const frames = [
+ keyframe,
+ sliceFrame(300, 33333),
+ {
+ data: Buffer.from('0000000a0201', 'hex'),
+ time: 66667,
+ },
+ {
+ ...sliceFrame(300, 0, true),
+ keyframe: true,
+ },
+ ]
+
+ for (const frame of frames) {
+ writeTierFrame(stream, 'video', frame)
+ }
+
+ // The discontinuity ends the run before the turn, which is why its frames leave at once with the run opened after it.
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.video.length === 3)
+
+ const timestamps = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4))
+
+ expect(consumer.taken.map(({ frame }) => [frame.time, frame.keyframe === true])).toEqual([frames[0], frames[1], frames[3]].map(({ keyframe, time }) => [
+ time,
+ keyframe === true,
+ ]))
+ expect(consumer.taken.map(({ data }) => data.equals(sliceFrame(300).data))).toEqual([true, true, true])
+ expect(consumer.taken.map(({ timestamp }) => timestamp >>> 0)).toEqual(timestamps)
+ expect(consumer.taken.map(({ opensRun }) => opensRun)).toEqual([true, false, true])
+ expect(stream.statistics()).toMatchObject({ packets: 3, drops: 1 })
+ })
+
+ it('raises a demand for a frame consumer alone, hands it frames and cuts none, and ends the demand once at its release', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const cut = vi.spyOn(FrameCutter.prototype, 'cut')
+ const { delegate, table } = harness()
+ const consumer = scriptedFrameConsumer()
+ const hold = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer)
+
+ expect(await hold.answer()).toBe('started')
+
+ const stream = streamOf(delegate)
+ writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0)))
+ writeTierFrame(stream, 'video', sliceFrame(300, 33333))
+ await vi.advanceTimersByTimeAsync(34)
+
+ expect(consumer.taken).toHaveLength(2)
+ expect(cut).not.toHaveBeenCalled()
+ expect(stream.statistics()).toEqual({
+ packets: 0,
+ bytes: 0,
+ drops: 0,
+ consumers: 1,
+ })
+
+ hold.release()
+ hold.release()
+ await settle()
+
+ expect(delegate.tierDemandStarted).toHaveBeenCalledOnce()
+ expect(endedCalls(delegate)).toBe(1)
+ })
+
+ it('counts a session once for each medium it takes and a frame consumer once on one demand, three consumers', async () => {
+ const { delegate, service, table } = harness()
+ await streaming(service, buildEmitterConnection(), await endpoint())
+ table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), scriptedFrameConsumer())
+
+ expect(streamOf(delegate).statistics().consumers).toBe(3)
+ })
+
+ it('calls a frame consumer\'s route once and ends the session beside it when the tier\'s stream fails', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, service, table } = harness()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, await endpoint())
+ const holder = scriptedHolder()
+ table.joinFrames(table.videoTiers.get(1)!, 'video', holder, scriptedFrameConsumer())
+
+ streamOf(delegate).fail('The encoder crashed.')
+ streamOf(delegate).fail('The encoder crashed again.')
+ await settle()
+
+ expect(holder.tierFailed).toHaveBeenCalledOnce()
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ })
+
+ it('logs a frame consumer\'s throwing hand-over once and ends it through its route, the write throwing nothing and the next consumer taking the frame', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { delegate, table } = harness()
+ const tier = table.videoTiers.get(1)!
+ const throwingHolder = scriptedHolder()
+ const throwing = table.joinFrames(tier, 'video', throwingHolder, {
+ take: () => {
+ throw new Error('The sealer failed.')
+ },
+ })
+ const next = scriptedFrameConsumer()
+ table.joinFrames(tier, 'video', scriptedHolder(), next)
+
+ expect(await throwing.answer()).toBe('started')
+
+ const stream = streamOf(delegate)
+
+ expect(() => writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0)))).not.toThrow()
+ expect(() => writeTierFrame(stream, 'video', sliceFrame(300, 33333))).not.toThrow()
+ await vi.advanceTimersByTimeAsync(34)
+ expect(error).toHaveBeenCalledOnce()
+ expect(String(error.mock.calls[0][0])).toMatch(/^A frame consumer of the picture of the video tier 1 of the video sensor ".+" failed to take a frame, and it /)
+ expect(throwingHolder.tierFailed).toHaveBeenCalledOnce()
+ expect(next.taken).toHaveLength(2)
+ })
+
+ it('completes the walk past a frame consumer whose hand-over ends its own holder, and passes it over once its release has run', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, table } = harness()
+ const tier = table.videoTiers.get(1)!
+ const after = [
+ scriptedFrameConsumer(),
+ scriptedFrameConsumer(),
+ ]
+ const ended = scriptedFrameConsumer()
+
+ // The consumer's way out of its own hand-over is its holder's end, which releases its hold in a later turn.
+ const ending: TierHold = table.joinFrames(tier, 'video', scriptedHolder(), {
+ take: (frame, timestamp, opensRun) => {
+ ended.take(frame, timestamp, opensRun)
+ void Promise.resolve().then(() => ending.release())
+ },
+ })
+
+ for (const consumer of after) {
+ table.joinFrames(tier, 'video', scriptedHolder(), consumer)
+ }
+
+ expect(await ending.answer()).toBe('started')
+
+ const stream = streamOf(delegate)
+ writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0)))
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect([
+ ended.taken.length,
+ ...after.map(({ taken }) => taken.length),
+ ]).toEqual([1, 1, 1])
+
+ await settle()
+ writeTierFrame(stream, 'video', sliceFrame(300, 33333))
+ await vi.advanceTimersByTimeAsync(34)
+
+ expect([
+ ended.taken.length,
+ ...after.map(({ taken }) => taken.length),
+ ]).toEqual([1, 2, 2])
+ })
+
+ it('hands a frame consumer joining a video tier another consumer streams none of the frames released before its join, counting in consumers from '
+ + 'it', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, table } = harness()
+ const tier = table.videoTiers.get(1)!
+ const streamer = scriptedFrameConsumer()
+ const consumer = scriptedFrameConsumer()
+ // A sound of the tier's stream at a time in microseconds.
+ const sound = (time: number): WrittenFrame => ({
+ data: Buffer.alloc(60, 0x78),
+ time,
+ })
+
+ // Each consumer takes the tier's sound, which joins the live releases at once: its join alone decides what it is handed, where a consumer of the
+ // picture opens from the keyframe the buffer keeps.
+ expect(await table.joinFrames(tier, 'audio', scriptedHolder(), streamer).answer()).toBe('started')
+
+ const stream = streamOf(delegate)
+ writeTierFrame(stream, 'audio', sound(0))
+ writeTierFrame(stream, 'audio', sound(33333))
+ await vi.advanceTimersByTimeAsync(34)
+
+ expect(stream.statistics().consumers).toBe(1)
+
+ table.joinFrames(tier, 'audio', scriptedHolder(), consumer)
+
+ expect(consumer.taken).toEqual([])
+ expect(stream.statistics().consumers).toBe(2)
+
+ writeTierFrame(stream, 'audio', sound(66667))
+ await vi.advanceTimersByTimeAsync(34)
+
+ expect(consumer.taken.map(({ frame }) => frame.time)).toEqual([66667])
+ expect(streamer.taken.map(({ frame }) => frame.time)).toEqual([0, 33333, 66667])
+ })
+
+ it('hands a frame consumer carrying a member named send every frame through its join, and sends it no packet', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, table } = harness()
+ const send = vi.fn<(packet: Buffer, octets: number, now: number) => boolean>(() => true)
+ const consumer = {
+ ...scriptedFrameConsumer(),
+ send,
+ }
+
+ expect(await table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer).answer()).toBe('started')
+
+ const stream = streamOf(delegate)
+ writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0)))
+ writeTierFrame(stream, 'video', sliceFrame(300, 33333))
+ await vi.advanceTimersByTimeAsync(34)
+
+ expect(consumer.taken.map(({ frame }) => frame.time)).toEqual([0, 33333])
+ expect(send).not.toHaveBeenCalled()
+ expect(stream.statistics()).toMatchObject({ packets: 0, consumers: 1 })
+ })
+
+ it('hands a frame consumer raising a demand the stream written inside its tierDemandStarted', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, table } = harness()
+ const tier = table.videoTiers.get(1)!
+ const raiser = scriptedFrameConsumer()
+
+ delegate.tierDemandStarted.mockImplementationOnce(async (stream) => {
+ stream.write(tierStreamInitialization())
+ stream.write(tierStreamFragment({
+ picture: [
+ keyframeSample(),
+ ],
+ }))
+ })
+
+ expect(await table.joinFrames(tier, 'video', scriptedHolder(), raiser).answer()).toBe('started')
+ await vi.advanceTimersByTimeAsync(0)
+ expect(raiser.taken.map(({ frame }) => frame.time)).toEqual([0])
+ })
+ })
+
+ describe('frame timing', () => {
+ it('times a first frame at one moment alike on two video tiers, each at its rate on the sensor\'s one clock, and a tier\'s sound two seconds after its '
+ + 'picture two seconds of the sound\'s ticks later on the picture\'s run', async () => {
+ // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds. Its
+ // origin is a whole millisecond, which is why the sound's due moment stands exactly two seconds after its picture's: on a fractional origin that sum can round
+ // up, which arms the pacer's timer a millisecond past the row's two-second step and leaves the sound unsent.
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const origin = Math.ceil(performance.now())
+ const made = vi.spyOn(performance, 'now').mockReturnValue(origin)
+ const { delegate, service } = harness()
+ made.mockRestore()
+ const firstEndpoint = await endpoint()
+ const secondEndpoint = await endpoint()
+ const first = await streaming(service, buildEmitterConnection(), firstEndpoint, 1)
+ const second = await streaming(service, buildEmitterConnection(), secondEndpoint, 2)
+
+ // Each tier's first frame, its keyframe, arrives a second after the management was made.
+ const now = vi.spyOn(performance, 'now').mockReturnValue(origin + 1000)
+ writeTierFrame(streamOf(delegate, 1), 'video', keyframeWithSets(sliceFrame(300, 5000000)))
+ writeTierFrame(streamOf(delegate, 2), 'video', keyframeWithSets(sliceFrame(200, 9000000)))
+ writeTierFrame(streamOf(delegate), 'audio', {
+ data: Buffer.alloc(80, 0x78),
+ time: 7000000,
+ })
+ await vi.advanceTimersByTimeAsync(0)
+
+ // The sound, in a fragment of its own, falls due on its picture's schedule two seconds after that picture, and the steady clock stands half a second
+ // past that as the pacer releases it: its release stands apart from its presentation's distance and only one run places it two seconds on.
+ now.mockReturnValue(origin + 3500)
+ await vi.advanceTimersByTimeAsync(2000)
+ now.mockRestore()
+ await until(() => firstEndpoint.received.video.length === 1 && secondEndpoint.received.video.length === 1 && firstEndpoint.received.audio.length === 1)
+
+ const [videoOne] = unprotected(first, firstEndpoint, 'video').map(packet => packet.readUInt32BE(4))
+ const [videoTwo] = unprotected(second, secondEndpoint, 'video').map(packet => packet.readUInt32BE(4))
+ const [audio] = unprotected(first, firstEndpoint, 'audio').map(packet => packet.readUInt32BE(4))
+
+ // Tier 1's picture opens its demand's one run, and the sound written in the same moment and timed two seconds after it stands two seconds of its
+ // ticks after that moment.
+ expect(videoTwo).toBe(videoOne)
+ expect((videoOne - 90000) >>> 0).toBe((audio - 48000 - 2 * 48000) >>> 0)
+ })
+
+ it('places a frame written after a malformed one at its own moment, which the malformed frame never moved', async () => {
+ // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds.
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+ const moment = performance.now()
+
+ // A frame placed at its own moment, three seconds in, stands seventeen seconds of ticks before a discontinuity placed at twenty seconds in. Had the
+ // malformed frame at time zero opened the run, the frame timed ten seconds would stand ten seconds in, and the two only ten seconds of ticks apart.
+ const now = vi.spyOn(performance, 'now').mockReturnValue(moment)
+ writeTierFrame(stream, 'video', {
+ data: Buffer.from('0000000a0201', 'hex'),
+ time: 0,
+ })
+ now.mockReturnValue(moment + 3000)
+ writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 10000000)))
+ await vi.advanceTimersByTimeAsync(0)
+ now.mockReturnValue(moment + 20000)
+ writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 10000000, true)))
+ await vi.advanceTimersByTimeAsync(0)
+ now.mockRestore()
+ await until(() => from.received.video.length === 2)
+
+ const [placed, reopened] = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4))
+
+ expect((reopened - placed) >>> 0).toBe(17000 * 90)
+ expect(stream.statistics().drops).toBe(1)
+ })
+
+ it('keeps a frame in its run when the time of day steps back an hour before it, and opens a later discontinuity at its steady moment\'s timestamp', async () => {
+ // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds.
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const stream = streamOf(delegate)
+ const steady = performance.now()
+ const day = Date.now()
+
+ // The clocks answer each write's moments only while it runs, because the test runner reads each clock: the time of day steps back an hour between the first
+ // two writes, while the steady clock moves forty milliseconds, and the discontinuity comes five seconds of the steady clock after that.
+ const now = vi.spyOn(performance, 'now').mockReturnValue(steady)
+ const time = vi.spyOn(Date, 'now').mockReturnValue(day)
+ writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0)))
+ await vi.advanceTimersByTimeAsync(0)
+ now.mockReturnValue(steady + 40)
+ time.mockReturnValue(day - 3600 * 1000)
+ writeTierFrame(stream, 'video', sliceFrame(300, 33333))
+ await vi.advanceTimersByTimeAsync(0)
+ now.mockReturnValue(steady + 5040)
+ writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0, true)))
+ await vi.advanceTimersByTimeAsync(0)
+ now.mockRestore()
+ time.mockRestore()
+ await until(() => from.received.video.length === 3)
+
+ const [first, second, reopened] = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4))
+
+ expect((second - first) >>> 0).toBe(3000)
+ expect((reopened - first) >>> 0).toBe(5040 * 90)
+ })
+
+ it('keeps one run for sixty frames of a 30 fps source written in one turn, each frame\'s packet 3000 ticks after the one before, warning nothing', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const held = holdSends(accessorySockets(createSocket).video)
+ const stream = streamOf(delegate)
+
+ // Each frame stands 33,333 or 33,334 microseconds after the one before, as a source's clock rounds a thirtieth of a second, and the last nearly two
+ // seconds after the first, a keyframe.
+ for (let frame = 0; frame < 60; frame++) {
+ const picture = sliceFrame(300, Math.round(frame * 1000000 / 30))
+
+ writeTierFrame(stream, 'video', (frame === 0)
+ ? keyframeWithSets(picture)
+ : picture)
+ }
+
+ await vi.advanceTimersByTimeAsync(1967)
+
+ const reference = new ReferenceSRTP(answer.videoSRTPParameters)
+ const timestamps = held.map(send => reference.unprotect(send.sent)!.readUInt32BE(4))
+
+ expect(complete(held)).toBe(60)
+ expect(timestamps.slice(1).map((timestamp, index) => (timestamp - timestamps[index]) >>> 0)).toEqual(timestamps.slice(1).map(() => 3000))
+ expect(warn).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('keyframe parameter sets', () => {
+ // A keyframe of the parameter sets whose types it is given, each a synthetic unit opening with its type's NAL unit header, and an IDR picture slice.
+ function keyframeOf(types: readonly number[], time = 0): TierFrame {
+ return {
+ data: tierFrameData([
+ ...types.map(type => nalUnit(Buffer.from([type << 1, 0x01]), 12)),
+ nalUnit(Buffer.from([0x26, 0x01]), 300),
+ ]),
+ keyframe: true,
+ time,
+ }
+ }
+
+ // The RTP payloads a cutter at the default packet size makes of a frame, as hex.
+ function payloadsOf(frame: TierFrame): string[] {
+ const cutter = new FrameCutter('video', Buffer.alloc(CUT))
+ const payloads: string[] = []
+
+ cutter.cut(frame.data, 0, true)
+
+ for (let packet = cutter.next(); packet !== undefined; packet = cutter.next()) {
+ payloads.push(packet.subarray(12).toString('hex'))
+ }
+
+ return payloads
+ }
+
+ const sentence = `The stream of the video tier 1 of the video sensor "${SENSOR_UUID.toLowerCase()}" carries a keyframe without its video, sequence and `
+ + 'picture parameter sets, in its sample or its initialization segment, which a viewer needs to decode it, and the keyframe is sent as it stands.'
+
+ it('sends a session and hands a frame consumer a keyframe without its sequence parameter set as written, warning once for the demand', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, service, table } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const consumer = scriptedFrameConsumer()
+ table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer)
+ const stream = streamOf(delegate)
+ const lacking = keyframeOf([32, 34])
+
+ writeTierFrame(stream, 'video', lacking)
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(warn.mock.calls).toEqual([
+ [sentence],
+ ])
+
+ writeTierFrame(stream, 'video', keyframeOf([32, 34], 33333))
+ await vi.advanceTimersByTimeAsync(34)
+ await until(() => from.received.video.length === 2 * payloadsOf(lacking).length)
+
+ expect(unprotected(answer, from, 'video').map(packet => packet.subarray(12).toString('hex'))).toEqual([
+ ...payloadsOf(lacking),
+ ...payloadsOf(lacking),
+ ])
+ expect(consumer.taken.map(({ data }) => data.equals(lacking.data))).toEqual([true, true])
+ expect(warn).toHaveBeenCalledOnce()
+ })
+
+ it('warns nothing for a keyframe carrying all three sets, a frame not marked a keyframe or an audio frame', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, table } = harness()
+
+ expect(await table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), scriptedFrameConsumer()).answer()).toBe('started')
+ expect(await table.joinFrames(table.videoTiers.get(1)!, 'audio', scriptedHolder(), scriptedFrameConsumer()).answer()).toBe('started')
+
+ writeTierFrame(streamOf(delegate), 'video', keyframeOf([32, 33, 34]))
+ writeTierFrame(streamOf(delegate), 'video', {
+ ...keyframeOf([], 33333),
+ keyframe: false,
+ })
+ writeTierFrame(streamOf(delegate), 'audio', {
+ data: Buffer.from([0xFC, 0x01]),
+ keyframe: true,
+ time: 0,
+ })
+ await vi.advanceTimersByTimeAsync(34)
+
+ expect(warn).not.toHaveBeenCalled()
+ })
+
+ it('reads a stream\'s keyframe with the parameter sets its initialization segment carries, sending them in it and warning nothing, and warns once for '
+ + 'a keyframe whose segment and sample hold none', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, table } = harness()
+ const sets = [32, 33, 34].map(type => nalUnit(Buffer.from([type << 1, 0x01]), 12))
+ const slice = nalUnit(Buffer.from([0x26, 0x01]), 300)
+ const consumers = [1, 2].map(() => scriptedFrameConsumer())
+
+ for (const [index, consumer] of consumers.entries()) {
+ expect(await table.joinFrames(table.videoTiers.get(index + 1)!, 'video', scriptedHolder(), consumer).answer()).toBe('started')
+ }
+
+ for (const [tierId, parameterSets] of [
+ [1, sets],
+ [2, []],
+ ] as const) {
+ streamOf(delegate, tierId).write(tierStreamInitialization({ parameterSets }))
+ streamOf(delegate, tierId).write(tierStreamFragment({
+ picture: [
+ pictureSample(tierFrameData([slice]), true),
+ ],
+ }))
+ }
+
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(consumers.map(({ taken }) => taken.map(({ data }) => data.toString('hex')))).toEqual([
+ [
+ tierFrameData([...sets, slice]).toString('hex'),
+ ],
+ [
+ tierFrameData([slice]).toString('hex'),
+ ],
+ ])
+ expect(warn.mock.calls).toEqual([
+ [
+ sentence.replace('video tier 1', 'video tier 2'),
+ ],
+ ])
+ })
+
+ it('sends a session each parameter set once in the packets of a keyframe that holds them over a stream whose initialization segment carries them too, '
+ + 'and hands a frame consumer the keyframe as its sample holds it', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, service, table } = harness()
+ const from = await endpoint()
+ const answer = await streaming(service, buildEmitterConnection(), from)
+ const consumer = scriptedFrameConsumer()
+ table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer)
+ const stream = streamOf(delegate)
+ const holding = keyframeOf([32, 33, 34])
+
+ stream.write(tierStreamInitialization({
+ parameterSets: [32, 33, 34].map(type => nalUnit(Buffer.from([type << 1, 0x01]), 12)),
+ }))
+ stream.write(tierStreamFragment({
+ picture: [
+ pictureSample(holding.data, true),
+ ],
+ }))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.video.length === payloadsOf(holding).length)
+
+ expect(unprotected(answer, from, 'video').map(packet => packet.subarray(12).toString('hex'))).toEqual(payloadsOf(holding))
+ expect(consumer.taken.map(({ data }) => data.toString('hex'))).toEqual([
+ holding.data.toString('hex'),
+ ])
+ expect(warn).not.toHaveBeenCalled()
+ })
+
+ it('warns again for the first such keyframe of a new demand of the tier', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { delegate, table } = harness()
+ const tier = table.videoTiers.get(1)!
+ const first = table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer())
+
+ expect(await first.answer()).toBe('started')
+
+ writeTierFrame(streamOf(delegate), 'video', keyframeOf([33, 34]))
+ writeTierFrame(streamOf(delegate), 'video', keyframeOf([33, 34], 33333))
+ await vi.advanceTimersByTimeAsync(34)
+ first.release()
+ await settle()
+
+ expect(await table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer()).answer()).toBe('started')
+
+ writeTierFrame(streamOf(delegate), 'video', keyframeOf([33, 34]))
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2)
+ expect(warn.mock.calls).toEqual([
+ [sentence],
+ [sentence],
+ ])
+ })
+ })
+
+ describe('talkback', () => {
+ it('writes each authenticated talkback packet whole to one sink, each in its own datagram\'s buffer with the tag behind it, and ends the sink at End', async () => {
+ const { delegate, service } = harness()
+ const { packets, release, start: startSink } = keepingSink()
+ delegate.talkbackStarted.mockImplementation(startSink)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+ // The first packet carries the marker bit above its payload type, as a talkspurt's first packet does.
+ const plain = [
+ talkbackPacket(1, { payloadType: 0x80 | 110 }),
+ talkbackPacket(2),
+ talkbackPacket(3),
+ ]
+ const sent = plain.map(packet => reference.protect(packet))
+
+ // Each packet goes through the controller's socket, and each kept buffer is the one Node handed the session for its datagram.
+ for (const [index, datagram] of sent.entries()) {
+ sendDatagram(from, answer, 'audio', datagram)
+ await until(() => packets.length === index + 1)
+ }
+
+ expect(delegate.talkbackStarted.mock.calls.map(([talker]) => talker.sensorUUID)).toEqual([
+ SENSOR_UUID.toLowerCase(),
+ ])
+ expect(packets).toEqual(plain)
+ expect(new Set(packets.map(packet => packet.buffer)).size).toBe(packets.length)
+
+ for (const [index, packet] of packets.entries()) {
+ expect(packet.byteOffset).toBe(0)
+ expect(Buffer.from(packet.buffer, packet.length)).toEqual(sent[index].subarray(packet.length))
+ }
+
+ expect(release).not.toHaveBeenCalled()
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expect(release).toHaveBeenCalledOnce()
+ })
+
+ it('drops talkback before Start, tampered, of another SSRC or payload type, too short, on the video socket or replayed, logging a refusal once', async () => {
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ const { sink, packets } = keepingSink()
+ delegate.talkbackStarted.mockReturnValue(sink)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const identifier = crypto.randomUUID()
+ await prepare(service, connection, from, identifier)
+ const { video, audio } = accessorySockets(createSocket)
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+ const videoReference = new ReferenceSRTP(CONTROLLER_KEYS.video)
+
+ audio.emit('message', reference.protect(talkbackPacket(1)))
+
+ expect(await start(service, connection, identifier)).toBe(RTPStreamingStatus.SUCCESS)
+
+ const tampered = reference.protect(talkbackPacket(2))
+ tampered[20] ^= 0x01
+ const otherSSRC = reference.protect(talkbackPacket(3, { ssrc: 0x55667788 }))
+ const otherPayloadType = reference.protect(talkbackPacket(4, { payloadType: 111 }))
+ const short = Buffer.from([0x80, 110, 0, 5])
+ const videoUnderVideoKey = videoReference.protect(talkbackPacket(6))
+ const videoUnderAudioKey = reference.protect(talkbackPacket(7))
+ const accepted = reference.protect(talkbackPacket(8))
+ // The replay is taken before the accepted packet is handed over, because the session unprotects that packet in its own buffer.
+ const replay = Buffer.from(accepted)
+ const lines = captureDebug('HAP-NodeJS:Camera:MultiTier')
+
+ audio.emit('message', tampered)
+ audio.emit('message', otherSSRC)
+ audio.emit('message', otherPayloadType)
+ audio.emit('message', short)
+ video.emit('message', videoUnderVideoKey)
+ video.emit('message', videoUnderAudioKey)
+ audio.emit('message', accepted)
+ audio.emit('message', replay)
+
+ expect(await end(service, connection, identifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expect(packets).toEqual([
+ talkbackPacket(8),
+ ])
+ expect(delegate.talkbackStarted).toHaveBeenCalledOnce()
+ expect(lines.filter(line => line.includes('drops a talkback datagram'))).toHaveLength(1)
+ expect(lines.filter(line => line.includes('dropped 1 more talkback datagram'))).toHaveLength(1)
+ })
+
+ it('unprotects and drops talkback while the camera\'s Speaker is muted, starting no sink and keeping a started one, writes a packet first seen '
+ + 'unmuted, and refuses one that arrived muted and arrives again as a replay', async () => {
+ let muted = true
+ const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotect')
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness({
+ speakerMuted: () => muted,
+ })
+ const { packets, release, start: startSink } = keepingSink()
+ delegate.talkbackStarted.mockImplementation(startSink)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ const { audio } = accessorySockets(createSocket)
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+ const sent = [1, 2, 3].map(sequence => reference.protect(talkbackPacket(sequence)))
+ const tampered = reference.protect(talkbackPacket(4))
+ const lines = captureDebug('HAP-NodeJS:Camera:MultiTier')
+
+ tampered[20] ^= 0x01
+ unprotect.mockClear()
+
+ // Each datagram is handed over as a copy, since the session unprotects one it reads in its own buffer. A packet that arrived muted can arrive again.
+ audio.emit('message', Buffer.from(sent[0]))
+
+ expect([delegate.talkbackStarted.mock.calls.length, unprotect.mock.calls.length]).toEqual([0, 1])
+
+ audio.emit('message', tampered)
+
+ expect(lines.filter(line => line.includes('drops a talkback datagram'))).toHaveLength(1)
+
+ muted = false
+ audio.emit('message', Buffer.from(sent[0]))
+ audio.emit('message', Buffer.from(sent[1]))
+ muted = true
+ audio.emit('message', Buffer.from(sent[2]))
+
+ expect(packets).toEqual([
+ talkbackPacket(2),
+ ])
+ expect(release).not.toHaveBeenCalled()
+ expect(delegate.talkbackStarted).toHaveBeenCalledOnce()
+ expect(unprotect).toHaveBeenCalledTimes(5)
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expect(release).toHaveBeenCalledOnce()
+ expect(lines.filter(line => line.includes('drops a talkback datagram'))).toHaveLength(1)
+ expect(lines.filter(line => line.includes('dropped 1 more talkback datagram'))).toHaveLength(1)
+ })
+
+ it('follows the controller\'s SRTP index through a mute of more than half the sequence range, writing each packet after it in order to the sink the '
+ + 'first packet started', async () => {
+ let muted = false
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness({
+ speakerMuted: () => muted,
+ })
+ const { packets, start: startSink } = keepingSink()
+ delegate.talkbackStarted.mockImplementation(startSink)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ const { audio } = accessorySockets(createSocket)
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+ // One packet past half the sequence range, which an index estimate from the first packet cannot bridge. A session that read none of the muted
+ // packets would read the next one under the wrong rollover counter.
+ const mutedPackets = 0x8000 + 1
+ const unmuted = [2, 3, 4].map(offset => mutedPackets + offset)
+
+ audio.emit('message', reference.protect(talkbackPacket(1)))
+ muted = true
+
+ for (let sequence = 2; sequence < 2 + mutedPackets; sequence++) {
+ audio.emit('message', reference.protect(talkbackPacket(sequence)))
+ }
+
+ muted = false
+
+ for (const sequence of unmuted) {
+ audio.emit('message', reference.protect(talkbackPacket(sequence)))
+ }
+
+ expect(packets).toEqual([1, ...unmuted].map(sequence => talkbackPacket(sequence)))
+ expect(delegate.talkbackStarted).toHaveBeenCalledOnce()
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ })
+
+ it('declines talkback for a delegate without talkbackStarted, one that answers undefined and one that throws, unprotecting and asking once', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotect')
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { tierDemandStarted } = scriptedTierDelegate()
+ const answering = scriptedTierDelegate()
+ const throwing = scriptedTierDelegate()
+ throwing.talkbackStarted.mockImplementation(() => {
+ throw new Error('The decoder would not start.')
+ })
+
+ const delegates: MultiTierStreamingDelegate[] = [
+ { tierDemandStarted },
+ answering,
+ throwing,
+ ]
+
+ for (const delegate of delegates) {
+ const { service } = harness({ delegate })
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ const { audio } = accessorySockets(createSocket)
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+ unprotect.mockClear()
+
+ audio.emit('message', reference.protect(talkbackPacket(1)))
+ audio.emit('message', reference.protect(talkbackPacket(2)))
+
+ expect(unprotect).toHaveBeenCalledOnce()
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ }
+
+ expect([answering.talkbackStarted.mock.calls.length, throwing.talkbackStarted.mock.calls.length]).toEqual([1, 1])
+ expect(error.mock.calls.filter(([line]) => String(line).startsWith('MultiTierStreamingDelegate failed to start talkback: '))).toHaveLength(1)
+ })
+
+ it('writes synchronously to a sink whose write and whose talker\'s cleanup throw, logging the first failed write, the disposal and a count of the rest, '
+ + 'and answers End', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ // The sink is a decoder class's instance, registered on its talker as it is answered, and its throwing disposal is the talker's cleanup.
+ const sink = {
+ [Symbol.dispose]: vi.fn<() => void>(() => {
+ throw new Error('The decoder would not close.')
+ }),
+ write: vi.fn(() => {
+ throw new Error('The decoder is full.')
+ }),
+ }
+ delegate.talkbackStarted.mockImplementation(talker => talker.use(sink))
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ const { audio } = accessorySockets(createSocket)
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+
+ for (const sequence of [1, 2, 3]) {
+ expect(() => audio.emit('message', reference.protect(talkbackPacket(sequence)))).not.toThrow()
+ expect(sink.write).toHaveBeenCalledTimes(sequence)
+ }
+
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expect(sink[Symbol.dispose]).toHaveBeenCalledOnce()
+ expect(error.mock.calls.map(([line]) => String(line).split(':')[0])).toEqual([
+ 'TalkbackSink failed to write a packet',
+ `MultiTierStreamingDelegate failed to end the talkback of multi-tier session ${answer.sessionIdentifier}`,
+ `TalkbackSink failed 2 more writes before multi-tier session ${answer.sessionIdentifier} ended.`,
+ ])
+ })
+
+ it('ends a sink once, after its last write, at End, at its connection\'s close and at destroy, and writes it nothing after', async () => {
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, management, service } = harness()
+ const sinks: KeepingSink[] = []
+ delegate.talkbackStarted.mockImplementation((talker) => {
+ const kept = keepingSink()
+ sinks.push(kept)
+
+ return kept.start(talker)
+ })
+ const from = await endpoint()
+ const ending = buildEmitterConnection()
+ const closing = buildEmitterConnection()
+ const destroyed = buildEmitterConnection()
+ const sessions: { answer: Prepared, talk: (sequence: number) => boolean }[] = []
+
+ for (const connection of [ending, closing, destroyed]) {
+ const answer = await streaming(service, connection, from)
+ const { audio } = accessorySockets(createSocket)
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+ const talk = (sequence: number): boolean => audio.emit('message', reference.protect(talkbackPacket(sequence)))
+
+ talk(1)
+ talk(2)
+ sessions.push({ answer, talk })
+ }
+
+ expect(await end(service, ending, sessions[0].answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ closing.emit('closed')
+ await settle()
+ await management.destroy()
+
+ for (const [index, { release, sink }] of sinks.entries()) {
+ sessions[index].talk(3)
+
+ expect(sink.write).toHaveBeenCalledTimes(2)
+ expect(release).toHaveBeenCalledOnce()
+ expect(release.mock.invocationCallOrder[0]).toBeGreaterThan(Math.max(...sink.write.mock.invocationCallOrder))
+ }
+
+ expect(sinks).toHaveLength(sessions.length)
+ })
+
+ it('gives each streaming session a sink of its own, written only its own controller\'s talkback', async () => {
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ const sinks: KeepingSink[] = []
+ delegate.talkbackStarted.mockImplementation(() => {
+ const kept = keepingSink()
+ sinks.push(kept)
+
+ return kept.sink
+ })
+ const from = await endpoint()
+ const first = await streaming(service, buildEmitterConnection(), from)
+ const firstSockets = accessorySockets(createSocket)
+ const second = await streaming(service, buildEmitterConnection(), from)
+ const secondSockets = accessorySockets(createSocket)
+ const firstReference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+ const secondReference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+
+ firstSockets.audio.emit('message', firstReference.protect(talkbackPacket(1)))
+ secondSockets.audio.emit('message', secondReference.protect(talkbackPacket(10)))
+ firstSockets.audio.emit('message', firstReference.protect(talkbackPacket(2)))
+
+ expect(first.sessionIdentifier).not.toBe(second.sessionIdentifier)
+ expect(delegate.talkbackStarted).toHaveBeenCalledTimes(2)
+ expect(sinks.map(({ packets }) => packets)).toEqual([
+ [
+ talkbackPacket(1),
+ talkbackPacket(2),
+ ],
+ [
+ talkbackPacket(10),
+ ],
+ ])
+ })
+
+ it('neither arms nor restarts the liveness window with talkback: a session silent in RTCP after one report ends and one that only talks streams on', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ fakeTimeoutSignals()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ const sinks: KeepingSink[] = []
+ delegate.talkbackStarted.mockImplementation((talker) => {
+ const kept = keepingSink()
+ sinks.push(kept)
+
+ return kept.start(talker)
+ })
+ const from = await endpoint()
+ const reporting = buildEmitterConnection()
+ const talking = buildEmitterConnection()
+ const reported = await streaming(service, reporting, from)
+ const reportedSockets = accessorySockets(createSocket)
+ const talked = await streaming(service, talking, from)
+ const talkedSockets = accessorySockets(createSocket)
+ const reportedReference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+ const talkedReference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+
+ // The sessions' one tier hands over pictures through each wait, which keeps its demand inside its silence bounds and leaves the liveness window
+ // alone to end a session.
+ reportedSockets.audio.emit('message', reportedReference.protectRTCP(Buffer.from(RECEIVER_REPORT, 'hex')))
+ await keepStreaming([
+ streamOf(delegate),
+ ], 20000, { advance: advanceAsync })
+ reportedSockets.audio.emit('message', reportedReference.protect(talkbackPacket(1)))
+ talkedSockets.audio.emit('message', talkedReference.protect(talkbackPacket(1)))
+ await keepStreaming([
+ streamOf(delegate),
+ ], 5000, { advance: advanceAsync, from: 20000000 })
+
+ expect(await end(service, reporting, reported.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+
+ await keepStreaming([
+ streamOf(delegate),
+ ], 25000, { advance: advanceAsync, from: 25000000 })
+
+ expect(await end(service, talking, talked.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expect(sinks).toHaveLength(2)
+ expect(sinks.map(({ release }) => release.mock.calls.length)).toEqual([1, 1])
+ })
+
+ it('starts no talkback in an exit, ends at once a sink whose delegate ended the session, and ends inside its write a sink that fails its stream', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotect')
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, management, service } = harness()
+ const from = await endpoint()
+
+ // A datagram emitted in the turn the session's exit begins, while its listeners still stand.
+ const exiting = await streaming(service, buildEmitterConnection(), from)
+ const exitingSockets = accessorySockets(createSocket)
+ const exited = management.endSession(exiting.sessionIdentifier)
+ exitingSockets.audio.emit('message', new ReferenceSRTP(CONTROLLER_KEYS.audio).protect(talkbackPacket(1)))
+ await exited
+
+ expect(unprotect).not.toHaveBeenCalled()
+ expect(delegate.talkbackStarted).not.toHaveBeenCalled()
+
+ // A delegate whose call ends the session before it answers a sink.
+ const ended = await streaming(service, buildEmitterConnection(), from)
+ const endedSockets = accessorySockets(createSocket)
+ const endedSink = keepingSink()
+ delegate.talkbackStarted.mockImplementationOnce((talker) => {
+ void management.endSession(ended.sessionIdentifier)
+
+ return endedSink.start(talker)
+ })
+
+ expect(() => endedSockets.audio.emit('message', new ReferenceSRTP(CONTROLLER_KEYS.audio).protect(talkbackPacket(1)))).not.toThrow()
+ expect(endedSink.release).toHaveBeenCalledOnce()
+ expect(endedSink.sink.write).not.toHaveBeenCalled()
+
+ // A sink whose write fails its tier's stream, which ends the session inside that write.
+ const failingConnection = buildEmitterConnection()
+ const failing = await streaming(service, failingConnection, from)
+ const failingSockets = accessorySockets(createSocket)
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+ const calls: string[] = []
+ const failingSink = {
+ write: vi.fn(() => {
+ calls.push('write')
+ streamOf(delegate).fail('The decoder failed.')
+ calls.push('write returns')
+ }),
+ }
+ delegate.talkbackStarted.mockImplementationOnce((talker) => {
+ talker.defer(() => calls.push('release'))
+
+ return failingSink
+ })
+
+ failingSockets.audio.emit('message', reference.protect(talkbackPacket(1)))
+ failingSockets.audio.emit('message', reference.protect(talkbackPacket(2)))
+ await settle()
+
+ expect(await end(service, failingConnection, failing.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect(calls).toEqual(['write', 'release', 'write returns'])
+ })
+
+ it('counts each rejection of an async write as a failed write, logging the first and a count of the rest, and answers End with none left unhandled', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ let writes = 0
+ // A plain async write rather than a mock, because a mock's own tracking of the promise it returns would handle the rejection the session must handle.
+ const sink: TalkbackSink = {
+ write: async () => {
+ writes++
+ throw new Error('The decoder is full.')
+ },
+ }
+ delegate.talkbackStarted.mockReturnValue(sink)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ const { audio } = accessorySockets(createSocket)
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+ // The listener collects each rejection no handler takes during the row, any of which would end a Homebridge process.
+ const unhandled: unknown[] = []
+ const collect = (reason: unknown): void => {
+ unhandled.push(reason)
+ }
+
+ process.on('unhandledRejection', collect)
+
+ try {
+ audio.emit('message', reference.protect(talkbackPacket(1)))
+ audio.emit('message', reference.protect(talkbackPacket(2)))
+ await settle()
+
+ expect(writes).toBe(2)
+ expect(error.mock.calls.map(([line]) => String(line).split(':')[0])).toEqual(['TalkbackSink failed to write a packet'])
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ await settle()
+ } finally {
+ process.off('unhandledRejection', collect)
+ }
+
+ expect(error.mock.calls.map(([line]) => String(line).split(':')[0])).toEqual([
+ 'TalkbackSink failed to write a packet',
+ `TalkbackSink failed 1 more write before multi-tier session ${answer.sessionIdentifier} ended.`,
+ ])
+ expect(unhandled).toEqual([])
+ })
+
+ it('declines an answer whose then cannot be read, throwing nothing from the socket, logging one line and neither asking again nor writing it', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { sink, packets } = keepingSink()
+ const { delegate, service } = harness()
+ const dispose = vi.fn<() => void>()
+ // A sink whose then getter throws, which means the read that asks whether the answer is a promise is the read that throws.
+ const unreadable = {
+ [Symbol.dispose]: dispose,
+ write: sink.write,
+ get then(): never {
+ throw new Error('The answer cannot be read.')
+ },
+ }
+ delegate.talkbackStarted.mockReturnValue(unreadable as unknown as TalkbackSink)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ const { audio } = accessorySockets(createSocket)
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+
+ expect(() => audio.emit('message', reference.protect(talkbackPacket(1)))).not.toThrow()
+ expect(() => audio.emit('message', reference.protect(talkbackPacket(2)))).not.toThrow()
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+
+ expect(delegate.talkbackStarted).toHaveBeenCalledOnce()
+ expect(packets).toEqual([])
+ expect(sink.write).not.toHaveBeenCalled()
+ expect(dispose).not.toHaveBeenCalled()
+ expect(error.mock.calls.map(([line]) => String(line).split(':')[0])).toEqual(['MultiTierStreamingDelegate failed to start talkback'])
+ })
+
+ it('counts the rejection of a thenable a write returns that is no promise as a failed write, logging the first and a count of the rest', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const { delegate, service } = harness()
+ // Every write answers a thenable that rejects as its then is called and is no Promise, which means only a read of then reaches its rejection.
+ const rejecting = {
+ then: (_resolved: unknown, rejected: (reason: unknown) => void) => rejected(new Error('The decoder is full.')),
+ }
+ const sink: TalkbackSink = {
+ write: (() => rejecting) as unknown as TalkbackSink['write'],
+ }
+ delegate.talkbackStarted.mockReturnValue(sink)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const answer = await streaming(service, connection, from)
+ const { audio } = accessorySockets(createSocket)
+ const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio)
+
+ audio.emit('message', reference.protect(talkbackPacket(1)))
+ audio.emit('message', reference.protect(talkbackPacket(2)))
+
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expect(error.mock.calls.map(([line]) => String(line).split(':')[0])).toEqual([
+ 'TalkbackSink failed to write a packet',
+ `TalkbackSink failed 1 more write before multi-tier session ${answer.sessionIdentifier} ended.`,
+ ])
+ })
+ })
+
+ describe('owner surface', () => {
+ it('serializes, restores and resets streaming enabled, ends every session at a reset or destroy run twice, and ignores an unknown session', async () => {
+ const { management, service } = harness()
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+
+ expect(management.serialize()).toEqual({ streamingEnabled: true })
+
+ management.deserialize({ streamingEnabled: false })
+
+ expect(management.serialize()).toEqual({ streamingEnabled: false })
+
+ management.deserialize({ streamingEnabled: 'on' } as unknown as { streamingEnabled: boolean })
+
+ expect(management.serialize()).toEqual({ streamingEnabled: false })
+
+ management.handleFactoryReset()
+ const answer = await streaming(service, connection, from)
+ management.handleFactoryReset()
+ management.handleFactoryReset()
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(management.serialize()).toEqual({ streamingEnabled: true })
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ await expect(management.endSession(UNKNOWN_SESSION)).resolves.toBeUndefined()
+
+ await streaming(service, connection, from)
+ await Promise.all([
+ management.destroy(),
+ management.destroy(),
+ ])
+ await until(() => udpSockets() === base)
+
+ const sessionIdentifier = crypto.randomUUID()
+ expect(await prepare(service, connection, from, sessionIdentifier)).toEqual({ status: SetupEndpointsStatus.ERROR, sessionIdentifier })
+ })
+
+ it('reports each change of streaming enabled with the sensor, views at home, the value and the reason', async () => {
+ const { changes, management, service } = harness()
+ const streamingEnabled = service.getCharacteristic(Characteristic.StreamingEnabled)
+
+ await streamingEnabled.handleSetRequest(false, buildEmitterConnection())
+ streamingEnabled.updateValue(true)
+ management.deserialize({ streamingEnabled: false })
+ management.handleFactoryReset()
+
+ expect(changes).toEqual([
+ {
+ reason: 'write',
+ sensorUUID: SENSOR_UUID.toLowerCase(),
+ value: false,
+ where: 'home',
+ },
+ {
+ reason: 'update',
+ sensorUUID: SENSOR_UUID.toLowerCase(),
+ value: true,
+ where: 'home',
+ },
+ {
+ reason: 'restore',
+ sensorUUID: SENSOR_UUID.toLowerCase(),
+ value: false,
+ where: 'home',
+ },
+ {
+ reason: 'reset',
+ sensorUUID: SENSOR_UUID.toLowerCase(),
+ value: true,
+ where: 'home',
+ },
+ ])
+ })
+ })
+
+ describe('over paired connections', () => {
+ const serverUsername = 'CA:FE:00:00:00:03'
+ const clientUsername = 'CA:FE:00:00:00:04'
+
+ let accessory: Accessory
+ let accessoryInfo: AccessoryInfo
+ let clients: HAPHTTPClient[]
+ let clientInfo: { username: string, privateKey: Buffer, publicKey: Buffer }
+
+ beforeEach(() => {
+ accessoryInfo = AccessoryInfo.create(serverUsername)
+ // @ts-expect-error: private access
+ accessoryInfo.setupID = Accessory._generateSetupID()
+ accessoryInfo.displayName = 'Camera'
+ accessoryInfo.category = Categories.IP_CAMERA
+ accessoryInfo.pincode = '031-45-154'
+ accessoryInfo.save = vi.fn()
+
+ const clientKeyPair = tweetnacl.sign.keyPair()
+ clientInfo = {
+ username: clientUsername,
+ privateKey: Buffer.from(clientKeyPair.secretKey),
+ publicKey: Buffer.from(clientKeyPair.publicKey),
+ }
+ accessoryInfo.addPairedClient(clientUsername, clientInfo.publicKey, PermissionTypes.ADMIN)
+
+ // The published accessory loads the paired record above in place of a stored one, as the legacy stream's paired rows do.
+ vi.spyOn(AccessoryInfo, 'load').mockReturnValue(accessoryInfo)
+ accessory = new Accessory('Camera', uuid.generate('multi-tier stream management over paired connections'))
+ clients = []
+ })
+
+ afterEach(async () => {
+ for (const client of clients) {
+ client.destroy()
+ }
+ await accessory.destroy()
+ })
+
+ it('prepares, starts, streams to and ends a session for a paired controller, its answer read on its connection and its start in the write response', async () => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance'],
+ })
+ fakeTimeoutSignals()
+ const { delegate, service } = harness()
+ accessory.addService(service)
+ const listening: Promise<[port: number, hostname: string]> = awaitEventOnce(accessory, AccessoryEventTypes.LISTENING)
+ await accessory.publish({
+ username: serverUsername,
+ pincode: accessoryInfo.pincode,
+ category: Categories.IP_CAMERA,
+ advertiser: MDNSAdvertiser.BONJOUR,
+ port: 0,
+ })
+ const [port] = await listening
+
+ const client = new HAPHTTPClient('127.0.0.1', port)
+ await client.connect()
+ clients.push(client)
+ client.enableEncryption(await new PairVerifyClient(client).sendPairVerify({
+ username: serverUsername,
+ publicKey: Buffer.from(accessoryInfo.signPk),
+ }, clientInfo))
+
+ const from = await endpoint()
+ const sessionIdentifier = crypto.randomUUID()
+ const setupEndpoints = { aid: accessory.aid!, iid: service.getCharacteristic(Characteristic.SetupEndpoints).iid! }
+ const streamingControl = { aid: accessory.aid!, iid: service.getCharacteristic(Characteristic.RTPStreamingControl).iid! }
+ const command = async (request: RTPStreamingControlRequest): Promise => {
+ const response = await client.sendCharacteristicWrite({
+ characteristics: [
+ {
+ ...streamingControl,
+ value: encodeRTPStreamingControlRequest(request),
+ r: true,
+ },
+ ],
+ })
+
+ return decodeRTPStreamingControlResponse((response.body!.characteristics[0] as { value: string }).value)
+ }
+
+ await client.sendCharacteristicWrite({
+ characteristics: [
+ {
+ ...setupEndpoints,
+ value: setupRequest(from, sessionIdentifier),
+ },
+ ],
+ })
+ const [read] = (await client.sendCharacteristicRead([setupEndpoints])).body.characteristics
+ const answer = decodeSetupEndpointsResponse((read as { value: string }).value) as Prepared
+
+ expect(answer.status).toBe(SetupEndpointsStatus.SUCCESS)
+ expect(await command({
+ sessionIdentifier,
+ command: RTPStreamingCommand.START,
+ videoTier: 2,
+ videoSSRC: CONTROLLER_SSRCS.video,
+ audioTier: 1,
+ audioSSRC: CONTROLLER_SSRCS.audio,
+ })).toEqual({ sessionIdentifier, status: RTPStreamingStatus.SUCCESS })
+
+ // One keyframe of a slice of 1000 octets and its parameter sets, which goes as one aggregation packet at either family's size, the slice its last unit.
+ const unit = nalUnit(SLICE, 1000)
+ writeTierFrame(streamOf(delegate, 2), 'video', keyframeWithSets({
+ data: tierFrameData([unit]),
+ time: 0,
+ }))
+ await vi.advanceTimersByTimeAsync(0)
+ await until(() => from.received.video.length === 1)
+
+ const plain = new ReferenceSRTP(answer.videoSRTPParameters).unprotect(from.received.video[0])!
+
+ expect(plain.readUInt32BE(8)).toBe(answer.videoSSRC)
+ expect(plain.subarray(12)).toHaveLength(setsAggregated(1000))
+ expect(plain.subarray(plain.length - unit.length).equals(unit)).toBe(true)
+ expect(await command({ sessionIdentifier, command: RTPStreamingCommand.END })).toEqual({ sessionIdentifier, status: RTPStreamingStatus.SUCCESS })
+ })
+ })
+
+ describe('camera controller wiring', () => {
+ const GLOBAL_KEY = 'cameraCapabilities:globalOperatingMode'
+ const CAPABILITIES_KEY = 'cameraCapabilities:cameraCapabilities'
+ // The HKSV3 recording management's keys, the last of the block's.
+ const RECORDING_KEYS = [
+ 'cameraCapabilities:cameraBufferManagement',
+ 'cameraCapabilities:cameraKeyManagement',
+ 'cameraCapabilities:cameraClientCertificateManagement',
+ ]
+ const SECOND_SENSOR = videoSensor('B0000002-0000-4000-8000-000000000002', { intent: CameraSensorIntent.PACKAGE })
+ const SECOND_KEY = 'cameraCapabilities:multiTierStream:b0000002-0000-4000-8000-000000000002'
+ const REMOVED_SENSOR = {
+ ...SECOND_SENSOR,
+ uuid: 'C0000003-0000-4000-8000-000000000003',
+ }
+ const REMOVED_KEY = 'cameraCapabilities:multiTierStream:c0000003-0000-4000-8000-000000000003'
+ // Each sensor's WebRTC stream service key, which every camera with the block holds after the multi-tier keys.
+ const WEBRTC_KEY = 'cameraCapabilities:webRTCStream:a1b2c3d4-0000-4000-8000-000000000001'
+ const SECOND_WEBRTC_KEY = 'cameraCapabilities:webRTCStream:b0000002-0000-4000-8000-000000000002'
+
+ // The cameras a row builds, removed after it. The global hook's wait for the sockets covers their sessions too.
+ const cameras: CameraController[] = []
+
+ afterEach(() => {
+ for (const camera of cameras.splice(0)) {
+ camera.handleControllerRemoved()
+ }
+ })
+
+ // A camera with the camera capabilities block over the given sensors and streaming options, by default the fixture's with its no-op delegate, which
+ // records from its camera buffer.
+ function wiredCamera(sensors: readonly CameraVideoSensor[] = [SENSOR, SECOND_SENSOR], streamingOptions = idleStreaming()): CameraController {
+ const camera = new CameraController(capabilitiesCameraOptions({
+ videoSensors: [...sensors],
+ streaming: streamingOptions,
+ }))
+
+ cameras.push(camera)
+ return camera
+ }
+
+ // A wired camera's services, constructed and configured as a first run of the accessory configures them, and the camera handed a published context.
+ function configured(camera: CameraController): CameraControllerServiceMap {
+ const map = camera.constructServices()
+ camera.configureServices()
+ handPublishedContext(camera)
+
+ return map
+ }
+
+ function multiTierServiceOf(map: CameraControllerServiceMap, key: string): CameraMultiTierRTPStreamManagement {
+ return map[key] as CameraMultiTierRTPStreamManagement
+ }
+
+ function prefixedKeys(map: CameraControllerServiceMap): string[] {
+ return Object.keys(map).filter(key => key.startsWith('cameraCapabilities:') && map[key] !== undefined)
+ }
+
+ // The tier table a wired camera built a video sensor's management with.
+ function tableOf(camera: CameraController, sensorUUID: string): TierTable {
+ // @ts-expect-error: private access
+ return camera.multiTierStreamManagements.get(sensorUUID.toLowerCase()).table
+ }
+
+ it('gives each video sensor\'s management a tier table of its own, built for that sensor', () => {
+ const camera = wiredCamera()
+ const map = configured(camera)
+ const tables = [SENSOR, SECOND_SENSOR].map(sensor => tableOf(camera, sensor.uuid))
+
+ expect(tables[0]).not.toBe(tables[1])
+ expect(tables.map(table => table.sensorUUID)).toEqual([SENSOR, SECOND_SENSOR].map(sensor => sensor.uuid.toLowerCase()))
+ expect(tables.map(table => MultiTierStreamManagement.serviceKey(table.streamTiers.sensorUUID))).toEqual([SERVICE_KEY, SECOND_KEY])
+ expect([SERVICE_KEY, SECOND_KEY].map(key => multiTierServiceOf(map, key).getCharacteristic(Characteristic.SupportedVideoStreamTiers).value))
+ .toEqual(tables.map(table => encodeSupportedVideoStreamTiers(table.streamTiers.videoStreamTiers)))
+ })
+
+ it('answers a sensor\'s best tier: the most pixels, the higher target bitrate between two of one size, and the earlier advertised between two of both',
+ () => {
+ // The best tier's identifier among tiers of the widths and bitrates given, each at 16 by 9 and identified by its place from 1.
+ const bestOf = (...tiers: (readonly [number, number])[]): number | undefined => bestStreamTier(tiers.map(([width, targetAverageBitrate], index) => ({
+ ...TIERS.videoStreamTiers.tiers[0],
+ height: width * 9 / 16,
+ identifier: index + 1,
+ targetAverageBitrate,
+ width,
+ })))?.identifier
+
+ expect(bestOf([1280, 768], [1920, 1000], [1920, 1700], [640, 180])).toBe(3)
+ expect(bestOf([1920, 1700], [1920, 1700])).toBe(1)
+ expect(bestOf([640, 180], [1280, 768])).toBe(2)
+ expect(bestOf()).toBeUndefined()
+ })
+
+ it('holds a sensor\'s tiers in their advertised order, each carrying the very stream tier object the sensor\'s WebRTC service is handed', () => {
+ const sensors = [SENSOR, SECOND_SENSOR]
+ const camera = new CameraController(capabilitiesCameraOptions({
+ videoSensors: sensors,
+ streaming: idleStreaming(),
+ webrtc: webRTCStreamingOptions(),
+ }))
+ cameras.push(camera)
+ const handed = vi.spyOn(camera as unknown as { webRTCStreamManagementOptions: () => WebRTCStreamManagementOptions[] }, 'webRTCStreamManagementOptions')
+
+ configured(camera)
+
+ const webRTCOptions = handed.mock.results.at(-1)!.value as WebRTCStreamManagementOptions[]
+
+ expect(webRTCOptions.map(options => options.sensorUUID)).toEqual(sensors.map(sensor => sensor.uuid.toLowerCase()))
+
+ for (const { audioStreamTiers, sensorUUID, videoStreamTiers } of webRTCOptions) {
+ const table = tableOf(camera, sensorUUID)
+ const videoTiers = Array.from(table.videoTiers.values())
+
+ expect(Array.from(table.videoTiers.keys())).toEqual(videoStreamTiers.tiers.map(tier => tier.identifier))
+ expect(videoTiers).toHaveLength(videoStreamTiers.tiers.length)
+
+ for (const [index, tier] of videoTiers.entries()) {
+ expect(tier.advertised).toBe(videoStreamTiers.tiers[index])
+ }
+
+ expect(table.audioTier.advertised).toBe(audioStreamTiers.tiers[0])
+ }
+ })
+
+ it('constructs one multi-tier stream service per video sensor under its key after the capabilities key, and none without the block', () => {
+ const map = wiredCamera().constructServices()
+
+ expect(prefixedKeys(map)).toEqual([
+ CAPABILITIES_KEY,
+ GLOBAL_KEY,
+ SERVICE_KEY,
+ SECOND_KEY,
+ WEBRTC_KEY,
+ SECOND_WEBRTC_KEY,
+ ...RECORDING_KEYS,
+ ])
+ expect(map[SERVICE_KEY]!.UUID).toBe(Service.CameraMultiTierRTPStreamManagement.UUID)
+ expect(map[SERVICE_KEY]!.subtype).toBe(SENSOR_UUID.toLowerCase())
+ expect(prefixedKeys(new CameraController(createCameraControllerOptions()).constructServices())).toEqual([])
+ })
+
+ it('keys each sensor\'s service and advertises its configuration in the plugin\'s order, the first Primary, for a camera given its package sensor first',
+ () => {
+ const map = wiredCamera([SECOND_SENSOR, SENSOR]).constructServices()
+ const decoded = decodeCameraCapabilities(map[CAPABILITIES_KEY]!.getCharacteristic(Characteristic.CameraCapabilitiesData).value as string)
+
+ expect(prefixedKeys(map)).toEqual([
+ CAPABILITIES_KEY,
+ GLOBAL_KEY,
+ SECOND_KEY,
+ SERVICE_KEY,
+ SECOND_WEBRTC_KEY,
+ WEBRTC_KEY,
+ ...RECORDING_KEYS,
+ ])
+ expect(decoded.cameraSensors.map(({ sensorIntent, sensorType, sensorUUID }) => ({ sensorIntent, sensorType, sensorUUID }))).toEqual([
+ {
+ sensorIntent: CameraSensorIntent.PACKAGE,
+ sensorType: CameraSensorType.PRIMARY,
+ sensorUUID: SECOND_SENSOR.uuid.toLowerCase(),
+ },
+ {
+ sensorIntent: CameraSensorIntent.MAIN,
+ sensorType: CameraSensorType.GENERIC,
+ sensorUUID: SENSOR_UUID.toLowerCase(),
+ },
+ ])
+ })
+
+ it('constructs every service in the order the accessory adds them, the block first, and links each sensor after the data stream service', () => {
+ const map = wiredCamera().constructServices()
+
+ expect(Object.keys(map)).toEqual([
+ CAPABILITIES_KEY,
+ GLOBAL_KEY,
+ SERVICE_KEY,
+ SECOND_KEY,
+ WEBRTC_KEY,
+ SECOND_WEBRTC_KEY,
+ ...RECORDING_KEYS,
+ 'microphone',
+ 'speaker',
+ 'motionService',
+ 'occupancyService',
+ 'cameraEventRecordingManagement',
+ 'cameraOperatingMode',
+ 'dataStreamTransportManagement',
+ ])
+ expect(map.speaker).toBeUndefined()
+ expect(map.cameraEventRecordingManagement!.linkedServices).toEqual([
+ map.dataStreamTransportManagement,
+ map.motionService,
+ map.occupancyService,
+ ])
+ })
+
+ it('adopts each saved sensor service, creates a missing one and deletes a removed sensor\'s at a restore, keeping every claimed key', () => {
+ const saved = savedMapOf(wiredCamera([SENSOR, REMOVED_SENSOR]))
+ const adopted = saved[SERVICE_KEY]
+
+ const restored = wiredCamera().initWithServices(saved)!
+
+ expect(restored[SERVICE_KEY]).toBe(adopted)
+ expect(restored[SECOND_KEY]!.UUID).toBe(Service.CameraMultiTierRTPStreamManagement.UUID)
+ expect(restored[REMOVED_KEY]).toBeUndefined()
+ expect(prefixedKeys(restored)).toEqual([
+ CAPABILITIES_KEY,
+ GLOBAL_KEY,
+ SERVICE_KEY,
+ SECOND_KEY,
+ WEBRTC_KEY,
+ SECOND_WEBRTC_KEY,
+ ...RECORDING_KEYS,
+ ])
+ })
+
+ it('builds each configuration from the streaming options it validated, whatever the plugin changes in its options object afterward', async () => {
+ const streamingOptions = idleStreaming()
+ const sensors = [
+ videoSensor(SENSOR_UUID),
+ SECOND_SENSOR,
+ ]
+ const camera = wiredCamera(sensors, streamingOptions)
+ configured(camera)
+ const videoStreamTiers = encodeSupportedVideoStreamTiers(TIERS.videoStreamTiers)
+
+ // The plugin drops the second sensor, changes the first's tier in place and sets a session bound validation refuses, then reconfigures.
+ sensors.pop()
+ sensors[0].tiers[0].bitrate = 1000
+ streamingOptions.maxSessions = 0
+ camera.handleControllerRemoved()
+
+ const map = configured(camera)
+ const service = multiTierServiceOf(map, SERVICE_KEY)
+ const from = await endpoint()
+
+ expect(prefixedKeys(map)).toEqual([
+ CAPABILITIES_KEY,
+ GLOBAL_KEY,
+ SERVICE_KEY,
+ SECOND_KEY,
+ WEBRTC_KEY,
+ SECOND_WEBRTC_KEY,
+ ...RECORDING_KEYS,
+ ])
+ expect(service.getCharacteristic(Characteristic.SupportedVideoStreamTiers).value).toBe(videoStreamTiers)
+ expect(await prepare(service, buildEmitterConnection(), from, crypto.randomUUID())).toMatchObject({ status: SetupEndpointsStatus.SUCCESS })
+ })
+
+ it('serializes and restores each sensor\'s slice, carries a removed sensor\'s and a record without the block, and drops it at a reset', () => {
+ const SENSOR_SLICE = SENSOR_UUID.toLowerCase()
+ const SECOND_SLICE = SECOND_SENSOR.uuid.toLowerCase()
+
+ expect(wiredCamera().serialize()!.multiTierStreamManagements).toBeUndefined()
+
+ const camera = wiredCamera()
+ configured(camera)
+
+ expect(camera.serialize()!.multiTierStreamManagements).toEqual({
+ [SENSOR_SLICE]: { streamingEnabled: true },
+ [SECOND_SLICE]: { streamingEnabled: true },
+ })
+
+ const restored = wiredCamera([SENSOR])
+ const map = configured(restored)
+ restored.deserialize({
+ streamManagements: [],
+ multiTierStreamManagements: {
+ [SENSOR_SLICE]: { streamingEnabled: false },
+ [SECOND_SLICE]: { streamingEnabled: false },
+ },
+ })
+
+ expect(multiTierServiceOf(map, SERVICE_KEY).getCharacteristic(Characteristic.StreamingEnabled).value).toBe(false)
+ expect(restored.serialize()!.multiTierStreamManagements).toEqual({
+ [SENSOR_SLICE]: { streamingEnabled: false },
+ [SECOND_SLICE]: { streamingEnabled: false },
+ })
+
+ restored.handleFactoryReset()
+
+ expect(restored.serialize()!.multiTierStreamManagements).toEqual({
+ [SENSOR_SLICE]: { streamingEnabled: true },
+ })
+
+ const plain = new CameraController(createCameraControllerOptions())
+ const record = {
+ [SECOND_SLICE]: { streamingEnabled: false },
+ }
+ plain.deserialize({
+ streamManagements: [],
+ multiTierStreamManagements: record,
+ })
+
+ expect(plain.serialize()!.multiTierStreamManagements).toEqual(record)
+
+ plain.handleFactoryReset()
+
+ expect(plain.serialize()!.multiTierStreamManagements).toBeUndefined()
+
+ // A record that is no plain object, or a slice that is none, restores nothing and throws nothing.
+ expect(() => restored.deserialize({
+ streamManagements: [],
+ multiTierStreamManagements: [] as unknown as Record,
+ })).not.toThrow()
+ expect(() => restored.deserialize({
+ streamManagements: [],
+ multiTierStreamManagements: { [SENSOR_SLICE]: null } as unknown as Record,
+ })).not.toThrow()
+ expect(restored.serialize()!.multiTierStreamManagements).toEqual({
+ [SENSOR_SLICE]: { streamingEnabled: true },
+ })
+ })
+
+ it('ends every multi-tier service\'s sessions and turns its status active off at camera off, and one service\'s alone at its streaming enabled', async () => {
+ const map = configured(wiredCamera())
+ const first = multiTierServiceOf(map, SERVICE_KEY)
+ const second = multiTierServiceOf(map, SECOND_KEY)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const firstAnswer = await streaming(first, connection, from)
+ const secondAnswer = await streaming(second, connection, from)
+
+ second.updateCharacteristic(Characteristic.StreamingEnabled, false)
+ await settle()
+ await until(() => udpSockets() === base + 2)
+
+ expect(first.getCharacteristic(Characteristic.StatusActive).value).toBe(true)
+ expect(second.getCharacteristic(Characteristic.StatusActive).value).toBe(false)
+ expect(await end(second, connection, secondAnswer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+
+ map[GLOBAL_KEY]!.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(first.getCharacteristic(Characteristic.StatusActive).value).toBe(false)
+ expect(await end(first, connection, firstAnswer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ })
+
+ it.each([
+ {
+ back: (camera: CameraController): void => camera.updateSourceState('available'),
+ leave: (camera: CameraController): void => camera.updateSourceState('away'),
+ leaving: 'its source stated away',
+ },
+ {
+ back: (camera: CameraController): void => handPublishedContext(camera),
+ leave: (camera: CameraController): void => camera.handleAccessoryContext({
+ accessoryInformation: new Service.AccessoryInformation('Camera') as AccessoryInformation,
+ accessoryUUID: NUMBERED_ACCESSORY_UUID,
+ published: false,
+ }),
+ leaving: 'its accessory not published',
+ },
+ ])('fails a setup endpoints write with the communication failure while the camera is out of service, $leaving, binding no socket and moving no '
+ + 'status active, answers error while it is switched off as well, and success once it is back and switched on', async ({ back, leave }) => {
+ const camera = wiredCamera()
+ const map = configured(camera)
+ const service = multiTierServiceOf(map, SERVICE_KEY)
+ const statusActive = service.getCharacteristic(Characteristic.StatusActive)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const createSocket = vi.spyOn(dgram, 'createSocket')
+ const moves: unknown[] = []
+
+ statusActive.on(CharacteristicEventTypes.CHANGE, ({ newValue }) => moves.push(newValue))
+ leave(camera)
+
+ await expect(writeSetup(service, connection, from)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ await expect(readSetupEndpoints(service, connection)).resolves.toBe('AgEC')
+ await expect(statusActive.handleGetRequest()).resolves.toBe(true)
+ expect(createSocket).not.toHaveBeenCalled()
+ expect(moves).toEqual([])
+
+ const switchedOff = crypto.randomUUID()
+
+ map[GLOBAL_KEY]!.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+
+ expect(await prepare(service, connection, from, switchedOff)).toEqual({ status: SetupEndpointsStatus.ERROR, sessionIdentifier: switchedOff })
+
+ back(camera)
+ map[GLOBAL_KEY]!.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON)
+
+ expect(await prepare(service, connection, from, crypto.randomUUID())).toMatchObject({ status: SetupEndpointsStatus.SUCCESS })
+ })
+
+ it('fails a setup endpoints write with the communication failure for a camera stated away while its sockets bind, leaving no socket open', async () => {
+ const camera = wiredCamera()
+ const service = multiTierServiceOf(configured(camera), SERVICE_KEY)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const localAddress = connection.getLocalAddress.bind(connection)
+
+ // The camera leaves service after the write's first check, as its sockets are about to bind.
+ vi.spyOn(connection, 'getLocalAddress').mockImplementation((addressVersion) => {
+ camera.updateSourceState('away')
+
+ return localAddress(addressVersion)
+ })
+
+ await expect(writeSetup(service, connection, from)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ await until(() => udpSockets() === base)
+ })
+
+ it('publishes one debug event of a setup endpoints write failed while the camera is out of service and no answer\'s, and neither for one refused '
+ + 'while it is switched off as well', async () => {
+ const camera = wiredCamera()
+ const map = configured(camera)
+ const service = multiTierServiceOf(map, SERVICE_KEY)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const events = captureDebugEvents('HAP-NodeJS:Camera:MultiTier')
+
+ camera.updateSourceState('away')
+ await expect(writeSetup(service, connection, from)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+
+ const failed = events.splice(0)
+
+ map[GLOBAL_KEY]!.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ await prepare(service, connection, from, crypto.randomUUID())
+
+ expect(failed).toEqual([
+ {
+ accessoryUUID: NUMBERED_ACCESSORY_UUID,
+ kind: 'setup-out-of-service',
+ sentence: 'Setup Endpoints fails with the communication failure while the camera is out of service.',
+ },
+ ])
+ expect(events.map(({ kind }) => kind)).toEqual(['setup-refused', 'write-answered'])
+ })
+
+ it('ends every session and withdraws nothing at a user\'s switch-off of a published camera, the pending start of its kept tier left pending with its '
+ + 'signal unaborted until it settles', async () => {
+ const delegate = scriptedTierDelegate()
+ const pending = pendingStart(delegate)
+ const camera = wiredCamera([
+ {
+ ...SENSOR,
+ tiers: SENSOR.tiers.map(tier => ({ ...tier, keepRunning: tier.id === 3 })),
+ },
+ ], { delegate })
+ const map = configured(camera)
+ const service = multiTierServiceOf(map, SERVICE_KEY)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const answer = await streaming(service, connection, from)
+ const kept = streamOf(delegate, 3)
+ const withdraw = vi.spyOn(TierTable.prototype, 'withdraw')
+
+ map[GLOBAL_KEY]!.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ expect([
+ withdraw.mock.calls.length,
+ signalOf(delegate, kept).aborted,
+ disposedOf(delegate, kept),
+ ]).toEqual([0, false, 0])
+
+ // The kept tier's keeper released it, and its start's settling ends its demand, releasing what the start registered.
+ pending.resolve()
+ await settle()
+
+ expect([
+ signalOf(delegate, kept).aborted,
+ disposedOf(delegate, kept),
+ ]).toEqual([false, 1])
+ })
+
+ it('emits a streaming enabled change naming its sensor and views at home for a write, a restore and a reset, beside each webrtc service\'s change '
+ + 'from away at the reset', async () => {
+ const camera = wiredCamera()
+ const map = configured(camera)
+ const changes: StreamingEnabledChange[] = []
+ camera.on(CameraControllerEvents.STREAMING_ENABLED_CHANGED, change => changes.push(change))
+
+ await map[SECOND_KEY]!.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, buildEmitterConnection())
+ camera.deserialize({
+ streamManagements: [],
+ multiTierStreamManagements: {
+ [SENSOR_UUID.toLowerCase()]: { streamingEnabled: false },
+ },
+ })
+ camera.handleFactoryReset()
+
+ expect(changes).toEqual([
+ {
+ reason: 'write',
+ sensorUUID: SECOND_SENSOR.uuid.toLowerCase(),
+ value: false,
+ where: 'home',
+ },
+ {
+ reason: 'restore',
+ sensorUUID: SENSOR_UUID.toLowerCase(),
+ value: false,
+ where: 'home',
+ },
+ {
+ reason: 'reset',
+ sensorUUID: SENSOR_UUID.toLowerCase(),
+ value: true,
+ where: 'home',
+ },
+ {
+ reason: 'reset',
+ sensorUUID: SECOND_SENSOR.uuid.toLowerCase(),
+ value: true,
+ where: 'home',
+ },
+ {
+ reason: 'reset',
+ sensorUUID: SENSOR_UUID.toLowerCase(),
+ value: true,
+ where: 'away',
+ },
+ {
+ reason: 'reset',
+ sensorUUID: SECOND_SENSOR.uuid.toLowerCase(),
+ value: true,
+ where: 'away',
+ },
+ ])
+ })
+
+ it('ends a multi-tier session at a force-stop of its identifier and ignores an identifier no session holds', async () => {
+ const camera = wiredCamera()
+ const service = multiTierServiceOf(configured(camera), SERVICE_KEY)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const answer = await streaming(service, connection, from)
+
+ expect(() => camera.forceStopStreamingSession(UNKNOWN_SESSION)).not.toThrow()
+ await settle()
+
+ expect(udpSockets()).toBe(base + 2)
+
+ camera.forceStopStreamingSession(answer.sessionIdentifier)
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ })
+
+ it('ends every session and leaves no policy listener on a removed service at a reset and a removal, the second run throwing nothing', async () => {
+ const camera = wiredCamera()
+ const map = configured(camera)
+ const service = multiTierServiceOf(map, SERVICE_KEY)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const answer = await streaming(service, connection, from)
+
+ camera.handleFactoryReset()
+ camera.handleControllerRemoved()
+
+ expect(() => {
+ camera.handleFactoryReset()
+ camera.handleControllerRemoved()
+ }).not.toThrow()
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+
+ // Each characteristic keeps only its service's own change listener, the legacy stream's Active and each multi-tier and WebRTC Streaming Enabled
+ // their class's as well, and no service keeps a configuration listener.
+ const streamServices = [Service.CameraMultiTierRTPStreamManagement.UUID, Service.CameraWebRTCStreamManagement.UUID]
+
+ for (const removed of Object.values(map).filter(candidate => candidate !== undefined)) {
+ expect(removed.listenerCount(ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE)).toBe(0)
+
+ for (const characteristic of removed.characteristics) {
+ const ownedByClass = (removed.UUID === Service.CameraRTPStreamManagement.UUID && characteristic.UUID === Characteristic.Active.UUID)
+ || (streamServices.includes(removed.UUID) && characteristic.UUID === Characteristic.StreamingEnabled.UUID)
+
+ expect(characteristic.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(ownedByClass ? 2 : 1)
+ }
+ }
+ })
+
+ it('sends each demand of a removed camera its end, naming its own stream, before the next camera\'s first start of that tier', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const delegate = scriptedTierDelegate()
+ const streamingOptions = { delegate }
+ const removed = wiredCamera([SENSOR], streamingOptions)
+ const removedService = multiTierServiceOf(configured(removed), SERVICE_KEY)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+
+ // Video tier 1 starts for one session, and a second session's Start waits on video tier 2, whose start never settles.
+ await streaming(removedService, connection, from)
+ const waiting = crypto.randomUUID()
+ await prepare(removedService, connection, from, waiting)
+ delegate.tierDemandStarted.mockImplementationOnce(async () => new Promise(() => undefined))
+ const starting = start(removedService, connection, waiting, 2)
+ await settle()
+ const removedStarts = delegate.tierDemandStarted.mock.calls.length
+ const aborted = vi.fn<() => void>()
+
+ signalOf(delegate, streamOf(delegate, 2)).addEventListener('abort', aborted)
+
+ // The next camera's sessions are prepared and started at once, with no wait for the removed camera's sessions to end.
+ removed.handleControllerRemoved()
+ const next = multiTierServiceOf(configured(wiredCamera([SENSOR], streamingOptions)), SERVICE_KEY)
+ await streaming(next, connection, from)
+ await streaming(next, connection, from, 2)
+
+ expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+
+ const streams = streamsOf(delegate)
+ const [settledStream, pendingStream] = streams
+
+ expect(streams.map(({ tier }) => tier.id)).toEqual([1, 2, 1, 2])
+ expect(streams.map(({ tier }) => tier.sensorUUID)).toEqual(Array.from({ length: 4 }).fill(SENSOR_UUID.toLowerCase()))
+
+ // The settled start's end is the release of what it registered, bound to its own stream, and the pending start's, which registered nothing, is the
+ // abort of its signal, each before the next camera's first start of that tier.
+ expect([
+ disposedOf(delegate, settledStream),
+ signalOf(delegate, settledStream).aborted,
+ ]).toEqual([1, false])
+ expect([
+ disposedOf(delegate, pendingStream),
+ aborted.mock.calls.length,
+ ]).toEqual([0, 1])
+
+ for (const [stream, end] of [
+ [settledStream, delegate.disposals.get(settledStream)!.mock.invocationCallOrder[0]],
+ [pendingStream, aborted.mock.invocationCallOrder[0]],
+ ] as const) {
+ const nextStart = streams.findIndex((candidate, index) => (index >= removedStarts) && (candidate.tier.id === stream.tier.id))
+
+ expect(end).toBeLessThan(delegate.tierDemandStarted.mock.invocationCallOrder[nextStart])
+ }
+ })
+
+ it('hands the state-change delegate to every multi-tier management, which is how each one\'s streaming enabled saves the camera', async () => {
+ const camera = wiredCamera()
+ const map = configured(camera)
+ const saves = vi.fn()
+ camera.setupStateChangeDelegate(saves)
+
+ await map[SERVICE_KEY]!.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, buildEmitterConnection())
+ await map[SECOND_KEY]!.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, buildEmitterConnection())
+
+ expect(saves).toHaveBeenCalledTimes(2)
+
+ camera.setupStateChangeDelegate(undefined)
+ map[SECOND_KEY]!.updateCharacteristic(Characteristic.StreamingEnabled, true)
+
+ expect(saves).toHaveBeenCalledTimes(2)
+ })
+
+ it('tells of a view at home once as its Start is answered and once as its session ends, naming the sensor, the session and the tier', async () => {
+ const camera = wiredCamera()
+ const service = multiTierServiceOf(configured(camera), SECOND_KEY)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const events: (readonly [string, CameraLiveView])[] = []
+ camera.on(CameraControllerEvents.LIVE_VIEW_STARTED, view => events.push(['started', view]))
+ camera.on(CameraControllerEvents.LIVE_VIEW_ENDED, view => events.push(['ended', view]))
+
+ // A session prepared and ended without a Start is no view.
+ const prepared = crypto.randomUUID()
+ await prepare(service, connection, from, prepared)
+
+ expect(await end(service, connection, prepared)).toBe(RTPStreamingStatus.NO_SUCH_STREAM)
+ expect(events).toEqual([])
+
+ const answer = await streaming(service, connection, from, 2)
+ const view: CameraLiveView = {
+ sensorUUID: SECOND_SENSOR.uuid.toLowerCase(),
+ sessionIdentifier: answer.sessionIdentifier,
+ tierId: 2,
+ where: 'home',
+ }
+
+ expect(events).toStrictEqual([
+ ['started', view],
+ ])
+
+ // A second Start of the streaming session is refused and tells of nothing.
+ expect(await start(service, connection, answer.sessionIdentifier, 2)).toBe(RTPStreamingStatus.ERROR)
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+ expect(events).toStrictEqual([
+ ['started', view],
+ ['ended', view],
+ ])
+
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(events).toHaveLength(2)
+ })
+
+ it('tells a removed camera\'s listeners of the end of each view at home in the removal\'s own turn, before the controller drops them', async () => {
+ const camera = wiredCamera()
+ const service = multiTierServiceOf(configured(camera), SERVICE_KEY)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const answer = await streaming(service, connection, from)
+ const ended = vi.fn<(view: CameraLiveView) => void>()
+ camera.on(CameraControllerEvents.LIVE_VIEW_ENDED, ended)
+
+ camera.handleControllerRemoved()
+
+ expect(ended.mock.calls).toStrictEqual([
+ [
+ {
+ sensorUUID: SENSOR_UUID.toLowerCase(),
+ sessionIdentifier: answer.sessionIdentifier,
+ tierId: 1,
+ where: 'home',
+ },
+ ],
+ ])
+ expect(camera.listenerCount(CameraControllerEvents.LIVE_VIEW_ENDED)).toBe(0)
+
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(ended).toHaveBeenCalledOnce()
+ })
+
+ it('logs each live-view listener that throws, calls the next listener, answers the Start and ends the session all the same', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const camera = wiredCamera()
+ const service = multiTierServiceOf(configured(camera), SERVICE_KEY)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const heard: string[] = []
+ const failing = (): void => {
+ throw new Error('The listener failed.')
+ }
+ camera.on(CameraControllerEvents.LIVE_VIEW_STARTED, failing)
+ camera.on(CameraControllerEvents.LIVE_VIEW_STARTED, () => heard.push('started'))
+ camera.on(CameraControllerEvents.LIVE_VIEW_ENDED, failing)
+ camera.on(CameraControllerEvents.LIVE_VIEW_ENDED, () => heard.push('ended'))
+
+ const answer = await streaming(service, connection, from)
+
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS)
+
+ await settle()
+ await until(() => udpSockets() === base)
+
+ expect(heard).toEqual(['started', 'ended'])
+ expect(error.mock.calls.map(([line]) => String(line).split(': ')[0])).toEqual([
+ '[Camera] A listener of the camera controller\'s live-view-started event failed',
+ '[Camera] A listener of the camera controller\'s live-view-ended event failed',
+ ])
+ })
+
+ describe('as it leaves service', () => {
+ const USERNAME = 'CA:FE:00:00:00:05'
+ const BRIDGE_USERNAME = 'CA:FE:00:00:00:06'
+ // The first sensor's tier the camera keeps running, whose first start stays pending, and the tier it records.
+ const KEPT_TIER = 3
+ const RECORDED_TIER = 1
+
+ // What every row reads once the camera has left service: each of its tiers ended, its recording cancelled with the end marker, its view at home
+ // ended while each Status Active stays on, since the user's switches alone move it, and the kept tier's pending start withdrawn with a debug line,
+ // its signal aborted, and no warning.
+ const ENDED = {
+ alerts: [],
+ recording: [
+ ['cancelled'],
+ {
+ data: Buffer.alloc(1),
+ isLast: true,
+ },
+ ],
+ registrations: [1, 1],
+ session: RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER,
+ signal: true,
+ statusActive: [true, true],
+ warnings: [],
+ withdrawn: [
+ `The library withdrew the pending start of the video tier ${KEPT_TIER} of the video sensor "${SENSOR_UUID.toLowerCase()}" as the camera went `
+ + 'out of service: every join waiting on it is refused.',
+ ],
+ }
+
+ // The accessories a row publishes or bridges, destroyed after it. No server, record or context outlives its row.
+ const accessories: Accessory[] = []
+
+ afterEach(async () => {
+ for (const accessory of accessories.splice(0)) {
+ await accessory.destroy()
+ }
+ })
+
+ // How a row's camera leaves service and how it comes back, once it is in service.
+ interface ServicePath {
+ readonly back: () => Promise
+ readonly leave: () => Promise
+ }
+
+ // A camera serving as it leaves service: its accessory and path, the stream of its kept tier and of its recorded tier, the recording
+ // open on the recorded tier and its view at home on it, and what it raised, ended and wrote meanwhile.
+ interface Serving {
+ readonly accessory: Accessory
+ readonly alerts: CameraProblem[]
+ readonly answer: Prepared
+ readonly base: number
+ readonly connection: HAPConnection
+ readonly delegate: ScriptedTierDelegate
+ readonly ends: CameraRecordingEnd[]
+ readonly kept: TierStream
+ readonly lines: string[]
+ readonly packets: RecordingPacket[]
+ readonly path: ServicePath
+ readonly pending: Deferred
+ readonly recorded: TierStream
+ readonly services: CameraMultiTierRTPStreamManagement[]
+ readonly warn: Mock
+ }
+
+ // Publishes an accessory through the advertiser the suite mocks, and nothing is announced.
+ async function publish(accessory: Accessory, username = USERNAME): Promise {
+ if (!accessories.includes(accessory)) {
+ accessories.push(accessory)
+ }
+
+ await accessory.publish({
+ advertiser: MDNSAdvertiser.BONJOUR,
+ category: Categories.CAMERA,
+ pincode: '031-45-154',
+ username,
+ })
+ }
+
+ // The accessory published alone, leaving service at its unpublish and coming back at its publish.
+ async function alone(accessory: Accessory): Promise {
+ await publish(accessory)
+
+ return {
+ back: async () => publish(accessory),
+ leave: async () => accessory.unpublish(),
+ }
+ }
+
+ // The accessory bridged to a published bridge, leaving service as it is taken off the bridge and coming back as it is put back.
+ async function bridged(accessory: Accessory): Promise {
+ const bridge = new Bridge('Bridge', uuid.generate('a bridge its camera leaves'))
+
+ await publish(bridge, BRIDGE_USERNAME)
+ accessories.push(accessory)
+ bridge.addBridgedAccessory(accessory)
+
+ return {
+ back: async () => {
+ bridge.addBridgedAccessory(accessory)
+ },
+ leave: async () => {
+ bridge.removeBridgedAccessory(accessory)
+ },
+ }
+ }
+
+ // The accessory published alone, its camera leaving service as its source is stated away and coming back as it is stated available.
+ async function stated(accessory: Accessory, camera: CameraController): Promise {
+ await publish(accessory)
+
+ return {
+ back: async () => {
+ camera.updateSourceState('available')
+ },
+ leave: async () => {
+ camera.updateSourceState('away')
+ },
+ }
+ }
+
+ // A camera on an accessory of its own, configured there: its first sensor's tier 3 marked keepRunning, whose first start, that tier's, stays
+ // pending, and its first sensor's tier 1 recorded with no prebuffer.
+ function keptCamera(): { accessory: Accessory, camera: CameraController, delegate: ScriptedTierDelegate, pending: Deferred } {
+ const delegate = scriptedTierDelegate()
+ const pending = pendingStart(delegate)
+ const camera = new CameraController(capabilitiesCameraOptions({
+ recording: { prebuffer: 0 },
+ streaming: { delegate },
+ videoSensors: [
+ {
+ ...SENSOR,
+ tiers: SENSOR.tiers.map(tier => ({ ...tier, keepRunning: tier.id === KEPT_TIER })),
+ },
+ SECOND_SENSOR,
+ ],
+ }))
+ const accessory = new Accessory('Camera', uuid.generate('a camera leaving service'))
+
+ cameras.push(camera)
+ accessory.configureController(camera)
+
+ return { accessory, camera, delegate, pending }
+ }
+
+ // The kept camera with recording on, put in service by the path given, its recorded tier written a ready buffer, a recording opened on it and a view
+ // at home started on it, the problems heard on its accessory's channel and its recording ends kept, the tiers' debug log captured and every warning
+ // held.
+ async function serving(enter: (accessory: Accessory, camera: CameraController) => Promise): Promise {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const lines = captureDebug('HAP-NodeJS:Camera:Tier')
+ const { accessory, camera, delegate, pending } = keptCamera()
+ const recordingManagement = camera.recordingManagement!
+ const { problems: alerts } = problemsOf(accessory.UUID)
+ const ends: CameraRecordingEnd[] = []
+ const packets: RecordingPacket[] = []
+
+ camera.on(CameraControllerEvents.RECORDING_ENDED, end => ends.push(end))
+ recordingManagement.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE)
+
+ const path = await enter(accessory, camera)
+ const recorded = streamOf(delegate, RECORDED_TIER)
+
+ recorded.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS }))
+ frames(recorded, 0, 1)
+
+ const recording = recordingManagement.delegate.handleRecordingStreamRequest(1)
+
+ void (async () => {
+ for await (const packet of recording) {
+ packets.push(packet)
+ }
+ })()
+ frames(recorded, 1, 45)
+
+ const services = accessory.services.filter(service => service.UUID === Service.CameraMultiTierRTPStreamManagement.UUID)
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const answer = await streaming(services[0] as CameraMultiTierRTPStreamManagement, connection, from, RECORDED_TIER)
+
+ return {
+ accessory,
+ alerts,
+ answer,
+ base,
+ connection,
+ delegate,
+ ends,
+ kept: streamOf(delegate, KEPT_TIER),
+ lines,
+ packets,
+ path,
+ pending,
+ recorded,
+ services: services as CameraMultiTierRTPStreamManagement[],
+ warn,
+ }
+ }
+
+ function statusActiveOf(services: readonly CameraMultiTierRTPStreamManagement[]): unknown[] {
+ return services.map(service => service.getCharacteristic(Characteristic.StatusActive).value)
+ }
+
+ // What the camera ended once it left service and the view's exit has settled, in the shape of the readings every row expects.
+ async function endedBy(served: Serving): Promise> {
+ await settle()
+ await until(() => udpSockets() === served.base)
+ await settle()
+
+ return {
+ alerts: served.alerts,
+ recording: [
+ served.ends.map(({ outcome }) => outcome),
+ served.packets.at(-1),
+ ],
+ registrations: [served.kept, served.recorded].map(stream => disposedOf(served.delegate, stream)),
+ session: await end(served.services[0], served.connection, served.answer.sessionIdentifier),
+ signal: signalOf(served.delegate, served.kept).aborted,
+ statusActive: statusActiveOf(served.services),
+ warnings: served.warn.mock.calls,
+ withdrawn: served.lines.filter(line => line.startsWith('The library withdrew')),
+ }
+ }
+
+ it.each([
+ ['its accessory is unpublished and published again', alone],
+ ['its accessory is taken off its published bridge and put back', bridged],
+ ['its source is stated away and then available', stated],
+ ] as const)('ends its kept and recorded tiers, its recording and its view at home, withdrawing its kept tier\'s pending start with no warning, as '
+ + '%s, and raises each tier it holds afresh with no alert once back', async (_path, enter) => {
+ const served = await serving(enter)
+
+ await served.path.leave()
+
+ expect(await endedBy(served)).toEqual(ENDED)
+
+ const before = streamsOf(served.delegate).length
+
+ await served.path.back()
+ await settle()
+
+ expect([
+ streamsOf(served.delegate).slice(before).map(({ tier }) => tier.id),
+ served.alerts,
+ statusActiveOf(served.services),
+ ]).toEqual([
+ [KEPT_TIER, RECORDED_TIER],
+ [],
+ [true, true],
+ ])
+
+ served.pending.resolve()
+ })
+
+ it.each([
+ ['standing alone', alone],
+ ['bridged', bridged],
+ ] as const)('ends its kept and recorded tiers, its recording and its view at home, withdrawing its kept tier\'s pending start with no warning, at '
+ + 'the destroy of its accessory %s', async (_path, enter) => {
+ const served = await serving(enter)
+
+ await served.accessory.destroy()
+
+ expect(await endedBy(served)).toEqual(ENDED)
+
+ served.pending.resolve()
+ })
+
+ it('calls tierDemandStarted no more at its removal from its published accessory than it did as the accessory was published, its kept tier\'s '
+ + 'start still pending, and writes no warning', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const { accessory, camera, delegate, pending } = keptCamera()
+
+ await alone(accessory)
+ await settle()
+
+ const published = delegate.tierDemandStarted.mock.calls.length
+
+ accessory.removeController(camera)
+ await settle()
+
+ expect([
+ published,
+ delegate.tierDemandStarted.mock.calls.length,
+ warn.mock.calls,
+ ]).toEqual([1, 1, []])
+
+ pending.resolve()
+ })
+
+ /* Whether the keeper's raise at the statement of available joins the demand the ending view still holds or raises the tier afresh follows the order
+ * of the session's release and the raise, which is why the row counts no start: it reads the tier running once the view's exit has settled, and every start
+ * matched by an end once a later away has ended it.
+ */
+ it('ends a view at home on its kept tier and holds the tier running once the view\'s exit has settled, its source stated away and then available in '
+ + 'one turn, and ends the tier at a later away, the plugin hearing as many ends of the tier as starts', async () => {
+ const { accessory, camera, delegate, pending } = keptCamera()
+ const running = (): number => streamsOf(delegate, KEPT_TIER).length - endsOf(delegate, KEPT_TIER)
+
+ pending.resolve()
+ await alone(accessory)
+
+ const service = accessory.getServiceById(Service.CameraMultiTierRTPStreamManagement, SENSOR_UUID.toLowerCase()) as CameraMultiTierRTPStreamManagement
+ const from = await endpoint()
+ const connection = buildEmitterConnection()
+ const base = udpSockets()
+ const answer = await streaming(service, connection, from, KEPT_TIER)
+
+ camera.updateSourceState('away')
+ camera.updateSourceState('available')
+ await settle()
+ await until(() => udpSockets() === base)
+ await settle()
+
+ const held = running()
+
+ expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+
+ camera.updateSourceState('away')
+ await settle()
+
+ expect([
+ held,
+ running(),
+ ]).toEqual([1, 0])
+ })
+ })
+ })
+})
diff --git a/src/lib/camera/MultiTierStreamManagement.ts b/src/lib/camera/MultiTierStreamManagement.ts
new file mode 100644
index 000000000..31fe4ef34
--- /dev/null
+++ b/src/lib/camera/MultiTierStreamManagement.ts
@@ -0,0 +1,1386 @@
+import type { Socket, SocketType } from 'node:dgram'
+
+import type { CameraLiveView, ControllerServiceMap, StateChangeDelegate } from '../controller/index.js'
+import type { CameraMultiTierRTPStreamManagement } from '../definitions/index.js'
+import type { HAPConnection } from '../util/eventedhttp.js'
+import type { RTPStreamingControlRequest, RTPStreamingControlResponse } from './capabilities/rtpStreaming.js'
+import type { SetupEndpointsRequest, SetupEndpointsResponse } from './capabilities/setupEndpoints.js'
+import type { CameraReporter, DebugWriter } from './diagnostics/CameraReporter.js'
+import type { OperatingModePolicy, StreamingEnabledChange } from './OperatingModePolicy.js'
+import type { MultiTierStreamingDelegate, StreamTierMedium, TalkbackSink, Talker } from './StreamingOptions.js'
+import type { Tier, TierHold, TierHolder, TierTable } from './TierTable.js'
+
+import { Buffer } from 'node:buffer'
+import crypto from 'node:crypto'
+import dgram from 'node:dgram'
+
+import { Characteristic } from '../Characteristic.js'
+import { HAPStatus } from '../HAPServer.js'
+import { Service } from '../Service.js'
+import { AsyncDisposableStack } from '../util/asyncDisposableStack.js'
+import { nounFor } from '../util/counted.js'
+import { DisposableStack } from '../util/disposableStack.js'
+import { errorMessage } from '../util/errors.js'
+import { HapStatusError } from '../util/hapStatusError.js'
+import { ntpTime } from '../util/ntp.js'
+import * as uuid from '../util/uuid.js'
+import { decodeRTPStreamingControlRequest, encodeRTPStreamingControlResponse, RTPStreamingCommand, RTPStreamingStatus } from './capabilities/rtpStreaming.js'
+import {
+ decodeSetupEndpointsRequest,
+ encodeSetupEndpointsResponse,
+ SETUP_ENDPOINTS_ERROR,
+ SetupEndpointsStatus,
+ SRTPCryptoSuites,
+} from './capabilities/setupEndpoints.js'
+import { encodeSupportedAudioStreamTiers, encodeSupportedVideoStreamTiers } from './capabilities/streamTiers.js'
+import { encodeSupportedRTPConfiguration } from './capabilities/supportedRtpConfiguration.js'
+import { reconcileSensorServices, sensorServiceKey } from './capabilityKeys.js'
+import { debugChannel } from './diagnostics/debugChannels.js'
+import { firstSequence, nextSequence, RTP_HEADER_LENGTH, wireTimestamp } from './rtp/packetRules.js'
+import { CLOCK_RATES } from './rtp/RTPClock.js'
+import { CommandQueue } from './session/CommandQueue.js'
+import { ConnectionSessions } from './session/ConnectionSessions.js'
+import { wireControlPoint } from './session/controlPoint.js'
+import { SessionTalkback } from './session/SessionTalkback.js'
+import { settleWithin } from './session/settleWithin.js'
+import { StreamingEnabledSwitch } from './session/StreamingEnabledSwitch.js'
+import { PLAIN_PACKET_LIMIT, SRTPContext } from './srtp/SRTPContext.js'
+
+const MULTI_TIER_DEBUG = debugChannel('HAP-NodeJS:Camera:MultiTier')
+
+// The reason the exit's debug event gives a session endSession ends, alone or among every session the service ends at once.
+const ENDED_BY_OWNER = 'its owner ended it'
+
+/* A prepared session nobody starts within this bound ends. A hub prepares again whenever its tile asks again. An abandoned preparation is routine, and a
+ * hub's connection, whose close would otherwise end the session, can live for days while the session holds one of the service's slots.
+ */
+const PREPARE_TIMEOUT = 60 * 1000
+
+// RFC 3550 6.2's minimum interval between sender reports, and the delay of the first report, half of it.
+const REPORT_INTERVAL = 5 * 1000
+const FIRST_REPORT_DELAY = REPORT_INTERVAL / 2
+
+// RFC 3550 A.7 divides each randomized report interval by e - 3/2, which compensates for the timer reconsideration that would otherwise lower the rate.
+const REPORT_COMPENSATION = Math.E - 1.5
+
+// RFC 3550 6.3.5 counts a participant gone once it has sent nothing for five reporting intervals at the minimum interval.
+const LIVENESS_WINDOW = 5 * REPORT_INTERVAL
+
+// AES_CM_128_HMAC_SHA1_80's master key and salt, which the accessory generates for each medium of each session.
+const SRTP_MASTER_KEY_LENGTH = 16
+const SRTP_MASTER_SALT_LENGTH = 14
+
+// The SRTP tag each pooled buffer leaves room for after its packet, and the index and tag SRTCP appends.
+const SRTP_TAG_LENGTH = 10
+const SRTCP_TRAILER_LENGTH = 14
+
+/* The buffers each sender pools at first, sized for a keyframe burst at the highest tier delivered in one turn for video and a few frames for audio, and the
+ * most its pool grows to. A send that finds every buffer in flight adds as many buffers again as the pool holds, up to its medium's ceiling. A burst
+ * larger than the pool is sent whole, and a pool never shrinks: each growth is allocated once and kept.
+ */
+const POOL_SIZES: Readonly> = { audio: 16, video: 256 }
+const POOL_CEILINGS: Readonly> = { audio: 128, video: 2048 }
+
+// The two media every session carries, one socket each, in the order their sockets bind.
+const MEDIA: readonly StreamTierMedium[] = ['video', 'audio']
+
+// The medium a view at home joins its own tier for where it takes its sound from the sensor's sound tier, and the medium it joins that tier for.
+const PICTURE: readonly StreamTierMedium[] = ['video']
+const SOUND: readonly StreamTierMedium[] = ['audio']
+
+// RFC 5761 4 tells RTCP from RTP on a multiplexed port by the second octet: from 192 to 223 it is RTCP.
+const RTCP_SECOND_OCTET_MINIMUM = 192
+const RTCP_SECOND_OCTET_MAXIMUM = 223
+
+// The payload type below the marker bit in the second octet of RFC 3550 5.1's fixed RTP header, whose octets 2 and 3 carry the sequence number and
+// octets 8 to 11 the SSRC.
+const RTP_PAYLOAD_TYPE_MASK = 0x7F
+const SEQUENCE_OFFSET = 2
+
+// RFC 3550 6.4.1's sender report, header to octet count, and RFC 4585 6.1's payload-specific feedback with the formats asking for a keyframe: the picture
+// loss indication (RFC 4585 6.3.1) and the full intra request (RFC 5104 4.3.1).
+const SENDER_REPORT = 200
+const SENDER_REPORT_LENGTH = 28
+const PAYLOAD_SPECIFIC_FEEDBACK = 206
+const KEYFRAME_FORMATS: ReadonlySet = new Set([1, 4])
+
+// The one suite the multi-tier service supports (the HomeKit Secure Video compatibility guide, section 3.6), as Supported RTP Configuration advertises it.
+const SUPPORTED_RTP_CONFIGURATION = encodeSupportedRTPConfiguration([SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80])
+
+/**
+ * The options of a {@link MultiTierStreamManagement}, one per video sensor. The camera controller validates the camera's streaming options before it builds
+ * one, which is why the options reach the class already coherent.
+ */
+export interface MultiTierStreamManagementOptions {
+ /**
+ * The camera's delegate, which starts each session's talkback. The table reports each tier's demand to the same delegate.
+ */
+ delegate: MultiTierStreamingDelegate
+ /**
+ * The video sensor's tier table, which the camera controller builds for the sensor: its stream tiers, which the service advertises and its key names,
+ * each video tier's demand, which reads the tier's stream, times its picture and its sound on the sensor's one clock and cuts them into the packets each
+ * joined session sends, and answers a viewer's keyframe request from the tier's buffer.
+ */
+ table: TierTable
+ /**
+ * The most sessions the service holds at once, prepared or streaming, as the camera's streaming options defaulted and validated it.
+ */
+ maxSessions: number
+ /**
+ * Called once for each session whose view started, as its disposal opens, in the exit's own turn.
+ */
+ onLiveViewEnded?: (view: CameraLiveView) => void
+ /**
+ * Called once for each session whose Start is answered with success, as it is answered.
+ */
+ onLiveViewStarted?: (view: CameraLiveView) => void
+ /**
+ * Called once for each change of the service's Streaming Enabled, before the state-change delegate.
+ */
+ onStreamingEnabledChange?: (change: StreamingEnabledChange) => void
+ /**
+ * The camera's reporter, through which each session's talkback reports a failure of the plugin's sink, of its start or of what the plugin registered on
+ * the talker.
+ */
+ reporter: CameraReporter
+ /**
+ * Whether the camera's Speaker is muted, read as it stands at each talkback datagram a session takes: a muted Speaker has every session drop its
+ * controller's talkback after the datagram is unprotected, which keeps the session's SRTP index in step with the controller's through a mute, and a sink
+ * a session started stays started, written nothing until the Speaker is unmuted.
+ */
+ speakerMuted: () => boolean
+}
+
+/**
+ * The persisted state of one video sensor's Camera Multi-Tier RTP Stream Management service.
+ */
+export interface MultiTierStreamManagementState {
+ /**
+ * The value of Streaming Enabled.
+ */
+ streamingEnabled: boolean
+}
+
+type SessionState = 'prepared' | 'streaming'
+
+// What a session's talkback and its view's end reach in the management that registered it, beside the session table. A keyframe request goes to the hold
+// the session's Start joined its tier with, which the session keeps, and the context carries no route for it.
+interface MultiTierSessionContext {
+ // The audio tier's payload type, which a controller's talkback carries, the delegate's talkbackStarted, which takes the talker, answering undefined for a
+ // delegate without it, the reader of whether the camera's Speaker is muted, and the camera's reporter, which each session's talkback reports through.
+ readonly audioPayloadType: number
+ readonly talkbackStarted: (talker: Talker) => TalkbackSink | undefined
+ readonly speakerMuted: () => boolean
+ readonly reporter: CameraReporter
+ // The video sensor the sessions view, in lowercase, and the hook a streaming session's disposal tells of its view's end through.
+ readonly sensorUUID: string
+ readonly liveViewEnded?: (view: CameraLiveView) => void
+}
+
+// One medium of a session: its socket, connected to the controller, the context protecting what the accessory sends, the context unprotecting what the
+// controller sends, its RTCP and on the audio socket its talkback, the SSRC the accessory answered, and the sender a successful Start joined to the
+// medium's tier, which its sender reports read until the session leaves.
+interface SessionMedium {
+ readonly socket: Socket
+ readonly outbound: SRTPContext
+ readonly inbound: SRTPContext
+ readonly ssrc: number
+ sender?: TierSender
+}
+
+// A Start's join of its video tier: its hold, and the sender the join made for each of the session's media.
+interface SessionHold {
+ readonly hold: TierHold
+ readonly senders: Readonly>
+}
+
+type MasterKeyAndSalt = Pick
+
+// Walks a compound RTCP packet (RFC 3550 6.1), answering whether any of its packets asks for a keyframe, or undefined for one whose lengths do not tile it.
+function asksForKeyframe(packet: Buffer, length: number): boolean | undefined {
+ let keyframe = false
+
+ for (let offset = 0; offset < length;) {
+ if (length - offset < 4 || packet[offset] >> 6 !== 2) {
+ return undefined
+ }
+
+ const end = offset + (packet.readUInt16BE(offset + 2) + 1) * 4
+
+ if (end > length) {
+ return undefined
+ }
+
+ if (packet[offset + 1] === PAYLOAD_SPECIFIC_FEEDBACK && KEYFRAME_FORMATS.has(packet[offset] & 0x1F)) {
+ keyframe = true
+ }
+
+ offset = end
+ }
+
+ return keyframe
+}
+
+// The accessory's own master key and salt for one medium of a session, fresh from the system's random source.
+function masterKeyAndSalt(): MasterKeyAndSalt {
+ return {
+ masterKey: crypto.randomBytes(SRTP_MASTER_KEY_LENGTH),
+ masterSalt: crypto.randomBytes(SRTP_MASTER_SALT_LENGTH),
+ }
+}
+
+// A report interval drawn as RFC 3550 6.2 and A.7 draw one at the minimum interval: uniformly from half to one and a half times it, then compensated.
+function reportInterval(): number {
+ return REPORT_INTERVAL * (0.5 + Math.random()) / REPORT_COMPENSATION
+}
+
+// Binds a socket at port 0 on its family's wildcard. The bind's own error listener answers a failure, as RTPProxy's does, and either way the socket then
+// carries the session's listener, because a dgram socket without one ends the process at its first error.
+async function bind(socket: Socket, address: string, listener: (error: Error) => void): Promise {
+ return new Promise((resolve) => {
+ const failed = (): void => {
+ socket.on('error', listener)
+ resolve(false)
+ }
+
+ socket.once('error', failed)
+ socket.bind(0, address, () => {
+ socket.removeListener('error', failed)
+ socket.on('error', listener)
+ resolve(true)
+ })
+ })
+}
+
+// Connects a socket to the controller's port, and every datagram from another source is dropped and no send looks up an address.
+async function connect(socket: Socket, port: number, address: string): Promise {
+ return new Promise((resolve) => {
+ socket.connect(port, address, (error?: Error) => resolve(!error))
+ })
+}
+
+async function close(socket: Socket): Promise {
+ return new Promise((resolve) => {
+ socket.close(() => resolve())
+ })
+}
+
+/* One session's sending half for one medium while the session is joined to a tier. Its pool of preallocated buffers, a ring, carries the packets in
+ * flight: a send takes the next buffer, copies the packet in, rewrites its payload type and SSRC and writes its own sequence number, numbering the packets
+ * it sends from a random start of its own, which means one session's opening shows no other session a gap. The send protects the packet in place and sends a view of it
+ * with the one completion callback the sender keeps. Sends complete in the order they were made: each completion frees the oldest buffer. A send that finds
+ * every buffer in flight grows the pool first, up to its ceiling, and one that finds a pool at its ceiling in flight refuses the packet, which the tier's
+ * stream counts as dropped and which takes the next sequence number all the same. The session's numbering carries the gap its viewer reads as a loss
+ * while every other session's own numbering runs on unbroken. The sender answers the room its ceiling leaves, which a view's opening is handed no more
+ * than in a turn, and its ceiling as its capacity, past which a frame of an opening is sent at once as a live release sends it. It reports from its first
+ * packet on, since an opening's timestamps stand past every timestamp its tier has sent and run at no more than the live edge: each packet's timestamp
+ * is a live one a report can map the clock to.
+ */
+class TierSender {
+ readonly session: MultiTierSession
+ packets = 0
+ octets = 0
+ private readonly medium: SessionMedium
+ private readonly payloadType: number
+ private readonly clockRate: number
+ private readonly slotLength: number
+ private readonly ceiling: number
+ private readonly slots: Buffer[]
+ private oldest = 0
+ private inFlight = 0
+ private sequence = firstSequence()
+ private lastTimestamp = 0
+ private lastSendTime = 0
+
+ constructor(session: MultiTierSession, medium: SessionMedium, payloadType: number, clockRate: number, packetSize: number, poolSize: number, ceiling: number) {
+ this.session = session
+ this.medium = medium
+ this.payloadType = payloadType
+ this.clockRate = clockRate
+ this.slotLength = packetSize + SRTP_TAG_LENGTH
+ this.ceiling = ceiling
+ this.slots = this.allocate(poolSize)
+ }
+
+ // The packets the sender can still take before a send meets its pool at its ceiling with every buffer in flight.
+ get free(): number {
+ return this.ceiling - this.inFlight
+ }
+
+ // The packets the sender takes with nothing in flight, its pool's ceiling.
+ get capacity(): number {
+ return this.ceiling
+ }
+
+ // Sends one plain RTP packet, answering whether a buffer was free for it.
+ send(packet: Buffer, octets: number, now: number): boolean {
+ const slots = this.slots
+
+ if (this.inFlight === slots.length) {
+ if (slots.length === this.ceiling) {
+ this.sequence = nextSequence(this.sequence)
+
+ return false
+ }
+
+ this.grow(Math.min(slots.length, this.ceiling - slots.length))
+ }
+
+ const slot = slots[(this.oldest + this.inFlight) % slots.length]
+ packet.copy(slot, 0)
+ slot[1] = (slot[1] & 0x80) | this.payloadType
+ slot.writeUInt16BE(this.sequence, SEQUENCE_OFFSET)
+ slot.writeUInt32BE(this.medium.ssrc, 8)
+ this.sequence = nextSequence(this.sequence)
+
+ const length = this.medium.outbound.protect(slot.subarray(0, packet.length), slot)
+ this.inFlight++
+ this.medium.socket.send(slot.subarray(0, length), this.sent)
+
+ this.packets++
+ this.octets += octets
+ this.lastTimestamp = packet.readUInt32BE(4)
+ this.lastSendTime = now
+
+ return true
+ }
+
+ /* Sends a sender report (RFC 3550 6.4.1) once the medium has sent a packet: its SSRC, the NTP time of the report, the last packet's RTP timestamp
+ * advanced by the steady time since it was sent, and the packet and octet counts. The NTP time is written as one 64-bit value modulo 2^64, which means its seconds
+ * wrap on 2036-02-07 (the RFC 5905 era). Each 32-bit word after it is written modulo 2^32, as the RTP timestamp and both counts wrap under RFC 3550.
+ */
+ report(moment: number, ntp: bigint): void {
+ if (this.packets === 0) {
+ return
+ }
+
+ const report = Buffer.alloc(SENDER_REPORT_LENGTH)
+ report[0] = 0x80
+ report[1] = SENDER_REPORT
+ report.writeUInt16BE(SENDER_REPORT_LENGTH / 4 - 1, 2)
+ report.writeUInt32BE(this.medium.ssrc, 4)
+ report.writeBigUInt64BE(BigInt.asUintN(64, ntp), 8)
+ report.writeUInt32BE(wireTimestamp(this.lastTimestamp + Math.round((moment - this.lastSendTime) * this.clockRate / 1000)), 16)
+ report.writeUInt32BE(this.packets >>> 0, 20)
+ report.writeUInt32BE(this.octets >>> 0, 24)
+
+ const output = Buffer.alloc(SENDER_REPORT_LENGTH + SRTCP_TRAILER_LENGTH)
+ this.medium.socket.send(output.subarray(0, this.medium.outbound.protectRTCP(report, output)))
+ }
+
+ // Allocates buffers for the pool in one allocation, each a view of its own stretch, as long as the largest packet and its tag.
+ private allocate(count: number): Buffer[] {
+ const pool = Buffer.alloc(count * this.slotLength)
+
+ return Array.from({ length: count }, (_slot, index) => pool.subarray(index * this.slotLength, (index + 1) * this.slotLength))
+ }
+
+ /* Adds buffers to a pool whose every buffer is in flight. They go in at the oldest buffer's place in the ring and the oldest moves past them. The ring
+ * runs from the oldest buffer in flight through the newest and then into the added ones: every buffer in flight keeps its bytes, the sends still complete
+ * in the order they were made, and the next send takes the first added buffer.
+ */
+ private grow(count: number): void {
+ this.slots.splice(this.oldest, 0, ...this.allocate(count))
+ this.oldest += count
+ }
+
+ // Each completion frees the oldest buffer, and one that reports an error, as a platform's send can for a controller that has gone, is counted on the
+ // session, which streams on until its connection closes, its RTCP falls silent or its tier fails, a silence of the tier's pictures among the failures.
+ private readonly sent = (error: Error | null): void => {
+ this.oldest = (this.oldest + 1) % this.slots.length
+ this.inFlight--
+
+ if (error) {
+ this.session.sendFailed(error)
+ }
+ }
+}
+
+/* The holder of a view at home's sound where the view takes it from the sensor's sound tier rather than from the tier of its picture: a holder of its own,
+ * which is why that tier's failure, a silence of its pictures among them, and a throw from the view's sound sender end the view's sound alone and never
+ * the view, which goes on silent. Its route releases its hold in a microtask of its own, as the keeper's does, since the route runs inside the stream's
+ * failure and a failed demand ends only as its last hold releases. The failed tier is left to its other holders rather than held by the view until it
+ * ends. A view whose sound is released this way is joined to no later demand of that tier.
+ */
+class SoundHolder implements TierHolder {
+ // The hold the view's sound joined the sound tier with, set as the join answers, which the route reads in its microtask, after the join has answered.
+ hold?: TierHold
+
+ tierFailed(): void {
+ queueMicrotask(() => this.hold?.release())
+ }
+}
+
+/* A registered session: its identifier, the connection that opened it, its state, its two media, the talkback that writes its controller's talkback to the
+ * plugin's sink, and the stack every resource it holds stands on in the order it was acquired. Its disposal is the one exit routine every path that ends a
+ * session runs, through the session table's exit. It holds the tier of its picture itself, and of its sound where the two are one: a failed tier, and a
+ * throw from one of its senders as the tier's pacer releases a packet, reach it through its route, which is that exit. A sound it takes from the sensor's
+ * sound tier is held through a sound holder, whose route ends the sound alone.
+ */
+class MultiTierSession implements AsyncDisposable, TierHolder {
+ readonly sessionIdentifier: string
+ readonly connection: HAPConnection
+ state: SessionState = 'prepared'
+ readonly media: Readonly>
+ // The SSRCs the controller's Start names for its own streams, which its RTCP reports and its talkback carry.
+ controllerSSRCs?: Readonly>
+ private readonly stack = new AsyncDisposableStack()
+ private readonly sessions: ConnectionSessions
+ private readonly context: MultiTierSessionContext
+ private readonly controller = new AbortController()
+ // The work buffer each authenticated RTCP packet is unprotected into, allocated once. It is as long as the longest plain packet a context unprotects,
+ // which a controller's compound reports fit, and a datagram whose packet is longer is dropped.
+ private readonly rtcp = Buffer.alloc(PLAIN_PACKET_LIMIT)
+ // The session's talkback, which starts the sink at the first talkback packet that authenticates while the Speaker is unmuted and closes once the
+ // delegate declined talkback or the talkback ended, its talker's registrations released, and every later talkback datagram is dropped before any
+ // cryptography.
+ private readonly sessionTalkback: SessionTalkback
+ // The talkback datagrams the audio context refused, the first a debug event as it happens and the rest one event, as the session ends. A flood writes
+ // no event per packet.
+ private refusedTalkback = 0
+ // The sends whose completion reported an error, on any of the session's media, the first a debug event as it happens and the rest one count as it ends.
+ private failedSends = 0
+
+ private videoTier = 0
+ // The hold a successful Start joined the session's video tier with for its picture, which a keyframe request goes to until the session leaves.
+ private tierHold?: TierHold
+ private prepareTimer?: ReturnType
+ private reportTimer?: ReturnType
+ private livenessTimer?: ReturnType
+
+ constructor(
+ sessionIdentifier: string,
+ connection: HAPConnection,
+ media: Record,
+ sessions: ConnectionSessions,
+ context: MultiTierSessionContext,
+ ) {
+ this.sessionIdentifier = sessionIdentifier
+ this.connection = connection
+ this.media = media
+ this.sessions = sessions
+ this.context = context
+ this.sessionTalkback = new SessionTalkback({
+ defer: release => this.stack.defer(release),
+ ended: () => this.signal.aborted,
+ reporter: context.reporter,
+ sensorUUID: context.sensorUUID,
+ session: `multi-tier session ${sessionIdentifier}`,
+ sessionIdentifier,
+ start: context.talkbackStarted,
+ })
+ }
+
+ // The session takes over what its preparation acquired, the sockets and the contexts on one stack, once the session table holds it.
+ hold(acquired: AsyncDisposableStack): void {
+ this.stack.use(acquired.move())
+ }
+
+ /* Reaches a Start's own stack of joins from the session's, through the one registration the Start makes before its first join. A session that exits
+ * while its Start waits releases each join, and with it each sender, above its contexts and sockets, as a streaming session's exit does. A join that
+ * raises a demand runs plugin code that can end the session, whose disposal starts in that turn and refuses a registration made after it, which is why none is
+ * made then. The Start leaves the registration nothing to release as it ends, its own disposal emptying the stack, or as it streams, its move emptying
+ * it, and a retried Start holds nothing through an earlier one's registration.
+ */
+ reach(joins: AsyncDisposableStack): void {
+ this.stack.use(joins)
+ }
+
+ // Aborts when the session ends, which cuts a Start's wait for its demands.
+ get signal(): AbortSignal {
+ return this.controller.signal
+ }
+
+ // The view a streaming session is, as the live-view events tell of it: at home, of the sensor, from the video tier its Start named.
+ get liveView(): CameraLiveView {
+ return {
+ sensorUUID: this.context.sensorUUID,
+ sessionIdentifier: this.sessionIdentifier,
+ tierId: this.videoTier,
+ where: 'home',
+ }
+ }
+
+ armPrepareTimeout(): void {
+ this.prepareTimer = setTimeout(() => void this.exit('nobody started it within the prepare timeout'), PREPARE_TIMEOUT).unref()
+ this.stack.defer(() => clearTimeout(this.prepareTimer))
+ }
+
+ // The session's route for a failed tier: its exit, as for every other path that ends it.
+ tierFailed(): void {
+ void this.exit('its tier failed')
+ }
+
+ // Counts one send whose completion reported an error, on any of the session's media, and writes a debug event of the session's first. A flood writes
+ // no event per packet.
+ sendFailed(error: Error): void {
+ if (++this.failedSends === 1) {
+ const { message } = error
+
+ this.context.reporter.debug(MULTI_TIER_DEBUG, 'packet-send-failed', () => ({
+ message,
+ sentence: `Multi-tier session ${this.sessionIdentifier} failed to send a packet: ${message}`,
+ sessionIdentifier: this.sessionIdentifier,
+ }))
+ }
+ }
+
+ /* A successful Start moves its holds onto the session's stack, above the sockets and contexts its preparation put there: each tier releases the session
+ * before a context is zeroed or a socket closed. It stops the prepare timeout and starts the session's reading: each socket's datagrams read, and the
+ * sender reports scheduled, the timers' clears registered now so a report or the liveness window armed later registers nothing. The hold of the Start's
+ * picture, which a keyframe request goes to, is kept beside the senders, the picture's and the sound's, and as the session leaves each socket's listener
+ * is removed before the hold is cleared and the holds are released, which means no request reaches a released hold.
+ */
+ stream(holds: AsyncDisposableStack, videoTier: number, joined: SessionHold, ssrcs: Record): void {
+ this.stack.use(holds.move())
+ clearTimeout(this.prepareTimer)
+ this.state = 'streaming'
+ this.videoTier = videoTier
+ this.controllerSSRCs = ssrcs
+ this.tierHold = joined.hold
+ this.stack.defer(() => {
+ this.tierHold = undefined
+ })
+
+ for (const medium of MEDIA) {
+ const path = this.media[medium]
+ const listener = (datagram: Buffer): void => this.receive(medium, datagram)
+
+ path.sender = joined.senders[medium]
+ path.socket.on('message', listener)
+ this.stack.defer(() => {
+ path.socket.removeListener('message', listener)
+ path.sender = undefined
+ })
+ }
+
+ this.stack.defer(() => {
+ clearTimeout(this.reportTimer)
+ clearTimeout(this.livenessTimer)
+ })
+
+ // The talkback and send counts are read as the session ends, after the talkback's end releases what its talker registered, which stands above this on
+ // the stack once a sink is taken.
+ this.stack.defer(() => {
+ const dropped = this.refusedTalkback - 1
+ const unsent = this.failedSends - 1
+
+ if (dropped > 0) {
+ this.context.reporter.debug(MULTI_TIER_DEBUG, 'talkback-dropped', () => ({
+ dropped,
+ sentence: `Multi-tier session ${this.sessionIdentifier} dropped ${dropped} more ${nounFor(dropped, 'talkback datagram')}.`,
+ sessionIdentifier: this.sessionIdentifier,
+ }))
+ }
+
+ if (unsent > 0) {
+ this.context.reporter.debug(MULTI_TIER_DEBUG, 'packets-unsent', () => ({
+ sentence: `Multi-tier session ${this.sessionIdentifier} failed to send ${unsent} more ${nounFor(unsent, 'packet')}.`,
+ sessionIdentifier: this.sessionIdentifier,
+ unsent,
+ }))
+ }
+
+ this.sessionTalkback.logFailedWrites()
+ })
+ this.scheduleReport(FIRST_REPORT_DELAY)
+ }
+
+ // Ends the session through the session table's exit, for every path that ends it from outside the management's own commands.
+ async exit(reason: string): Promise {
+ await this.sessions.exit(this, reason)
+ }
+
+ /* The exit's disposal. Its opening in the session table removes the session and releases its connection's held answers, and guards the rest: a close, an
+ * End, a timeout or an error arriving while the exit runs finds the session gone, and a disposal that finds nothing to remove has run already. The
+ * answers go first: a read during the teardown answers the empty value. A streaming session's view ends in the same turn, ahead of every await, which is why
+ * the end of a removal reaches the camera's listeners before the controller drops them. The stack then releases everything in reverse: the talkback's
+ * end, releasing what its talker registered, and the talkback and send counts, written as debug events, the timers, the report listeners and the
+ * senders, the holds, a streaming session's or a waiting Start's, a demand ending with its last join, the contexts, zeroed, and the sockets, closed.
+ */
+ async [Symbol.asyncDispose](): Promise {
+ if (!this.sessions.beginDisposal(this)) {
+ return
+ }
+
+ this.controller.abort()
+
+ if (this.state === 'streaming') {
+ this.context.liveViewEnded?.(this.liveView)
+ }
+
+ await this.stack.disposeAsync()
+ }
+
+ /* Reads one datagram from the controller, RTCP and RTP told apart by RFC 5761 4. Every authenticated RTCP packet arms or restarts the liveness window,
+ * whatever it carries, and a picture loss indication or a full intra request on the video socket goes to the session's hold on its picture's tier, whose
+ * demand answers it for this session alone, from the camera buffer where it keeps a keyframe released, and writes one debug event with what it came to, a
+ * session whose hold has gone reading as stopped. RTP on the audio socket is the controller's talkback, which goes to its own method and never touches
+ * the liveness window, and RTP on the video socket is dropped.
+ */
+ private receive(medium: StreamTierMedium, datagram: Buffer): void {
+ if (datagram.length < 2) {
+ return
+ }
+
+ if (datagram[1] < RTCP_SECOND_OCTET_MINIMUM || datagram[1] > RTCP_SECOND_OCTET_MAXIMUM) {
+ if (medium === 'audio') {
+ this.talkback(datagram)
+ }
+
+ return
+ }
+
+ if (datagram.length - SRTCP_TRAILER_LENGTH > this.rtcp.length) {
+ const { length } = datagram
+
+ this.context.reporter.debug(MULTI_TIER_DEBUG, 'rtcp-too-long', () => ({
+ length,
+ medium,
+ sentence: `Multi-tier session ${this.sessionIdentifier} drops a ${medium} RTCP datagram of ${length} octets, longer than it reads.`,
+ sessionIdentifier: this.sessionIdentifier,
+ }))
+ return
+ }
+
+ const length = this.media[medium].inbound.unprotectRTCP(datagram, this.rtcp)
+
+ if (length === undefined) {
+ this.context.reporter.debug(MULTI_TIER_DEBUG, 'rtcp-refused', () => ({
+ medium,
+ sentence: `Multi-tier session ${this.sessionIdentifier} drops a ${medium} RTCP datagram that fails authentication or replays an index.`,
+ sessionIdentifier: this.sessionIdentifier,
+ }))
+ return
+ }
+
+ this.touchLiveness()
+
+ const keyframe = asksForKeyframe(this.rtcp, length)
+
+ if (keyframe === undefined) {
+ this.context.reporter.debug(MULTI_TIER_DEBUG, 'rtcp-malformed', () => ({
+ medium,
+ sentence: `Multi-tier session ${this.sessionIdentifier} drops a malformed ${medium} RTCP packet.`,
+ sessionIdentifier: this.sessionIdentifier,
+ }))
+ return
+ }
+
+ if (keyframe && medium === 'video') {
+ const outcome = this.tierHold?.answerKeyframeRequest() ?? 'stopped'
+
+ this.context.reporter.debug(MULTI_TIER_DEBUG, 'keyframe-request', () => ({
+ outcome,
+ sentence: `Multi-tier session ${this.sessionIdentifier} takes a keyframe request on video tier ${this.videoTier}: ${outcome}.`,
+ sessionIdentifier: this.sessionIdentifier,
+ tierId: this.videoTier,
+ }))
+ }
+ }
+
+ /* Hands one talkback datagram to the session's talkback. The checks that need no cryptography come first: nothing is read once the session's talkback is
+ * closed, the delegate having declined talkback or the talkback having ended, or once the session's exit began, and a datagram too short for an RTP
+ * header, of another payload type than the audio tier's, or from another SSRC than the one the controller's Start named for audio is dropped. The packet
+ * is then unprotected in place, in the buffer its datagram arrived in: the sink is written a view of that buffer, which it may keep, and the session
+ * copies nothing and keeps no reference. A refused datagram is left as it arrived. The camera's Speaker mute is read last, after the unprotect, which is why a
+ * muted packet still moves the SRTP index as the controller's does and the first packet after a mute reads under the right rollover counter, while the
+ * muted packet itself is dropped and starts no sink. The talkback starts the sink at the first packet that authenticates while the Speaker is unmuted and
+ * guards every write, since the sink is plugin code running inside a socket listener. The talkback's end, which releases what its talker registered,
+ * stands on the stack above the socket listeners: every path that ends the session runs it while they stand.
+ */
+ private talkback(datagram: Buffer): void {
+ if (this.sessionTalkback.closed || this.signal.aborted || datagram.length < RTP_HEADER_LENGTH
+ || (datagram[1] & RTP_PAYLOAD_TYPE_MASK) !== this.context.audioPayloadType || datagram.readUInt32BE(8) !== this.controllerSSRCs?.audio) {
+ return
+ }
+
+ const length = this.media.audio.inbound.unprotect(datagram, datagram)
+
+ if (length === undefined) {
+ if (++this.refusedTalkback === 1) {
+ this.context.reporter.debug(MULTI_TIER_DEBUG, 'talkback-refused', () => ({
+ sentence: `Multi-tier session ${this.sessionIdentifier} drops a talkback datagram too short for its header and tag, longer than it reads, `
+ + 'replaying an index or failing authentication.',
+ sessionIdentifier: this.sessionIdentifier,
+ }))
+ }
+
+ return
+ }
+
+ if (this.context.speakerMuted()) {
+ return
+ }
+
+ this.sessionTalkback.write(datagram.subarray(0, length))
+ }
+
+ // The liveness window arms at the controller's first authenticated RTCP packet and restarts at each later one. A controller that reports and then falls
+ // silent ends its session, and one that never reports streams until its End, its connection's close, its tier's failure or the camera turning off.
+ private touchLiveness(): void {
+ if (this.livenessTimer) {
+ this.livenessTimer.refresh()
+ return
+ }
+
+ this.livenessTimer = setTimeout(() => void this.exit('its controller sent no RTCP within the liveness window'), LIVENESS_WINDOW).unref()
+ }
+
+ /* Each turn reads the steady clock once, which every report's RTP timestamp advances by, and the time of day once, for the one thing it serves: the NTP
+ * time each report states, the same for every medium's report of the turn. A correction of the time of day moves the NTP time alone.
+ */
+ private scheduleReport(delay: number): void {
+ this.reportTimer = setTimeout(() => {
+ const moment = performance.now()
+ const ntp = ntpTime(Date.now())
+
+ for (const medium of MEDIA) {
+ this.media[medium].sender?.report(moment, ntp)
+ }
+
+ this.scheduleReport(reportInterval())
+ }, delay).unref()
+ }
+}
+
+/**
+ * Serves one video sensor's Camera Multi-Tier RTP Stream Management service. It prepares each session on its own sockets and SRTP contexts, holds it in a
+ * session table that ties it to the connection that opened it, starts and ends it, holds its video tier's picture and sound in the sensor's tier table and
+ * sends it, under its own key and SSRC, every packet the tier's stream makes, its sound under the audio tier's payload type while the camera's Microphone
+ * is unmuted, reads each controller's RTCP and sends it sender reports, and writes each controller's talkback to a sink the delegate gives that session
+ * while the camera's Speaker is unmuted. The tier table reads each video tier's stream, times its picture and its sound on the sensor's one clock, cuts
+ * them into packets and reports each tier's demand to the delegate, which runs one encoding for each video tier as demand comes and goes and never sees a
+ * session. Its Status Active is the policy's, and its Streaming Enabled is its own.
+ *
+ * Where the sensor's audio states its source `'shared'`, a session of a tier other than the sensor's sound tier holds its own tier for its picture and the
+ * sound tier for its sound alone, through a hold of its own. It starts and runs on its own tier, its sound joining as the sound tier runs, which runs for
+ * it where nothing else holds it, and it goes on silent until it is opened again where the sound tier is refused, cut or fails, the failure told as that
+ * tier's own problem.
+ *
+ * Both control points are transient by their definitions: a writer's last answer reaches it in the write response and on its plain reads alone, until its
+ * session ends, the service is destroyed or reset, or the camera is switched off or goes out of service. The service runs its writes one at a time. A
+ * capacity check, the change to the session table and the answer are atomic across the delegate's awaits. A malformed write, or one a plugin makes without
+ * a connection, fails with `INVALID_VALUE_IN_REQUEST`, and a Setup Endpoints write while the camera is out of service fails with the communication failure,
+ * `SERVICE_COMMUNICATION_FAILURE`.
+ */
+export class MultiTierStreamManagement {
+ /**
+ * The service's key, in the camera's service map and in the policy alike.
+ * @private
+ */
+ readonly serviceKey: string
+ private readonly policy: OperatingModePolicy
+ private readonly sensorUUID: string
+ private readonly maxSessions: number
+ private readonly service: CameraMultiTierRTPStreamManagement
+ private readonly table: TierTable
+ private readonly streamingEnabled: StreamingEnabledSwitch
+ private readonly queue = new CommandQueue()
+ private readonly sessions: ConnectionSessions
+ private readonly context: MultiTierSessionContext
+ // The camera's reporter's debug events on the service's debug name, which the session table and each control point write through as well.
+ private readonly debug: DebugWriter
+ // The hook a session's view is told of through as its Start is answered with success.
+ private readonly onLiveViewStarted?: (view: CameraLiveView) => void
+ // The payload type each medium's packets carry: the video tiers' for picture and the audio tier's for sound, whichever video tier the sound comes from.
+ private readonly payloadTypes: Readonly>
+
+ /**
+ * Adopts the saved service or builds one, and sets its static characteristics. The options arrive validated by the camera's streaming options.
+ * @param options - The service's options.
+ * @param policy - The camera's operating-mode policy, which derives the service's Status Active.
+ * @param service - A saved service to adopt, which keeps its Streaming Enabled.
+ */
+ constructor(options: MultiTierStreamManagementOptions, policy: OperatingModePolicy, service?: CameraMultiTierRTPStreamManagement) {
+ const { delegate, maxSessions, onLiveViewEnded, onLiveViewStarted, onStreamingEnabledChange, reporter, speakerMuted, table } = options
+ const { audioStreamTiers, videoStreamTiers } = table.streamTiers
+
+ this.policy = policy
+ this.sensorUUID = table.sensorUUID
+ this.serviceKey = MultiTierStreamManagement.serviceKey(this.sensorUUID)
+ this.maxSessions = maxSessions
+ this.table = table
+ this.onLiveViewStarted = onLiveViewStarted
+ this.context = {
+ audioPayloadType: audioStreamTiers.payloadType,
+ talkbackStarted: talker => delegate.talkbackStarted?.(talker),
+ speakerMuted,
+ reporter,
+ sensorUUID: this.sensorUUID,
+ liveViewEnded: onLiveViewEnded,
+ }
+ this.debug = reporter.writer(MULTI_TIER_DEBUG)
+ this.payloadTypes = { video: videoStreamTiers.payloadType, audio: audioStreamTiers.payloadType }
+ this.service = service ?? MultiTierStreamManagement.constructService(this.sensorUUID)
+ this.sessions = new ConnectionSessions(this.service, this.debug, 'multi-tier')
+ this.streamingEnabled = new StreamingEnabledSwitch(this.service.getCharacteristic(Characteristic.StreamingEnabled), this.sensorUUID, 'home', onStreamingEnabledChange)
+
+ this.service.updateCharacteristic(Characteristic.SensorUUID, uuid.write(this.sensorUUID).toString('base64'))
+ this.service.updateCharacteristic(Characteristic.SupportedVideoStreamTiers, encodeSupportedVideoStreamTiers(videoStreamTiers))
+ this.service.updateCharacteristic(Characteristic.SupportedAudioStreamTiers, encodeSupportedAudioStreamTiers(audioStreamTiers))
+ this.service.updateCharacteristic(Characteristic.SupportedRTPConfiguration, SUPPORTED_RTP_CONFIGURATION)
+ this.setupServiceHandlers()
+ }
+
+ /**
+ * The key a video sensor's service carries in the camera's service map and in the policy.
+ * @param sensorUUID - The video sensor's UUID.
+ * @returns The capability prefix, `multiTierStream:` and the UUID in lowercase.
+ * @private
+ */
+ static serviceKey(sensorUUID: string): string {
+ return sensorServiceKey('multiTierStream', sensorUUID)
+ }
+
+ /**
+ * Reconciles every video sensor's service in a restored service map, in the order given: a sensor's saved service under its key is adopted, and a sensor
+ * without one gets a new service, inserted. The key of a sensor missing from the camera's inventory is left to the capability key sweep.
+ * @param serviceMap - The camera's service map, changed in place.
+ * @param sensors - Each video sensor's options, in the camera's order.
+ * @param create - Builds a sensor's management over its saved service, or over a new one when it is given none.
+ * @returns Whether the map changed.
+ * @private
+ */
+ static reconcile(
+ serviceMap: ControllerServiceMap,
+ sensors: readonly MultiTierStreamManagementOptions[],
+ create: (options: MultiTierStreamManagementOptions, service?: CameraMultiTierRTPStreamManagement) => MultiTierStreamManagement,
+ ): boolean {
+ return reconcileSensorServices(
+ serviceMap,
+ sensors,
+ options => MultiTierStreamManagement.serviceKey(options.table.sensorUUID),
+ (options, service?: CameraMultiTierRTPStreamManagement) => create(options, service).getService(),
+ )
+ }
+
+ /**
+ * The Camera Multi-Tier RTP Stream Management service.
+ * @returns The service.
+ */
+ getService(): CameraMultiTierRTPStreamManagement {
+ return this.service
+ }
+
+ /**
+ * Binds the service's Streaming Enabled into the policy and subscribes whether the service may stream and its Status Active, once the camera's services
+ * are configured. It writes no Status Active, which {@link writeStatusActive} writes once the camera's restore has run.
+ * @private
+ */
+ configureServices(): void {
+ this.policy.bindStreamingEnabled(this.serviceKey, this.service.getCharacteristic(Characteristic.StreamingEnabled))
+ this.policy.subscribeDerivation('streamOpen', this.streamOpenChanged, this.serviceKey)
+ this.policy.subscribeDerivation('statusActive', this.statusActiveChanged, this.serviceKey)
+
+ // The listener comes after the bind: the policy's listener, and with it the release and the session end, runs ahead of the state-change delegate, whose
+ // throw would otherwise leave a disabled service's answers held and its sessions live.
+ this.streamingEnabled.listen()
+ }
+
+ /**
+ * Writes the service's Status Active from the policy as it stands, which the camera controller calls at the first context its accessory hands it in
+ * each configuration, after the restore. A derivation tells its listeners only when it moves, which is why this write carries the value it held before its first
+ * move, and each later move reaches the service through the subscription.
+ * @private
+ */
+ writeStatusActive(): void {
+ this.service.updateCharacteristic(Characteristic.StatusActive, this.policy.statusActive(this.serviceKey))
+ }
+
+ /**
+ * The state to persist.
+ * @returns The value of Streaming Enabled.
+ * @private
+ */
+ serialize(): MultiTierStreamManagementState {
+ return {
+ streamingEnabled: this.streamingEnabled.value,
+ }
+ }
+
+ /**
+ * Restores persisted state, applying its Streaming Enabled when it is a boolean.
+ * @param state - The persisted state.
+ * @private
+ */
+ deserialize(state: MultiTierStreamManagementState): void {
+ this.streamingEnabled.restore(state.streamingEnabled)
+ }
+
+ /**
+ * Sets the delegate a change of Streaming Enabled calls, which is how the owner persists it.
+ * @param delegate - The delegate, or `undefined` to clear it.
+ * @private
+ */
+ setupStateChangeDelegate(delegate?: StateChangeDelegate): void {
+ this.streamingEnabled.setupStateChangeDelegate(delegate)
+ }
+
+ /**
+ * Releases every answer the control points hold, ends every session, withdraws each tier demand still pending, refusing every join waiting on it, and
+ * restores Streaming Enabled to its default, true.
+ */
+ handleFactoryReset(): void {
+ void this.endAllSessionsAndDemands()
+ this.streamingEnabled.reset()
+ }
+
+ /**
+ * Ends a session. An identifier no registered session carries is ignored.
+ * @param sessionIdentifier - The session's identifier.
+ */
+ async endSession(sessionIdentifier: string): Promise {
+ await this.sessions.end(sessionIdentifier, ENDED_BY_OWNER)
+ }
+
+ /**
+ * Ends every session, releases every answer the control points hold, withdraws each tier demand still pending, refusing every join waiting on it, and
+ * answers each later write without a session, before the service is dropped.
+ */
+ async destroy(): Promise {
+ this.sessions.markDestroyed()
+ await this.endAllSessionsAndDemands()
+ }
+
+ // A service this class builds is keyed by the sensor's UUID, in lowercase, and the sensor's identity and not its position binds it.
+ private static constructService(subtype: string): CameraMultiTierRTPStreamManagement {
+ const service = new Service.CameraMultiTierRTPStreamManagement('', subtype)
+ service.updateCharacteristic(Characteristic.StreamingEnabled, true)
+
+ return service
+ }
+
+ private setupServiceHandlers(): void {
+ // A read answers the policy at once, and it is right even for a change no derivation hears, such as a direct assignment to a projection's value.
+ this.service.getCharacteristic(Characteristic.StatusActive).onGet(() => this.policy.statusActive(this.serviceKey))
+
+ // R15 9.75 answers a read before any write with Error, naming no session; a writer's held answer is served ahead of this handler.
+ this.service.getCharacteristic(Characteristic.SetupEndpoints).onGet(() => SETUP_ENDPOINTS_ERROR)
+
+ wireControlPoint(
+ this.service.getCharacteristic(Characteristic.SetupEndpoints),
+ this.queue,
+ this.debug,
+ decodeSetupEndpointsRequest,
+ this.setupEndpoints.bind(this),
+ encodeSetupEndpointsResponse,
+ )
+ wireControlPoint(
+ this.service.getCharacteristic(Characteristic.RTPStreamingControl),
+ this.queue,
+ this.debug,
+ decodeRTPStreamingControlRequest,
+ this.streamingControl.bind(this),
+ encodeRTPStreamingControlResponse,
+ )
+ }
+
+ // The policy tells this listener each time the service's gate opens or closes. A gate that closes, the camera switched off or out of service, releases
+ // every connection's answers and ends every session through the session table, its promise voided, which is why nothing throws into the write or the statement
+ // that closed it.
+ private readonly streamOpenChanged = (open: boolean): void => {
+ if (!open) {
+ void this.sessions.endAll(ENDED_BY_OWNER)
+ }
+ }
+
+ // The policy tells this listener each time the service's Status Active moves, which the user's switches and its own Streaming Enabled alone move, after
+ // the gate's listener has ended the sessions of a switch-off.
+ private readonly statusActiveChanged = (active: boolean): void => {
+ this.service.updateCharacteristic(Characteristic.StatusActive, active)
+ }
+
+ /* Whether a Setup Endpoints write may prepare a session, read at its first check and at its re-check after the sockets bind: false while the camera is
+ * switched off, which the write answers with its own refusal, and a throw of the communication failure while the camera is out of service, which fails
+ * the write with that status, after one debug event of its own.
+ */
+ private setupOpen(): boolean {
+ const gate = this.policy.streamGate(this.serviceKey)
+
+ if (gate === 'out of service') {
+ this.debug('setup-out-of-service', () => ({
+ sentence: 'Setup Endpoints fails with the communication failure while the camera is out of service.',
+ }))
+ throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ }
+
+ return gate === 'open'
+ }
+
+ /* Ends every session and withdraws each tier demand whose start is still pending in the same turn, while the exits run and before a later write can hold
+ * one: a delegate whose start has not settled hears through its start's signal at the reset or the destroy itself that the library stops waiting, not
+ * at the start's own bound, and a Start that was waiting on it finds its session gone and answers Unknown Session Identifier.
+ */
+ private async endAllSessionsAndDemands(): Promise {
+ const ended = this.sessions.endAll(ENDED_BY_OWNER)
+
+ this.table.withdraw('when its service ended every session: the demand is withdrawn and every join waiting on it is refused')
+ await ended
+ }
+
+ // Whether a live session of the management carries an SSRC, on either medium.
+ private carries(ssrc: number): boolean {
+ return this.sessions.identifiers().some((sessionIdentifier) => {
+ const media = this.sessions.get(sessionIdentifier)!.media
+
+ return media.video.ssrc === ssrc || media.audio.ssrc === ssrc
+ })
+ }
+
+ // A random 32-bit SSRC (RFC 3550 8.1) no live session of the management carries and other than the session's other SSRC.
+ private freshSSRC(other?: number): number {
+ for (;;) {
+ const ssrc = crypto.randomBytes(4).readUInt32BE(0)
+
+ if (ssrc !== other && !this.carries(ssrc)) {
+ return ssrc
+ }
+ }
+ }
+
+ private async setupEndpoints(request: SetupEndpointsRequest, connection: HAPConnection): Promise {
+ const { audioSRTPParameters, sessionIdentifier, videoSRTPParameters } = request
+ const refuse = (status: SetupEndpointsStatus.BUSY | SetupEndpointsStatus.ERROR, reason: string): SetupEndpointsResponse => {
+ this.debug('setup-refused', () => ({
+ reason,
+ sentence: `Refusing Setup Endpoints for multi-tier session ${sessionIdentifier}: ${reason}`,
+ sessionIdentifier,
+ }))
+
+ return { status, sessionIdentifier }
+ }
+
+ if (!this.sessions.serves(connection)) {
+ return refuse(SetupEndpointsStatus.ERROR, 'the management no longer serves its connection.')
+ }
+
+ if (videoSRTPParameters.cryptoSuite !== SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80 || audioSRTPParameters.cryptoSuite !== SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80) {
+ return refuse(SetupEndpointsStatus.ERROR, 'it names an SRTP suite other than AES_CM_128_HMAC_SHA1_80.')
+ }
+
+ // The contexts stand on this stack until the session registers, and every answer short of success zeroes what they derived.
+ using contexts = new DisposableStack()
+ let inbound: Record
+
+ try {
+ inbound = {
+ video: contexts.use(new SRTPContext(videoSRTPParameters.masterKey, videoSRTPParameters.masterSalt)),
+ audio: contexts.use(new SRTPContext(audioSRTPParameters.masterKey, audioSRTPParameters.masterSalt)),
+ }
+ } catch (error) {
+ return refuse(SetupEndpointsStatus.ERROR, errorMessage(error))
+ }
+
+ // A session that cannot start binds no socket: a camera switched off answers Error, and one out of service fails the write.
+ if (!this.setupOpen()) {
+ return refuse(SetupEndpointsStatus.ERROR, 'Status Active is false.')
+ }
+
+ const held = this.sessions.get(sessionIdentifier)
+
+ if (held && (held.connection !== connection || held.state === 'streaming')) {
+ return refuse(SetupEndpointsStatus.ERROR, 'another connection\'s session, or a streaming one, holds its identifier.')
+ }
+
+ // A connection that prepares again replaces the prepared sessions it holds, what the hubs do when their tile asks again, its own identifier's among them.
+ await Promise.all(this.sessions.identifiers()
+ .map(identifier => this.sessions.get(identifier)!)
+ .filter(session => session.connection === connection && session.state === 'prepared')
+ .map(async session => this.sessions.exit(session, 'its connection prepared another session')))
+
+ if (this.sessions.size >= this.maxSessions) {
+ return refuse(SetupEndpointsStatus.BUSY, `the service holds its most sessions, ${this.maxSessions}.`)
+ }
+
+ return await this.prepare(request, connection, contexts, inbound)
+ }
+
+ /* Prepares a session: two sockets on the controller's address family, bound at port 0 on its wildcard, which means a scoped IPv6 address never reaches a bind, and
+ * connected to the controller's ports; the accessory's own master key and salt and a fresh SSRC per medium; and the contexts. The served and destroyed
+ * reads and the service's gate are taken again in the synchronous turn that registers the session, because the binds await. A camera out of service
+ * by then fails the write and its sockets close.
+ */
+ private async prepare(
+ request: SetupEndpointsRequest,
+ connection: HAPConnection,
+ contexts: DisposableStack,
+ inbound: Record,
+ ): Promise {
+ const { audioSRTPParameters, controllerAddress, sessionIdentifier, videoSRTPParameters } = request
+ const { addressVersion } = controllerAddress
+ const refused = (reason: string): SetupEndpointsResponse => {
+ this.debug('setup-refused', () => ({
+ reason,
+ sentence: `Refusing Setup Endpoints for multi-tier session ${sessionIdentifier}: ${reason}`,
+ sessionIdentifier,
+ }))
+
+ return { status: SetupEndpointsStatus.ERROR, sessionIdentifier }
+ }
+
+ let address: string
+
+ try {
+ address = connection.getLocalAddress(addressVersion)
+ } catch (error) {
+ return refused(errorMessage(error))
+ }
+
+ // The sockets stand on this stack until the session registers, and every answer short of success closes them.
+ await using pending = new AsyncDisposableStack()
+ let session: MultiTierSession | undefined
+
+ // A connected socket reports a controller's closed port as an error, which ends the session it carries.
+ const failed = (error: Error): void => {
+ const { message } = error
+
+ this.debug('socket-error', () => ({
+ message,
+ sentence: `A socket of multi-tier session ${sessionIdentifier} reports an error: ${message}`,
+ sessionIdentifier,
+ }))
+
+ if (session) {
+ void session.exit('its socket reported an error')
+ }
+ }
+
+ const type: SocketType = addressVersion === 'ipv6'
+ ? 'udp6'
+ : 'udp4'
+ const wildcard = addressVersion === 'ipv6'
+ ? '::'
+ : '0.0.0.0'
+ const sockets: Record = {
+ video: pending.adopt(dgram.createSocket(type), close),
+ audio: pending.adopt(dgram.createSocket(type), close),
+ }
+
+ if (!(await Promise.all(MEDIA.map(async medium => bind(sockets[medium], wildcard, failed)))).every(Boolean)) {
+ return refused('a socket failed to bind.')
+ }
+
+ const ports: Record = { video: controllerAddress.videoRTPPort, audio: controllerAddress.audioRTPPort }
+
+ if (!(await Promise.all(MEDIA.map(async medium => connect(sockets[medium], ports[medium], controllerAddress.address)))).every(Boolean)) {
+ return refused('a socket failed to connect to the controller.')
+ }
+
+ const keys: Record = {
+ video: masterKeyAndSalt(),
+ audio: masterKeyAndSalt(),
+ }
+ const videoSSRC = this.freshSSRC()
+ const audioSSRC = this.freshSSRC(videoSSRC)
+ const media: Record = {
+ video: {
+ socket: sockets.video,
+ outbound: contexts.use(new SRTPContext(keys.video.masterKey, keys.video.masterSalt)),
+ inbound: inbound.video,
+ ssrc: videoSSRC,
+ },
+ audio: {
+ socket: sockets.audio,
+ outbound: contexts.use(new SRTPContext(keys.audio.masterKey, keys.audio.masterSalt)),
+ inbound: inbound.audio,
+ ssrc: audioSSRC,
+ },
+ }
+
+ if (!this.sessions.serves(connection) || !this.setupOpen()) {
+ return refused('its connection closed, the management was destroyed or its gate read switched off while its sockets bound.')
+ }
+
+ // The session is registered before it takes over the sockets and the contexts, and before the socket error listener can end it: a registration that
+ // throws leaves them on the stacks that release them.
+ const prepared = new MultiTierSession(sessionIdentifier, connection, media, this.sessions, this.context)
+ this.sessions.add(prepared)
+ session = prepared
+ pending.use(contexts.move())
+ prepared.hold(pending)
+ prepared.armPrepareTimeout()
+
+ const accessoryAddress = {
+ addressVersion,
+ address,
+ videoRTPPort: sockets.video.address().port,
+ audioRTPPort: sockets.audio.address().port,
+ }
+
+ // The keys and salts are secrets and debug output is often shared in public, which is why the event names each one's length and never its bytes.
+ this.debug('session-prepared', () => {
+ const suite = SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80
+ const keyLengths = [videoSRTPParameters.masterKey.length, audioSRTPParameters.masterKey.length]
+ const saltLengths = [videoSRTPParameters.masterSalt.length, audioSRTPParameters.masterSalt.length]
+
+ return {
+ accessoryAddress: address,
+ accessoryPorts: [accessoryAddress.videoRTPPort, accessoryAddress.audioRTPPort],
+ controllerAddress: controllerAddress.address,
+ controllerPorts: [ports.video, ports.audio],
+ keyLengths,
+ saltLengths,
+ sentence: `Prepared multi-tier session ${sessionIdentifier} from ${controllerAddress.address} ports ${ports.video} and ${ports.audio} on ${address} `
+ + `ports ${accessoryAddress.videoRTPPort} and ${accessoryAddress.audioRTPPort}, suite ${suite}, controller key lengths ${keyLengths[0]} and `
+ + `${keyLengths[1]} and salt lengths ${saltLengths[0]} and ${saltLengths[1]}.`,
+ sessionIdentifier,
+ suite,
+ }
+ })
+
+ return {
+ status: SetupEndpointsStatus.SUCCESS,
+ sessionIdentifier,
+ accessoryAddress,
+ videoSRTPParameters: { cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, ...keys.video },
+ audioSRTPParameters: { cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, ...keys.audio },
+ videoSSRC,
+ audioSSRC,
+ }
+ }
+
+ private async streamingControl(request: RTPStreamingControlRequest, connection: HAPConnection): Promise {
+ const { sessionIdentifier } = request
+ const session = this.sessions.liveSession(sessionIdentifier, connection)
+
+ if (!session) {
+ return { sessionIdentifier, status: RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER }
+ }
+
+ if (request.command === RTPStreamingCommand.START) {
+ return await this.start(session, request)
+ }
+
+ // An End of a session that never started answers No Such Stream, and the session ends either way.
+ const streaming = session.state === 'streaming'
+ await this.sessions.exit(session, 'its controller ended it')
+
+ return {
+ sessionIdentifier,
+ status: streaming
+ ? RTPStreamingStatus.SUCCESS
+ : RTPStreamingStatus.NO_SUCH_STREAM,
+ }
+ }
+
+ private async start(
+ session: MultiTierSession,
+ request: Extract,
+ ): Promise {
+ const { sessionIdentifier } = session
+ const answer = (status: RTPStreamingStatus): RTPStreamingControlResponse => ({ sessionIdentifier, status })
+ const { audioTier } = this.table
+ const videoTier = this.table.videoTiers.get(request.videoTier)
+
+ if (session.state === 'streaming' || !this.policy.streamOpen(this.serviceKey) || !videoTier || request.audioTier !== audioTier.tierId) {
+ return answer(RTPStreamingStatus.ERROR)
+ }
+
+ // The joins' holds stand on this Start's own stack until it succeeds: a Start answered busy leaves no tier holding the session, and a retried Start
+ // joins anew. The session reaches that stack before the joins, which is why a session that ends while its Start waits releases the joins, and its senders, above
+ // its contexts and sockets. A join that raises a demand runs plugin code, the demand's start, and that code can end the session. A join made as the
+ // session's signal aborted is released at once.
+ await using holds = new AsyncDisposableStack()
+
+ session.reach(holds)
+
+ const joined = this.hold(holds, session, videoTier)
+
+ if (joined === undefined) {
+ return answer(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ }
+
+ const { hold } = joined
+
+ // The picture's demand still waiting on its start is waited for within the session's exit alone, since the start's own bound withdraws a start that never
+ // settles and refuses every join waiting on it, and a sound taken from the sensor's sound tier is never waited for: it holds back no view. A session
+ // gone once the wait is over, which a wait its session's signal cut always finds, a failed tier among the ways, answers Unknown Session Identifier. A
+ // wait answered anything but started, a refused start or one a withdrawal cut, its bound's among them, answers Busy with no report of the management's
+ // own and leaves the session prepared, which means a call that never settles releases the service's queue. A hold no wait answers reads its demand as it stands.
+ const started = hold.waiting
+ ? (await settleWithin(hold.answer(), session.signal))?.value === 'started'
+ : hold.started
+
+ if (!this.sessions.holds(session)) {
+ return answer(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER)
+ }
+
+ if (!started) {
+ return answer(RTPStreamingStatus.BUSY)
+ }
+
+ session.stream(
+ holds,
+ request.videoTier,
+ joined,
+ { video: request.videoSSRC, audio: request.audioSSRC },
+ )
+ this.onLiveViewStarted?.(session.liveView)
+
+ return answer(RTPStreamingStatus.SUCCESS)
+ }
+
+ /* Joins a video tier for a session's picture and its sound in one step, its hold's release on the Start's stack, before the Start waits, which is why a stream the
+ * plugin writes while the tier's demand is starting reaches the session that raised it as the tier's pacer releases it, its picture and its sound alike.
+ * The table raises the demand when the tier has none, decides its packet size from the listening family of the session's HAP server when no session is
+ * joined, and makes the session's sender of each medium for that size, under that medium's payload type, before it calls the delegate for a demand it
+ * raised, a join into a running demand calling it for nothing. A join into a tier whose buffer keeps a keyframe the pacer has released opens its picture
+ * from the latest such keyframe, handed across the pacer's turns as the live edge reaches each picture and while it fits its sender's room, while its
+ * sound joins the live releases at once, and a join into a tier whose buffer keeps no such keyframe has its picture start at the stream's next keyframe.
+ *
+ * A tier whose sound the sensor takes from its sound tier is joined for its picture alone, and the sound tier then for the sound alone, through a sound
+ * holder of the session's own, its release on the Start's stack beside the picture's: the sound tier's failure ends the sound and never the view, and
+ * a sound tier whose demand failed before the join is released at once, the view silent from its start. The answer carries the picture's hold, which
+ * the Start waits on and a keyframe request goes to, and a sender of each medium from the join that took it. Each join whose plugin code ended the
+ * session finds the Start's stack swept by the session's exit already, a join made before it released by that sweep, which means its hold is released at once
+ * and the join answers none.
+ */
+ private hold(holds: AsyncDisposableStack, session: MultiTierSession, tier: Tier): SessionHold | undefined {
+ const senders: Partial> = {}
+ const joining = (medium: StreamTierMedium, packetSize: number): TierSender => {
+ const sender = new TierSender(session, session.media[medium], this.payloadTypes[medium], CLOCK_RATES[medium], packetSize, POOL_SIZES[medium],
+ POOL_CEILINGS[medium])
+
+ senders[medium] = sender
+
+ return sender
+ }
+ const soundTier = this.table.soundTierOf(tier)
+ const apart = soundTier !== tier
+ const hold = this.table.join(tier, session, session.connection, apart
+ ? PICTURE
+ : MEDIA, joining)
+
+ if (session.signal.aborted) {
+ hold.release()
+
+ return undefined
+ }
+
+ holds.defer(() => hold.release())
+
+ if (apart) {
+ const holder = new SoundHolder()
+ const sound = this.table.join(soundTier, holder, session.connection, SOUND, joining)
+
+ holder.hold = sound
+
+ if (session.signal.aborted) {
+ sound.release()
+
+ return undefined
+ }
+
+ holds.defer(() => sound.release())
+
+ // A demand that failed before this join, which another holder still keeps, calls this holder's route for no failure, the route having run for the
+ // holds that stood then. The sound's hold is released here. The failed tier is left to its other holders and the view goes on silent.
+ if (!sound.waiting && !sound.started) {
+ sound.release()
+ }
+ }
+
+ return { hold, senders: senders as Record }
+ }
+}
diff --git a/src/lib/camera/OperatingModePolicy.spec.ts b/src/lib/camera/OperatingModePolicy.spec.ts
new file mode 100644
index 000000000..42155aeda
--- /dev/null
+++ b/src/lib/camera/OperatingModePolicy.spec.ts
@@ -0,0 +1,1147 @@
+import type { Mock } from 'vitest'
+
+import type { WithUUID } from '../../types.js'
+import type { CameraGlobalOperatingMode, CameraOperatingMode, CameraRecordingManagement } from '../definitions/index.js'
+import type { HAPConnection } from '../util/eventedhttp.js'
+import type { OperatingModeChange, OperatingModeField, OperatingModeState } from './OperatingModePolicy.js'
+
+import { describe, expect, it, vi } from 'vitest'
+
+import { Access, Characteristic, CharacteristicEventTypes } from '../Characteristic.js'
+import { Service, ServiceEventTypes } from '../Service.js'
+import { OperatingModePolicy } from './OperatingModePolicy.js'
+
+import '../definitions/index.js'
+
+// The policy's rows run over real services and no controller. Each one reads the policy's own bindings, refresh and derivations.
+interface Camera {
+ policy: OperatingModePolicy
+ recordingManagement: CameraRecordingManagement
+ operatingMode: CameraOperatingMode
+ global: CameraGlobalOperatingMode
+ changes: OperatingModeChange[]
+ saves: Mock
+}
+
+const HUB = {} as HAPConnection
+
+const PERSISTED_SLICE: OperatingModeState = {
+ recordingActive: false,
+ recordingAudioActive: false,
+ eventSnapshotsActive: true,
+ homeKitCameraActive: true,
+ periodicSnapshotsActive: true,
+}
+
+// The services a recording camera and the global service start with, each characteristic at its field's default.
+function services(): Pick {
+ const recordingManagement = new Service.CameraRecordingManagement('', '')
+ recordingManagement.setCharacteristic(Characteristic.Active, false)
+ recordingManagement.setCharacteristic(Characteristic.RecordingAudioActive, false)
+
+ const operatingMode = new Service.CameraOperatingMode('', '')
+ operatingMode.setCharacteristic(Characteristic.EventSnapshotsActive, true)
+ operatingMode.setCharacteristic(Characteristic.HomeKitCameraActive, true)
+ operatingMode.setCharacteristic(Characteristic.PeriodicSnapshotsActive, true)
+
+ const global = new Service.CameraGlobalOperatingMode('', '')
+ global.setCharacteristic(Characteristic.HomeKitCameraActive, true)
+ global.setCharacteristic(Characteristic.StreamingEnabled, true)
+ global.setCharacteristic(Characteristic.CameraOperatingModeIndicator, true)
+
+ return { recordingManagement, operatingMode, global }
+}
+
+// A policy bound to the recording services and, unless a row leaves it out, the global service, its hook and its delegate recorded, the hook handing each
+// change it records to the row's reaction with the camera: a row reads the policy or writes a characteristic as each change arrives.
+function camera(
+ withGlobal = true,
+ prepare: (camera: Omit) => void = () => undefined,
+ react: (change: OperatingModeChange, camera: Camera) => void = () => undefined,
+): Camera {
+ const changes: OperatingModeChange[] = []
+ const saves = vi.fn()
+ const bound = services()
+ const made: Camera = {
+ policy: new OperatingModePolicy({
+ fieldChanged: (change) => {
+ changes.push(change)
+ react(change, made)
+ },
+ }),
+ changes,
+ saves,
+ ...bound,
+ }
+
+ prepare(bound)
+ made.policy.setupStateChangeDelegate(saves)
+ made.policy.bindRecording(bound.recordingManagement, bound.operatingMode)
+ if (withGlobal) {
+ made.policy.bindGlobalOperatingMode(bound.global)
+ }
+
+ return made
+}
+
+// Gives the legacy and the global operating-mode services every field characteristic each can carry before the policy binds them, getCharacteristic adding
+// each one absent.
+function addEveryOptional({ operatingMode, global }: Pick): void {
+ for (const optional of [
+ Characteristic.CameraOperatingModeIndicator,
+ Characteristic.ManuallyDisabled,
+ Characteristic.NightVision,
+ Characteristic.ThirdPartyCameraActive,
+ ]) {
+ operatingMode.getCharacteristic(optional)
+ global.getCharacteristic(optional)
+ }
+}
+
+// The listeners on each service and on each of its characteristics, the ones the services add for themselves among them, in a fixed order.
+function listenerCounts(...services: Service[]): number[] {
+ return services.flatMap(service => [
+ service.listenerCount(ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE),
+ ...service.characteristics.map(characteristic => characteristic.listenerCount(CharacteristicEventTypes.CHANGE)),
+ ])
+}
+
+describe('operating-mode policy', () => {
+ it('reads an unprojected field as its default through a restore, and serializes nothing for a slice without a global field', () => {
+ const changes: OperatingModeChange[] = []
+ const saves = vi.fn()
+ const policy = new OperatingModePolicy({
+ fieldChanged: change => changes.push(change),
+ })
+ policy.setupStateChangeDelegate(saves)
+
+ policy.restore({
+ ...PERSISTED_SLICE,
+ recordingActive: true,
+ homeKitCameraActive: false,
+ })
+
+ expect(policy.homeKitCameraActive).toBe(true)
+ expect(policy.recordingActive).toBe(false)
+ expect(policy.serialize()).toBeUndefined()
+ expect(changes).toEqual([])
+ expect(saves).not.toHaveBeenCalled()
+ })
+
+ it('reads a field with one projection through it, a direct assignment included', () => {
+ const { policy, operatingMode } = camera(false)
+
+ operatingMode.getCharacteristic(Characteristic.HomeKitCameraActive).value = Characteristic.HomeKitCameraActive.OFF
+
+ expect(policy.homeKitCameraActive).toBe(false)
+ })
+
+ it('seeds the stored value from the first projection at the second bind and refreshes a disagreeing second to it, telling no one', () => {
+ const subscriber = vi.fn()
+ const { policy, global, changes, saves } = camera(false, ({ operatingMode, global }) => {
+ operatingMode.getCharacteristic(Characteristic.HomeKitCameraActive).value = Characteristic.HomeKitCameraActive.OFF
+ global.getCharacteristic(Characteristic.HomeKitCameraActive).value = Characteristic.HomeKitCameraActive.ON
+ })
+ policy.subscribe('homeKitCameraActive', subscriber)
+
+ policy.bindGlobalOperatingMode(global)
+
+ expect(policy.homeKitCameraActive).toBe(false)
+ expect(global.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.OFF)
+ expect(subscriber).not.toHaveBeenCalled()
+ expect(changes).toEqual([])
+ expect(saves).not.toHaveBeenCalled()
+ })
+
+ it('refreshes the global projection at a write of the legacy one and tells each listener once', async () => {
+ const subscriber = vi.fn()
+ const { policy, operatingMode, global, changes, saves } = camera()
+ policy.subscribe('homeKitCameraActive', subscriber)
+
+ await operatingMode.getCharacteristic(Characteristic.HomeKitCameraActive).handleSetRequest(Characteristic.HomeKitCameraActive.OFF, HUB)
+
+ expect(global.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.OFF)
+ expect(policy.homeKitCameraActive).toBe(false)
+ expect(subscriber.mock.calls).toEqual([
+ [false],
+ ])
+ expect(changes).toHaveLength(1)
+ expect(saves).toHaveBeenCalledTimes(1)
+ })
+
+ it('refreshes the legacy projection at a write of the global one and tells each listener once', async () => {
+ const subscriber = vi.fn()
+ const { policy, operatingMode, global, changes, saves } = camera()
+ policy.subscribe('homeKitCameraActive', subscriber)
+
+ await global.getCharacteristic(Characteristic.HomeKitCameraActive).handleSetRequest(Characteristic.HomeKitCameraActive.OFF, HUB)
+
+ expect(operatingMode.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(0)
+ expect(policy.homeKitCameraActive).toBe(false)
+ expect(subscriber.mock.calls).toEqual([
+ [false],
+ ])
+ expect(changes).toHaveLength(1)
+ expect(saves).toHaveBeenCalledTimes(1)
+ })
+
+ it('moves no gate at a direct assignment to one of two projections', () => {
+ const { policy, global } = camera()
+
+ global.getCharacteristic(Characteristic.HomeKitCameraActive).value = Characteristic.HomeKitCameraActive.OFF
+
+ expect(policy.homeKitCameraActive).toBe(true)
+ expect(policy.streamingAllowed()).toBe(true)
+ })
+
+ it('reads through the remaining projection when the second goes and reads the default when the last goes', () => {
+ const allowed = vi.fn()
+ const { policy, operatingMode, global } = camera(true, ({ operatingMode, global }) => {
+ operatingMode.addCharacteristic(Characteristic.ManuallyDisabled)
+ global.addCharacteristic(Characteristic.ManuallyDisabled)
+ })
+ policy.subscribeDerivation('streamingAllowed', allowed)
+ const legacy = operatingMode.getCharacteristic(Characteristic.ManuallyDisabled)
+
+ legacy.updateValue(1)
+ legacy.value = 0
+ global.removeCharacteristic(global.getCharacteristic(Characteristic.ManuallyDisabled))
+
+ expect(legacy.value).toBe(1)
+ expect(policy.manuallyDisabled).toBe(true)
+
+ operatingMode.removeCharacteristic(legacy)
+
+ expect(policy.manuallyDisabled).toBe(false)
+ expect(allowed.mock.calls).toEqual([
+ [false],
+ [true],
+ ])
+ })
+
+ it('runs the subscribers again at an unchanged write', () => {
+ const subscriber = vi.fn()
+ const { policy, operatingMode } = camera(false)
+ policy.subscribe('homeKitCameraActive', subscriber)
+
+ operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON)
+ operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON)
+
+ expect(subscriber.mock.calls).toEqual([
+ [true],
+ [true],
+ ])
+ })
+
+ it('refreshes a further projection to the stored value as it binds, telling no one', () => {
+ const { policy, operatingMode, changes, saves } = camera()
+ const further = services().global
+ operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ changes.length = 0
+ saves.mockClear()
+
+ // The policy treats every projection alike, which is why a second global service stands in for a third service that projects the camera state.
+ policy.bindGlobalOperatingMode(further)
+
+ expect(further.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.OFF)
+ expect(policy.homeKitCameraActive).toBe(false)
+ expect(changes).toEqual([])
+ expect(saves).not.toHaveBeenCalled()
+ })
+
+ it('allows streaming only while the camera and streaming are on and the camera is not manually disabled', () => {
+ const { policy, global } = camera(true, ({ global }) => {
+ global.addCharacteristic(Characteristic.ManuallyDisabled)
+ })
+
+ for (const cameraActive of [false, true]) {
+ for (const streamingEnabled of [false, true]) {
+ for (const manuallyDisabled of [false, true]) {
+ global.updateCharacteristic(Characteristic.HomeKitCameraActive, cameraActive ? 1 : 0)
+ global.updateCharacteristic(Characteristic.StreamingEnabled, streamingEnabled)
+ global.updateCharacteristic(Characteristic.ManuallyDisabled, manuallyDisabled ? 1 : 0)
+
+ expect(policy.streamingAllowed()).toBe(cameraActive && streamingEnabled && !manuallyDisabled)
+ }
+ }
+ }
+ })
+
+ it('derives a stream service\'s status active from its bound streaming enabled and reads an unbound key\'s as on', () => {
+ const { policy } = camera()
+ const streamingEnabled = new Characteristic.StreamingEnabled()
+ streamingEnabled.updateValue(true)
+ policy.bindStreamingEnabled('multiTierStream:a', streamingEnabled)
+
+ expect(policy.statusActive('multiTierStream:a')).toBe(true)
+
+ streamingEnabled.updateValue(false)
+
+ expect(policy.statusActive('multiTierStream:a')).toBe(false)
+ expect(policy.statusActive('multiTierStream:b')).toBe(true)
+ })
+
+ it('reads a stream service\'s status active on and its stream open off while the camera is out of service with its switches on, both off while it is '
+ + 'switched off in service or not and both on in service and switched on, telling its stream open listener first and dropping both at disposal', () => {
+ const state = { away: false, published: true }
+ const policy = new OperatingModePolicy({
+ published: () => state.published,
+ sourceAway: () => state.away,
+ })
+ const { global, operatingMode, recordingManagement } = services()
+ const heard: [string, boolean][] = []
+ // The key's Status Active and whether it may stream, as the policy answers them.
+ const reading = (): boolean[] => [
+ policy.statusActive('multiTierStream:a'),
+ policy.streamOpen('multiTierStream:a'),
+ ]
+ const read: boolean[][] = []
+
+ policy.bindRecording(recordingManagement, operatingMode)
+ policy.bindGlobalOperatingMode(global)
+ policy.subscribeDerivation('statusActive', active => heard.push(['statusActive', active]), 'multiTierStream:a')
+ policy.subscribeDerivation('streamOpen', open => heard.push(['streamOpen', open]), 'multiTierStream:a')
+ read.push(reading())
+ state.away = true
+ policy.serviceChanged()
+ read.push(reading())
+ state.away = false
+ policy.serviceChanged()
+
+ const leftAndBack = heard.splice(0)
+
+ global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ read.push(reading())
+ state.published = false
+ policy.serviceChanged()
+ read.push(reading())
+
+ const switchedOff = heard.splice(0)
+
+ policy[Symbol.dispose]()
+ state.published = true
+ global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON)
+ policy.serviceChanged()
+
+ expect(read).toEqual([
+ [true, true],
+ [true, false],
+ [false, false],
+ [false, false],
+ ])
+ expect(leftAndBack).toEqual([
+ ['streamOpen', false],
+ ['streamOpen', true],
+ ])
+ expect(switchedOff).toEqual([
+ ['streamOpen', false],
+ ['statusActive', false],
+ ])
+ expect(heard).toEqual([])
+ })
+
+ it('tells every key\'s stream open listener before any key\'s status active listener at a recompute that moves both of two keys', () => {
+ const { policy, global } = camera()
+ const heard: string[] = []
+
+ // The listeners are subscribed each key's status active first and the second key before the first. The order heard is the recompute's own.
+ for (const key of ['multiTierStream:b', 'multiTierStream:a']) {
+ policy.subscribeDerivation('statusActive', active => heard.push(`${key} statusActive ${active}`), key)
+ policy.subscribeDerivation('streamOpen', open => heard.push(`${key} streamOpen ${open}`), key)
+ }
+
+ global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+
+ expect(heard).toEqual([
+ 'multiTierStream:b streamOpen false',
+ 'multiTierStream:a streamOpen false',
+ 'multiTierStream:b statusActive false',
+ 'multiTierStream:a statusActive false',
+ ])
+ })
+
+ it('tells a key\'s stream open listener before its status active listener at a change of its own streaming enabled', () => {
+ const { policy } = camera()
+ const streamingEnabled = new Characteristic.StreamingEnabled()
+ const heard: string[] = []
+
+ streamingEnabled.updateValue(true)
+ policy.bindStreamingEnabled('multiTierStream:a', streamingEnabled)
+ policy.subscribeDerivation('statusActive', active => heard.push(`statusActive ${active}`), 'multiTierStream:a')
+ policy.subscribeDerivation('streamOpen', open => heard.push(`streamOpen ${open}`), 'multiTierStream:a')
+ streamingEnabled.updateValue(false)
+
+ expect(heard).toEqual([
+ 'streamOpen false',
+ 'statusActive false',
+ ])
+ })
+
+ it('moves recording published with the user\'s switches and the accessory\'s publication and never with the source, its listener hearing after '
+ + 'recording in service\'s at a recompute', () => {
+ const state = { away: false, published: true }
+ const policy = new OperatingModePolicy({
+ published: () => state.published,
+ sourceAway: () => state.away,
+ })
+ const { global, operatingMode, recordingManagement } = services()
+ const heard: string[] = []
+ const read: boolean[] = []
+
+ policy.bindRecording(recordingManagement, operatingMode)
+ policy.bindGlobalOperatingMode(global)
+ recordingManagement.updateCharacteristic(Characteristic.Active, true)
+
+ // Recording published is subscribed first, which means the order heard is the recompute's own.
+ policy.subscribeDerivation('recordingPublished', published => heard.push(`recordingPublished ${published}`))
+ policy.subscribeDerivation('recordingInService', inService => heard.push(`recordingInService ${inService}`))
+ read.push(policy.recordingPublished())
+
+ // The source stated away and back moves recording in service alone.
+ state.away = true
+ policy.serviceChanged()
+ read.push(policy.recordingPublished())
+ state.away = false
+ policy.serviceChanged()
+
+ const sourced = heard.splice(0)
+
+ // The accessory unpublished and published again, and recording switched off, each move recording in service and then recording published.
+ state.published = false
+ policy.serviceChanged()
+ read.push(policy.recordingPublished())
+ state.published = true
+ policy.serviceChanged()
+ read.push(policy.recordingPublished())
+ recordingManagement.updateCharacteristic(Characteristic.Active, false)
+ read.push(policy.recordingPublished())
+
+ expect(read).toEqual([true, true, false, true, false])
+ expect(sourced).toEqual([
+ 'recordingInService false',
+ 'recordingInService true',
+ ])
+ expect(heard).toEqual([
+ 'recordingInService false',
+ 'recordingPublished false',
+ 'recordingInService true',
+ 'recordingPublished true',
+ 'recordingInService false',
+ 'recordingPublished false',
+ ])
+ })
+
+ it('tells a derivation\'s listener only when its value moves', () => {
+ const allowed = vi.fn()
+ const { policy, global } = camera()
+ policy.subscribeDerivation('streamingAllowed', allowed)
+
+ global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+
+ expect(allowed.mock.calls).toEqual([
+ [false],
+ ])
+ })
+
+ it('allows recording only while recording is active, the camera is on and it is not manually disabled', () => {
+ const { policy, recordingManagement, global } = camera(true, ({ global }) => {
+ global.addCharacteristic(Characteristic.ManuallyDisabled)
+ })
+
+ for (const recordingActive of [false, true]) {
+ for (const cameraActive of [false, true]) {
+ for (const manuallyDisabled of [false, true]) {
+ recordingManagement.updateCharacteristic(Characteristic.Active, recordingActive ? 1 : 0)
+ global.updateCharacteristic(Characteristic.HomeKitCameraActive, cameraActive ? 1 : 0)
+ global.updateCharacteristic(Characteristic.ManuallyDisabled, manuallyDisabled ? 1 : 0)
+
+ expect(policy.recordingAllowed()).toBe(recordingActive && cameraActive && !manuallyDisabled)
+ }
+ }
+ }
+ })
+
+ it('tells a recording allowed listener each time a write of either input moves the value, and nothing at a write that leaves it as it stands', () => {
+ const allowed = vi.fn()
+ const { policy, recordingManagement, operatingMode } = camera()
+ policy.subscribeDerivation('recordingAllowed', allowed)
+
+ recordingManagement.updateCharacteristic(Characteristic.Active, true)
+ recordingManagement.updateCharacteristic(Characteristic.Active, true)
+ operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ recordingManagement.updateCharacteristic(Characteristic.Active, false)
+ operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON)
+
+ expect(allowed.mock.calls).toEqual([
+ [true],
+ [false],
+ ])
+ })
+
+ it('drops a recording allowed listener at disposal, and a later reset tells it nothing', () => {
+ const allowed = vi.fn()
+ const { policy, recordingManagement } = camera()
+ policy.subscribeDerivation('recordingAllowed', allowed)
+ recordingManagement.updateCharacteristic(Characteristic.Active, true)
+
+ policy[Symbol.dispose]()
+ policy.reset()
+
+ expect(policy.recordingAllowed()).toBe(false)
+ expect(allowed.mock.calls).toEqual([
+ [true],
+ ])
+ })
+
+ it('tells a status active listener of its own key and of the camera-wide inputs, never of another key', () => {
+ const statusActive = vi.fn()
+ const { policy, global } = camera()
+ const first = new Characteristic.StreamingEnabled()
+ const second = new Characteristic.StreamingEnabled()
+ first.updateValue(true)
+ second.updateValue(true)
+ policy.bindStreamingEnabled('multiTierStream:a', first)
+ policy.bindStreamingEnabled('multiTierStream:b', second)
+ policy.subscribeDerivation('statusActive', statusActive, 'multiTierStream:a')
+
+ second.updateValue(false)
+ first.updateValue(false)
+ first.updateValue(true)
+ global.updateCharacteristic(Characteristic.StreamingEnabled, false)
+
+ expect(statusActive.mock.calls).toEqual([
+ [false],
+ [true],
+ [false],
+ ])
+ })
+
+ it('disables a legacy stream at each global input', () => {
+ const { policy, global } = camera(true, ({ global }) => {
+ global.addCharacteristic(Characteristic.ManuallyDisabled)
+ })
+ const stream = new Service.CameraRTPStreamManagement('', '0')
+ stream.setCharacteristic(Characteristic.Active, true)
+ policy.bindStream(0, stream)
+
+ expect(policy.legacyStreamingDisabled(0)).toBe(false)
+
+ global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ expect(policy.legacyStreamingDisabled(0)).toBe(true)
+
+ global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON)
+ global.updateCharacteristic(Characteristic.StreamingEnabled, false)
+ expect(policy.legacyStreamingDisabled(0)).toBe(true)
+
+ global.updateCharacteristic(Characteristic.StreamingEnabled, true)
+ global.updateCharacteristic(Characteristic.ManuallyDisabled, 1)
+ expect(policy.legacyStreamingDisabled(0)).toBe(true)
+
+ global.updateCharacteristic(Characteristic.ManuallyDisabled, 0)
+ expect(policy.legacyStreamingDisabled(0)).toBe(false)
+ })
+
+ it('serializes the persisted fields without the global service and every field with it', () => {
+ expect(Object.keys(camera(false).policy.serialize()!)).toEqual([
+ 'recordingActive',
+ 'recordingAudioActive',
+ 'eventSnapshotsActive',
+ 'homeKitCameraActive',
+ 'periodicSnapshotsActive',
+ ])
+ expect(camera().policy.serialize()).toEqual({
+ ...PERSISTED_SLICE,
+ globalStreamingEnabled: true,
+ operatingModeIndicator: true,
+ manuallyDisabled: false,
+ nightVision: false,
+ thirdPartyCameraActive: false,
+ motionEnabled: true,
+ })
+ expect(Object.keys(camera().policy.serialize()!)).toEqual([
+ 'recordingActive',
+ 'recordingAudioActive',
+ 'eventSnapshotsActive',
+ 'homeKitCameraActive',
+ 'periodicSnapshotsActive',
+ 'globalStreamingEnabled',
+ 'operatingModeIndicator',
+ 'manuallyDisabled',
+ 'nightVision',
+ 'thirdPartyCameraActive',
+ 'motionEnabled',
+ ])
+ })
+
+ it('leaves a field the restored slice lacks as the policy holds it', () => {
+ const { policy, global } = camera()
+ global.getCharacteristic(Characteristic.NightVision).updateValue(true)
+
+ policy.restore(PERSISTED_SLICE)
+
+ expect(policy.nightVision).toBe(true)
+ expect(global.getCharacteristic(Characteristic.NightVision).value).toBe(true)
+ })
+
+ it('writes every default through every projection at a reset', () => {
+ const { policy, recordingManagement, operatingMode, global } = camera(true, addEveryOptional)
+ policy.restore({
+ recordingActive: true,
+ recordingAudioActive: true,
+ eventSnapshotsActive: false,
+ homeKitCameraActive: false,
+ periodicSnapshotsActive: false,
+ globalStreamingEnabled: false,
+ operatingModeIndicator: false,
+ manuallyDisabled: true,
+ nightVision: true,
+ thirdPartyCameraActive: true,
+ })
+
+ policy.reset()
+
+ expect(recordingManagement.getCharacteristic(Characteristic.Active).value).toBe(0)
+ expect(recordingManagement.getCharacteristic(Characteristic.RecordingAudioActive).value).toBe(0)
+ expect(operatingMode.getCharacteristic(Characteristic.EventSnapshotsActive).value).toBe(1)
+ expect(operatingMode.getCharacteristic(Characteristic.PeriodicSnapshotsActive).value).toBe(1)
+ expect(global.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(true)
+ for (const service of [operatingMode, global]) {
+ expect(service.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(1)
+ expect(service.getCharacteristic(Characteristic.CameraOperatingModeIndicator).value).toBe(1)
+ expect(service.getCharacteristic(Characteristic.ManuallyDisabled).value).toBe(0)
+ expect(service.getCharacteristic(Characteristic.NightVision).value).toBe(false)
+ expect(service.getCharacteristic(Characteristic.ThirdPartyCameraActive).value).toBe(0)
+ }
+ })
+
+ it('reports a write from a controller with the write reason', async () => {
+ const { global, changes } = camera()
+
+ await global.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, HUB)
+
+ expect(changes).toEqual([
+ { field: 'globalStreamingEnabled', value: false, reason: 'write' },
+ ])
+ })
+
+ it('reports a plugin update with the update reason', () => {
+ const { global, changes } = camera()
+
+ global.updateCharacteristic(Characteristic.CameraOperatingModeIndicator, 0)
+
+ expect(changes).toEqual([
+ { field: 'operatingModeIndicator', value: false, reason: 'update' },
+ ])
+ })
+
+ it('reports a restored field with the restore reason', () => {
+ const { policy, changes } = camera(false)
+
+ policy.restore({ homeKitCameraActive: false })
+
+ expect(changes).toEqual([
+ { field: 'homeKitCameraActive', value: false, reason: 'restore' },
+ ])
+ })
+
+ it('reports each reset field with the reset reason', () => {
+ const { policy, changes } = camera(false)
+
+ policy.reset()
+
+ expect(changes).toEqual([
+ { field: 'recordingActive', value: false, reason: 'reset' },
+ { field: 'recordingAudioActive', value: false, reason: 'reset' },
+ { field: 'eventSnapshotsActive', value: true, reason: 'reset' },
+ { field: 'periodicSnapshotsActive', value: true, reason: 'reset' },
+ { field: 'homeKitCameraActive', value: true, reason: 'reset' },
+ ])
+ })
+
+ it.each<[string, Partial, OperatingModeField[]]>([
+ [
+ 'HomeKit Camera Active off',
+ { homeKitCameraActive: false },
+ [
+ 'recordingActive',
+ 'recordingAudioActive',
+ 'eventSnapshotsActive',
+ 'periodicSnapshotsActive',
+ 'homeKitCameraActive',
+ ],
+ ],
+ [
+ 'Manually Disabled on',
+ { manuallyDisabled: true },
+ [
+ 'recordingActive',
+ 'recordingAudioActive',
+ 'eventSnapshotsActive',
+ 'periodicSnapshotsActive',
+ 'homeKitCameraActive',
+ 'manuallyDisabled',
+ ],
+ ],
+ ])('reads the whole restored state at every change of a restore of recording on with %s, the changes in the write order, each one saved, and tells '
+ + 'a recording allowed listener nothing', (_, saved, order) => {
+ const read: boolean[][] = []
+ const allowed = vi.fn()
+ const state: Partial = {
+ ...PERSISTED_SLICE,
+ recordingActive: true,
+ ...saved,
+ }
+ // The global service carries Manually Disabled: a restore that defines it writes it rather than holding it, and each reading takes it.
+ const { policy, changes, saves } = camera(true, ({ global }) => {
+ global.addCharacteristic(Characteristic.ManuallyDisabled)
+ }, (_change, made) => {
+ read.push([
+ made.policy.streamingAllowed(),
+ made.policy.recordingAllowed(),
+ ])
+ })
+ policy.subscribeDerivation('recordingAllowed', allowed)
+
+ policy.restore(state)
+
+ expect(changes).toEqual(order.map(field => ({ field, value: state[field], reason: 'restore' })))
+ expect(read).toEqual(order.map(() => [false, false]))
+ expect(saves).toHaveBeenCalledTimes(order.length)
+ expect(allowed).not.toHaveBeenCalled()
+ })
+
+ it('stores every field a restore writes before it tells of any, each characteristic\'s own change event arriving in the write order, and tells a '
+ + 'derivation the restore moves once, ahead of the first change', () => {
+ const heard: string[] = []
+ const { policy, recordingManagement, operatingMode, global } = camera(true, undefined, ({ field }) => {
+ heard.push(`told ${field}`)
+ })
+
+ // Each characteristic that projects a field the restore writes, in the write order, HomeKit Camera Active on the legacy service and on the global one.
+ for (const [field, service, projection] of [
+ ['recordingActive', recordingManagement, Characteristic.Active],
+ ['recordingAudioActive', recordingManagement, Characteristic.RecordingAudioActive],
+ ['eventSnapshotsActive', operatingMode, Characteristic.EventSnapshotsActive],
+ ['periodicSnapshotsActive', operatingMode, Characteristic.PeriodicSnapshotsActive],
+ ['homeKitCameraActive', operatingMode, Characteristic.HomeKitCameraActive],
+ ['homeKitCameraActive', global, Characteristic.HomeKitCameraActive],
+ ] as const) {
+ service.getCharacteristic(projection).on(CharacteristicEventTypes.CHANGE, () => {
+ heard.push(`stored ${field}`)
+ })
+ }
+
+ policy.subscribeDerivation('recordingAllowed', () => {
+ heard.push('recording allowed')
+ })
+
+ policy.restore({
+ ...PERSISTED_SLICE,
+ recordingActive: true,
+ })
+
+ expect(heard).toEqual([
+ 'stored recordingActive',
+ 'stored recordingAudioActive',
+ 'stored eventSnapshotsActive',
+ 'stored periodicSnapshotsActive',
+ 'stored homeKitCameraActive',
+ 'stored homeKitCameraActive',
+ 'recording allowed',
+ 'told recordingActive',
+ 'told recordingAudioActive',
+ 'told eventSnapshotsActive',
+ 'told periodicSnapshotsActive',
+ 'told homeKitCameraActive',
+ ])
+ })
+
+ it('reads the whole reset state at every change of a reset of a camera with recording on and HomeKit Camera Active off, each one saved', () => {
+ const read: boolean[][] = []
+ const { policy, recordingManagement, global, changes, saves } = camera(true, undefined, (_change, made) => {
+ read.push([
+ made.policy.streamingAllowed(),
+ made.policy.recordingAllowed(),
+ ])
+ })
+ recordingManagement.updateCharacteristic(Characteristic.Active, true)
+ global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ changes.length = 0
+ read.length = 0
+ saves.mockClear()
+
+ policy.reset()
+
+ expect(changes.map(({ field }) => field)).toEqual([
+ 'recordingActive',
+ 'recordingAudioActive',
+ 'eventSnapshotsActive',
+ 'periodicSnapshotsActive',
+ 'homeKitCameraActive',
+ 'globalStreamingEnabled',
+ 'operatingModeIndicator',
+ ])
+ expect(read).toEqual(changes.map(() => [true, false]))
+ expect(saves).toHaveBeenCalledTimes(changes.length)
+ })
+
+ it.each<{
+ name: string
+ run: (policy: OperatingModePolicy) => void
+ write: number
+ told: OperatingModeChange[]
+ }>([
+ {
+ name: 'restore',
+ run: policy => policy.restore({
+ recordingActive: true,
+ homeKitCameraActive: false,
+ }),
+ write: Characteristic.HomeKitCameraActive.ON,
+ told: [
+ { field: 'recordingActive', value: true, reason: 'restore' },
+ { field: 'homeKitCameraActive', value: true, reason: 'update' },
+ ],
+ },
+ {
+ name: 'reset',
+ run: policy => policy.reset(),
+ write: Characteristic.HomeKitCameraActive.OFF,
+ told: [
+ { field: 'recordingActive', value: false, reason: 'reset' },
+ { field: 'homeKitCameraActive', value: false, reason: 'update' },
+ { field: 'recordingAudioActive', value: false, reason: 'reset' },
+ { field: 'eventSnapshotsActive', value: true, reason: 'reset' },
+ { field: 'periodicSnapshotsActive', value: true, reason: 'reset' },
+ { field: 'globalStreamingEnabled', value: true, reason: 'reset' },
+ { field: 'operatingModeIndicator', value: true, reason: 'reset' },
+ ],
+ },
+ ])('lets a field the hook writes through its characteristic at a $name\'s first change stand, told by that write alone and never again by the '
+ + '$name, each change saved', ({ run, write, told }) => {
+ const { policy, changes, saves } = camera(true, undefined, (_change, made) => {
+ if (made.changes.length === 1) {
+ made.operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, write)
+ }
+ })
+
+ run(policy)
+
+ expect(changes).toEqual(told)
+ expect(policy.homeKitCameraActive).toBe(write === Characteristic.HomeKitCameraActive.ON)
+ expect(saves).toHaveBeenCalledTimes(told.length)
+ })
+
+ it('binds a field characteristic a plugin adds and drops one it removes', async () => {
+ const { policy, operatingMode, global } = camera()
+
+ const legacy = operatingMode.getCharacteristic(Characteristic.NightVision)
+ const current = global.getCharacteristic(Characteristic.NightVision)
+ await current.handleSetRequest(true, HUB)
+
+ expect(legacy.value).toBe(true)
+
+ operatingMode.removeCharacteristic(legacy)
+ current.value = false
+
+ expect(policy.nightVision).toBe(false)
+ })
+
+ it('binds each projection once however often its service changes configuration', () => {
+ const subscriber = vi.fn()
+ const { policy, global, saves } = camera()
+ policy.subscribe('homeKitCameraActive', subscriber)
+ const characteristic = global.getCharacteristic(Characteristic.HomeKitCameraActive)
+
+ characteristic.setProps({})
+ characteristic.setProps({})
+ characteristic.updateValue(Characteristic.HomeKitCameraActive.OFF)
+
+ expect(subscriber).toHaveBeenCalledTimes(1)
+ expect(saves).toHaveBeenCalledTimes(1)
+ })
+
+ it('marks every projection of an admin-only field and no other', () => {
+ const { recordingManagement, operatingMode, global } = camera(true, addEveryOptional)
+ const adminOnly = (service: Service, type: WithUUID<{ new (): Characteristic }>): unknown => service.getCharacteristic(type).props.adminOnlyAccess
+
+ expect(adminOnly(recordingManagement, Characteristic.Active)).toEqual([Access.WRITE])
+ expect(adminOnly(recordingManagement, Characteristic.RecordingAudioActive)).toBeUndefined()
+ expect(adminOnly(operatingMode, Characteristic.EventSnapshotsActive)).toEqual([Access.WRITE])
+ expect(adminOnly(operatingMode, Characteristic.PeriodicSnapshotsActive)).toEqual([Access.WRITE])
+ for (const service of [operatingMode, global]) {
+ expect(adminOnly(service, Characteristic.HomeKitCameraActive)).toEqual([Access.WRITE])
+ expect(adminOnly(service, Characteristic.CameraOperatingModeIndicator)).toEqual([Access.WRITE])
+ expect(adminOnly(service, Characteristic.ManuallyDisabled)).toBeUndefined()
+ expect(adminOnly(service, Characteristic.NightVision)).toBeUndefined()
+ expect(adminOnly(service, Characteristic.ThirdPartyCameraActive)).toBeUndefined()
+ }
+ })
+
+ it('removes every listener it added at disposal and tells no one afterward, disposed twice', () => {
+ const subscriber = vi.fn()
+ const derivationListener = vi.fn()
+ let unbound: number[] = []
+ const { policy, recordingManagement, operatingMode, global, changes, saves } = camera(true, (bound) => {
+ unbound = listenerCounts(bound.recordingManagement, bound.operatingMode, bound.global)
+ })
+ const streamingEnabled = new Characteristic.StreamingEnabled()
+ streamingEnabled.updateValue(true)
+ policy.bindStreamingEnabled('multiTierStream:a', streamingEnabled)
+ policy.subscribe('homeKitCameraActive', subscriber)
+ policy.subscribeDerivation('streamingAllowed', derivationListener)
+ policy.subscribeDerivation('statusActive', derivationListener, 'multiTierStream:a')
+
+ policy[Symbol.dispose]()
+ policy[Symbol.dispose]()
+
+ expect(listenerCounts(recordingManagement, operatingMode, global)).toEqual(unbound)
+ expect(streamingEnabled.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(0)
+
+ global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ recordingManagement.updateCharacteristic(Characteristic.Active, true)
+ streamingEnabled.updateValue(false)
+
+ expect(subscriber).not.toHaveBeenCalled()
+ expect(derivationListener).not.toHaveBeenCalled()
+ expect(changes).toEqual([])
+ expect(saves).not.toHaveBeenCalled()
+ })
+
+ it('removes its listener from a streaming enabled its key is bound away from, which means a write to that one tells the key\'s derivation nothing', () => {
+ const statusActive = vi.fn()
+ const { policy } = camera()
+ const first = new Characteristic.StreamingEnabled()
+ const second = new Characteristic.StreamingEnabled()
+ first.updateValue(true)
+ second.updateValue(true)
+ policy.bindStreamingEnabled('multiTierStream:a', first)
+ policy.subscribeDerivation('statusActive', statusActive, 'multiTierStream:a')
+
+ policy.bindStreamingEnabled('multiTierStream:a', second)
+ first.updateValue(false)
+
+ expect(first.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(0)
+ expect(statusActive).not.toHaveBeenCalled()
+ expect(policy.statusActive('multiTierStream:a')).toBe(true)
+
+ second.updateValue(false)
+
+ expect(statusActive.mock.calls).toEqual([
+ [false],
+ ])
+ })
+
+ it('holds a global field a restore writes before its characteristic exists for serialize and the first bind alone, and drops it at a reset', () => {
+ const { policy, global, changes, saves } = camera()
+ policy.restore({
+ ...PERSISTED_SLICE,
+ nightVision: true,
+ })
+ const heard = changes.length
+ const saved = saves.mock.calls.length
+
+ expect(policy.nightVision).toBe(false)
+ expect(policy.serialize()!.nightVision).toBe(true)
+
+ const nightVision = global.getCharacteristic(Characteristic.NightVision)
+
+ expect(nightVision.value).toBe(true)
+ expect(policy.nightVision).toBe(true)
+ expect(changes).toHaveLength(heard)
+ expect(saves).toHaveBeenCalledTimes(saved)
+
+ const reset = camera()
+ reset.policy.restore({
+ ...PERSISTED_SLICE,
+ nightVision: true,
+ })
+ reset.policy.reset()
+
+ expect(reset.policy.serialize()!.nightVision).toBe(false)
+ expect(reset.global.getCharacteristic(Characteristic.NightVision).value).toBe(false)
+
+ const disabled = camera()
+ const streamingEnabled = new Characteristic.StreamingEnabled()
+ streamingEnabled.updateValue(true)
+ disabled.policy.bindStreamingEnabled('multiTierStream:a', streamingEnabled)
+ disabled.policy.restore({
+ ...PERSISTED_SLICE,
+ manuallyDisabled: true,
+ })
+
+ expect(disabled.policy.statusActive('multiTierStream:a')).toBe(true)
+
+ disabled.global.getCharacteristic(Characteristic.ManuallyDisabled)
+
+ expect(disabled.policy.statusActive('multiTierStream:a')).toBe(false)
+ })
+
+ describe('motion enabled', () => {
+ it('reads motion enabled as on with the global service bound and no motion sensor, and serializes it last', () => {
+ const { policy } = camera()
+
+ expect(policy.motionEnabled).toBe(true)
+ expect(Object.entries(policy.serialize()!).at(-1)).toEqual(['motionEnabled', true])
+ })
+
+ it('adds motion enabled reading on to a motion sensor that lacks it and reports a hub write through it once, saving once', async () => {
+ const { policy, changes, saves } = camera()
+ const motionSensor = new Service.MotionSensor('', '')
+
+ expect(motionSensor.testCharacteristic(Characteristic.MotionEnabled)).toBe(false)
+
+ policy.bindMotionSensor(motionSensor)
+ const motionEnabled = motionSensor.getCharacteristic(Characteristic.MotionEnabled)
+
+ expect(motionEnabled.value).toBe(true)
+ expect(changes).toEqual([])
+ expect(saves).not.toHaveBeenCalled()
+
+ await motionEnabled.handleSetRequest(false, HUB)
+
+ expect(changes).toEqual([
+ { field: 'motionEnabled', value: false, reason: 'write' },
+ ])
+ expect(policy.motionEnabled).toBe(false)
+ expect(saves).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps the value of a motion enabled the sensor already carries at the bind', () => {
+ const { policy } = camera()
+ const motionSensor = new Service.MotionSensor('', '')
+ motionSensor.getCharacteristic(Characteristic.MotionEnabled).updateValue(false)
+
+ policy.bindMotionSensor(motionSensor)
+
+ expect(motionSensor.getCharacteristic(Characteristic.MotionEnabled).value).toBe(false)
+ expect(policy.motionEnabled).toBe(false)
+ })
+
+ it('marks a motion enabled whose props carry no admin-only access admin-only at the bind', () => {
+ const { policy } = camera()
+ const motionSensor = new Service.MotionSensor('', '')
+ const motionEnabled = motionSensor.getCharacteristic(Characteristic.MotionEnabled)
+ motionEnabled.setProps({ adminOnlyAccess: null })
+
+ expect(motionEnabled.props.adminOnlyAccess).toBeUndefined()
+
+ policy.bindMotionSensor(motionSensor)
+
+ expect(motionEnabled.props.adminOnlyAccess).toEqual([Access.WRITE])
+ })
+
+ it('holds a restored motion enabled for serialize and the motion sensor\'s bind alone, which seeds it, and drops it at a reset', () => {
+ const { policy, changes, saves } = camera()
+ policy.restore({
+ ...PERSISTED_SLICE,
+ motionEnabled: false,
+ })
+ const heard = changes.length
+ const saved = saves.mock.calls.length
+
+ expect(policy.motionEnabled).toBe(true)
+ expect(policy.serialize()!.motionEnabled).toBe(false)
+
+ const motionSensor = new Service.MotionSensor('', '')
+ policy.bindMotionSensor(motionSensor)
+
+ expect(motionSensor.getCharacteristic(Characteristic.MotionEnabled).value).toBe(false)
+ expect(policy.motionEnabled).toBe(false)
+ expect(changes).toHaveLength(heard)
+ expect(saves).toHaveBeenCalledTimes(saved)
+
+ const reset = camera()
+ reset.policy.restore({
+ ...PERSISTED_SLICE,
+ motionEnabled: false,
+ })
+ reset.policy.reset()
+ const later = new Service.MotionSensor('', '')
+ reset.policy.bindMotionSensor(later)
+
+ expect(later.getCharacteristic(Characteristic.MotionEnabled).value).toBe(true)
+ expect(reset.policy.serialize()!.motionEnabled).toBe(true)
+ })
+
+ it('writes motion enabled after every other field at a restore and at a reset, each under its own reason', () => {
+ const { policy, changes } = camera(true, addEveryOptional)
+ policy.bindMotionSensor(new Service.MotionSensor('', ''))
+ const order = [
+ 'recordingActive',
+ 'recordingAudioActive',
+ 'eventSnapshotsActive',
+ 'periodicSnapshotsActive',
+ 'homeKitCameraActive',
+ 'globalStreamingEnabled',
+ 'operatingModeIndicator',
+ 'manuallyDisabled',
+ 'nightVision',
+ 'thirdPartyCameraActive',
+ 'motionEnabled',
+ ]
+
+ policy.restore({
+ ...PERSISTED_SLICE,
+ globalStreamingEnabled: true,
+ operatingModeIndicator: true,
+ manuallyDisabled: false,
+ nightVision: false,
+ thirdPartyCameraActive: false,
+ motionEnabled: false,
+ })
+
+ expect(changes.map(({ field }) => field)).toEqual(order)
+ expect(changes.at(-1)).toEqual({ field: 'motionEnabled', value: false, reason: 'restore' })
+
+ changes.length = 0
+ policy.reset()
+
+ expect(changes.map(({ field }) => field)).toEqual(order)
+ expect(changes.at(-1)).toEqual({ field: 'motionEnabled', value: true, reason: 'reset' })
+ })
+
+ it('carries a restored motion enabled untouched without the global service, and serializes a slice without it as before', () => {
+ const { policy } = camera(false)
+ const slice: OperatingModeState = {
+ ...PERSISTED_SLICE,
+ motionEnabled: false,
+ }
+
+ policy.restore(slice)
+
+ expect(policy.serialize()).toEqual(slice)
+
+ policy.restore(PERSISTED_SLICE)
+
+ expect(policy.serialize()).toEqual(PERSISTED_SLICE)
+ expect(Object.keys(policy.serialize()!)).toEqual(Object.keys(PERSISTED_SLICE))
+ })
+
+ it('drops a motion enabled the plugin removes, reading the default, and binds one it adds again', async () => {
+ const { policy, changes } = camera()
+ const motionSensor = new Service.MotionSensor('', '')
+ policy.bindMotionSensor(motionSensor)
+ const removed = motionSensor.getCharacteristic(Characteristic.MotionEnabled)
+ removed.updateValue(false)
+
+ expect(policy.motionEnabled).toBe(false)
+
+ motionSensor.removeCharacteristic(removed)
+
+ expect(policy.motionEnabled).toBe(true)
+
+ changes.length = 0
+ const added = motionSensor.getCharacteristic(Characteristic.MotionEnabled)
+ await added.handleSetRequest(true, HUB)
+
+ expect(changes).toEqual([
+ { field: 'motionEnabled', value: true, reason: 'write' },
+ ])
+ expect(policy.motionEnabled).toBe(true)
+ })
+ })
+})
diff --git a/src/lib/camera/OperatingModePolicy.ts b/src/lib/camera/OperatingModePolicy.ts
new file mode 100644
index 000000000..ce3918275
--- /dev/null
+++ b/src/lib/camera/OperatingModePolicy.ts
@@ -0,0 +1,1104 @@
+import type { WithUUID } from '../../types.js'
+import type { CharacteristicChange } from '../Characteristic.js'
+import type { StateChangeDelegate } from '../controller/index.js'
+import type {
+ CameraCapabilities,
+ CameraGlobalOperatingMode,
+ CameraOperatingMode,
+ CameraRecordingManagement,
+ CameraRTPStreamManagement,
+ MotionSensor,
+} from '../definitions/index.js'
+import type { Service } from '../Service.js'
+
+import { Access, ChangeReason, Characteristic, CharacteristicEventTypes, Formats } from '../Characteristic.js'
+import { ServiceEventTypes } from '../Service.js'
+import { DisposableStack } from '../util/disposableStack.js'
+
+/**
+ * A camera's persisted operating mode, one boolean per field the operating-mode policy owns. The optional fields are the ones only a camera with the
+ * camera capabilities block projects, which a layout saved without the block carries none of. While more than one characteristic projects a field, a direct
+ * assignment to any one of them reaches no gate, because no change event carries it to the others, which is why a plugin writes a field through its characteristic's
+ * set path or `updateValue`.
+ */
+export interface OperatingModeState {
+ /**
+ * Service `CameraRecordingManagement`; Characteristic `Active`
+ */
+ recordingActive: boolean
+ /**
+ * Service `CameraRecordingManagement`; Characteristic `RecordingAudioActive`
+ */
+ recordingAudioActive: boolean
+ /**
+ * Service `CameraOperatingMode`; Characteristic `EventSnapshotsActive`
+ */
+ eventSnapshotsActive: boolean
+ /**
+ * Services `CameraOperatingMode` and `CameraGlobalOperatingMode`; Characteristic `HomeKitCameraActive`
+ */
+ homeKitCameraActive: boolean
+ /**
+ * Service `CameraOperatingMode`; Characteristic `PeriodicSnapshotsActive`
+ */
+ periodicSnapshotsActive: boolean
+ /**
+ * Service `CameraGlobalOperatingMode`; Characteristic `StreamingEnabled`
+ */
+ globalStreamingEnabled?: boolean
+ /**
+ * Services `CameraGlobalOperatingMode` and, when the plugin adds it, `CameraOperatingMode`; Characteristic `CameraOperatingModeIndicator`
+ */
+ operatingModeIndicator?: boolean
+ /**
+ * Services `CameraGlobalOperatingMode`, `CameraCapabilities` and `CameraOperatingMode`, each when the plugin adds it; Characteristic `ManuallyDisabled`
+ */
+ manuallyDisabled?: boolean
+ /**
+ * Services `CameraGlobalOperatingMode` and `CameraOperatingMode`, each when the plugin adds it; Characteristic `NightVision`
+ */
+ nightVision?: boolean
+ /**
+ * Services `CameraGlobalOperatingMode` and `CameraOperatingMode`, each when the plugin adds it; Characteristic `ThirdPartyCameraActive`
+ */
+ thirdPartyCameraActive?: boolean
+ /**
+ * Service `MotionSensor` on a camera with the camera capabilities block; Characteristic `MotionEnabled`
+ */
+ motionEnabled?: boolean
+}
+
+/**
+ * The name of one operating-mode field.
+ *
+ * @group Camera
+ */
+export type OperatingModeField = keyof OperatingModeState
+
+/**
+ * Why a piece of a camera's state changed, as an operating-mode field, a stream service's Streaming Enabled and a video sensor's motion zones each report it.
+ *
+ * - `'write'`: a HomeKit controller wrote a characteristic that holds the state, or the plugin called its `setValue`.
+ * - `'update'`: the plugin surfaced a value it holds: an `updateValue`, a get handler that returned a new value, or an event notification.
+ * - `'restore'`: the camera restored its persisted state.
+ * - `'reset'`: a factory reset gave the state its default.
+ *
+ * @group Camera
+ */
+export type CameraChangeReason = 'write' | 'update' | 'restore' | 'reset'
+
+/**
+ * One change of an operating-mode field, as the camera controller's operating-mode event reports it.
+ *
+ * @group Camera
+ */
+export interface OperatingModeChange {
+ /**
+ * The field that changed.
+ */
+ readonly field: OperatingModeField
+ /**
+ * The field's value, which a write that leaves it unchanged reports again.
+ */
+ readonly value: boolean
+ /**
+ * Why the field changed.
+ */
+ readonly reason: CameraChangeReason
+}
+
+/**
+ * One change of a multi-tier or WebRTC stream service's Streaming Enabled, as the camera controller's streaming-enabled event reports it.
+ *
+ * @group Camera
+ */
+export interface StreamingEnabledChange {
+ /**
+ * The video sensor whose service changed, in lowercase.
+ */
+ readonly sensorUUID: string
+ /**
+ * Whether the change is for views at home, the sensor's Camera Multi-Tier RTP Stream Management changing, or for views from away, its Camera WebRTC
+ * Stream Management changing.
+ */
+ readonly where: 'home' | 'away'
+ /**
+ * The value of Streaming Enabled, which a write that leaves it unchanged reports again.
+ */
+ readonly value: boolean
+ /**
+ * Why it changed.
+ */
+ readonly reason: CameraChangeReason
+}
+
+/**
+ * What a camera's operating-mode policy is made with. A policy made without them announces no field change and reads its camera in service.
+ */
+export interface OperatingModePolicyOptions {
+ /**
+ * Called once for each change of a field, after its subscribers and before the state-change delegate. A restore and a reset store every field they
+ * write before the first call they make, and each call of theirs reads the camera's whole restored or reset state.
+ */
+ readonly fieldChanged?: (change: OperatingModeChange) => void
+ /**
+ * Whether the camera's accessory is published, as the camera controller reads it from the context its accessory last handed it, read at each query of
+ * whether the camera is in service. Published by default.
+ */
+ readonly published?: () => boolean
+ /**
+ * Whether the plugin has stated its camera's source away, as the camera controller holds it, read at each query of whether the camera is in service.
+ * Not away by default.
+ */
+ readonly sourceAway?: () => boolean
+}
+
+/**
+ * What a stream service's gate reads: `open` where the service may start a stream, `switched off` where the user's switch does not allow streaming or
+ * the service's own Streaming Enabled is off, and `out of service` where the user's switches allow it and the camera is out of service. The user's switch
+ * is read first: a camera switched off and out of service at once reads `switched off`.
+ */
+export type StreamGate = 'open' | 'switched off' | 'out of service'
+
+type OperatingModeSubscriber = (value: boolean) => void
+
+type DerivationListener = (value: boolean) => void
+
+// The derivations of the whole camera, in the order a recompute tells them: the user's switches alone first, then each together with the camera in
+// service, which means going out of service tells the kept tiers, then the recordings, then each stream service, and last recording allowed together with the
+// accessory published, which reads nothing of the source. A switch-off or an unpublish ends the recording before the clips.
+const CAMERA_DERIVATIONS = [
+ 'streamingAllowed',
+ 'recordingAllowed',
+ 'streamingInService',
+ 'recordingInService',
+ 'recordingPublished',
+] as const
+
+type CameraDerivation = typeof CAMERA_DERIVATIONS[number]
+
+// The derivations of each stream service, by its key, in the order a recompute and a change of the service's own Streaming Enabled tell them, after the
+// camera's own: whether the service may start or hold a stream before its Status Active. A switch-off ends a service's sessions before its Status Active
+// is written.
+const SERVICE_DERIVATIONS = [
+ 'streamOpen',
+ 'statusActive',
+] as const
+
+type ServiceDerivation = typeof SERVICE_DERIVATIONS[number]
+
+// A derivation keeps its listeners and the value they last heard: a recompute that leaves the value unmoved tells none of them.
+interface Derivation {
+ readonly compute: () => boolean
+ readonly listeners: DerivationListener[]
+ last: boolean
+}
+
+// A projection pairs the characteristic that projects a field with the service that carries it. A pass over that service can tell which of its projections it dropped.
+interface Projection {
+ readonly characteristic: Characteristic
+ readonly service: Service
+}
+
+// A stream service's bound Streaming Enabled and the policy's listener on it, kept together so a rebind of the key removes that listener at once.
+interface StreamingEnabledBinding {
+ readonly characteristic: Characteristic
+ readonly listener: () => void
+}
+
+type FieldCharacteristic = readonly [OperatingModeField, WithUUID<{ new (): Characteristic }>]
+
+// One field a restore or a reset writes and the value it writes there.
+interface FieldWrite {
+ readonly field: OperatingModeField
+ readonly value: boolean
+}
+
+// A field no characteristic projects holds the value a factory reset gives it.
+const DEFAULTS: Readonly> = {
+ recordingActive: false,
+ recordingAudioActive: false,
+ eventSnapshotsActive: true,
+ homeKitCameraActive: true,
+ periodicSnapshotsActive: true,
+ globalStreamingEnabled: true,
+ operatingModeIndicator: true,
+ manuallyDisabled: false,
+ nightVision: false,
+ thirdPartyCameraActive: false,
+ motionEnabled: true,
+}
+
+// These are the fields only a camera with the camera capabilities block projects, which a layout saved without the block lacks.
+const CAPABILITY_BLOCK_FIELDS = [
+ 'globalStreamingEnabled',
+ 'operatingModeIndicator',
+ 'manuallyDisabled',
+ 'nightVision',
+ 'thirdPartyCameraActive',
+ 'motionEnabled',
+] as const
+
+// A restore and a reset store the fields in this order and then tell of them in it, the camera state the sensors mirror coming after the snapshot fields.
+const WRITE_ORDER: readonly OperatingModeField[] = [
+ 'recordingActive',
+ 'recordingAudioActive',
+ 'eventSnapshotsActive',
+ 'periodicSnapshotsActive',
+ 'homeKitCameraActive',
+ ...CAPABILITY_BLOCK_FIELDS,
+]
+
+// Every projection of these fields takes admin-only write. A write through any projection, which the refresh carries to every other, needs an admin.
+const ADMIN_ONLY_FIELDS: ReadonlySet = new Set([
+ 'recordingActive',
+ 'eventSnapshotsActive',
+ 'periodicSnapshotsActive',
+ 'homeKitCameraActive',
+ 'operatingModeIndicator',
+ 'motionEnabled',
+])
+
+// Each of these lists the field characteristics one subscribed service can carry, read when a pass runs, after the definitions have populated the characteristic types.
+function globalOperatingModeFields(): FieldCharacteristic[] {
+ return [
+ ['homeKitCameraActive', Characteristic.HomeKitCameraActive],
+ ['globalStreamingEnabled', Characteristic.StreamingEnabled],
+ ['operatingModeIndicator', Characteristic.CameraOperatingModeIndicator],
+ ['manuallyDisabled', Characteristic.ManuallyDisabled],
+ ['nightVision', Characteristic.NightVision],
+ ['thirdPartyCameraActive', Characteristic.ThirdPartyCameraActive],
+ ]
+}
+
+function cameraCapabilitiesFields(): FieldCharacteristic[] {
+ return [
+ ['manuallyDisabled', Characteristic.ManuallyDisabled],
+ ]
+}
+
+function motionSensorFields(): FieldCharacteristic[] {
+ return [
+ ['motionEnabled', Characteristic.MotionEnabled],
+ ]
+}
+
+function cameraOperatingModeFields(): FieldCharacteristic[] {
+ return [
+ ['homeKitCameraActive', Characteristic.HomeKitCameraActive],
+ ['eventSnapshotsActive', Characteristic.EventSnapshotsActive],
+ ['periodicSnapshotsActive', Characteristic.PeriodicSnapshotsActive],
+ ['operatingModeIndicator', Characteristic.CameraOperatingModeIndicator],
+ ['manuallyDisabled', Characteristic.ManuallyDisabled],
+ ['nightVision', Characteristic.NightVision],
+ ['thirdPartyCameraActive', Characteristic.ThirdPartyCameraActive],
+ ]
+}
+
+// A write from HomeKit or the plugin's setValue is a write, and every other change is the plugin surfacing a value it holds. A stream service's own
+// Streaming Enabled reports its changes through the same mapping.
+export function changeReason(reason: ChangeReason): CameraChangeReason {
+ return reason === ChangeReason.WRITE
+ ? 'write'
+ : 'update'
+}
+
+// The refresh writes a field's value as its projection's format holds it: it writes what a HomeKit controller would.
+function projectedValue(characteristic: Characteristic, value: boolean): boolean | number {
+ if (characteristic.props.format === Formats.BOOL) {
+ return value
+ }
+
+ return value
+ ? 1
+ : 0
+}
+
+/**
+ * The one owner of a camera's operating mode. Each characteristic that expresses a field is its projection, and how the policy holds the field follows the
+ * number of projections. With none, the field reads its default and a restore or a reset writes nothing: no value reaches a gate that no characteristic
+ * could change. A restore on a camera with the capabilities block, which the policy knows by the global service's bind, holds a field only the block projects
+ * instead, for `serialize` and for the field's first projection, which the bind seeds with it, and a reset drops it. With one, the policy reads the field
+ * through it, and every write that reaches the characteristic, a direct assignment of its value included, reaches the gates that query the policy. With two
+ * or more, the policy stores the field, seeded from the first projection when the second binds, and a write through any projection sets the stored value and
+ * refreshes every other one; a direct assignment to one projection then reaches no gate, because no change event carries it to the others.
+ *
+ * A write stores the field in its projections and then tells of it, in one order: the field's subscribers, the derivations, the field-change hook, then the
+ * state-change delegate. A change event's write tells as soon as it stores. A restore and a reset store every field they write before they tell of any.
+ * Each change they tell is read against the camera's whole restored or reset state, never one where a field they write still holds its earlier value,
+ * and a field a listener writes to another value while they tell stands, told by that write's own change and not again by them. A characteristic's own
+ * change event arrives as its field is stored, which means a write a listener of one makes while a restore or a reset still stores is a change event's write like
+ * any other: it is told at once, against the fields stored so far, and a field later in the write order then takes the restore's or the reset's value and
+ * is told again. The refresh writes each projection under a guard naming the field, and the change event it causes returns at the policy's own listener
+ * rather than running the write again. A binding or an unbinding moves the field only when the source of its reading changes, and runs no subscriber, hook
+ * or delegate.
+ *
+ * Beside the user's switches the policy answers whether the camera is in service: its accessory is published, which the camera controller reads from the
+ * context its accessory hands it, and the plugin has not stated its source away, which the controller holds, the policy reading each through its option
+ * at each query and storing neither. `streamingAllowed` and `recordingAllowed` keep the user's switches alone, and the library's own gates read each
+ * together with the camera in service, through `streamingInService` and `recordingInService`, and a stream service's gate, {@link streamGate}, reads
+ * streaming in service beside the service's own Streaming Enabled. A hub's clips read `recordingPublished`, recording allowed together with the accessory
+ * published and nothing of the source. A source stated away leaves a clip in flight to finish. The controller calls {@link serviceChanged} at each
+ * change of a cause, which recomputes every derivation.
+ */
+export class OperatingModePolicy implements Disposable {
+ private readonly projections = new Map()
+ private readonly stored = new Map()
+ private readonly subscribers = new Map()
+ private readonly streams: Characteristic[] = []
+ private readonly streamingEnabled = new Map()
+ private readonly serviceDerivations: Readonly>> = {
+ statusActive: new Map(),
+ streamOpen: new Map(),
+ }
+
+ private readonly cameraDerivations = new Map()
+ private readonly published: () => boolean
+ private readonly sourceAway: () => boolean
+ private fieldChanged?: (change: OperatingModeChange) => void
+ private stateChangeDelegate?: StateChangeDelegate
+
+ /**
+ * The removal of every listener the policy adds to a characteristic or a service, run once at disposal.
+ */
+ private readonly listeners = new DisposableStack()
+
+ /**
+ * The capability block fields a restore wrote on a camera with the block while no characteristic projected them, each kept until its first projection
+ * binds.
+ */
+ private readonly held = new Map()
+
+ /**
+ * The camera's `CameraOperatingMode` service, kept from the recording bind so the global service's bind can reach its optional characteristics.
+ */
+ private cameraOperatingMode?: CameraOperatingMode
+
+ /**
+ * The camera's `CameraGlobalOperatingMode` service, while one projects the fields only it carries. Its bind also marks a camera with the capabilities
+ * block, which `restore` and `serialize` read to tell such a camera from one without the block.
+ */
+ private globalOperatingMode?: CameraGlobalOperatingMode
+
+ /**
+ * The field the refresh is writing. The change event each of its writes causes returns at the policy's listener.
+ */
+ private refreshing?: OperatingModeField
+
+ /**
+ * A restored slice that defines a field no service of this camera projects, carried untouched so `serialize` writes it back until a factory reset.
+ */
+ private carried?: OperatingModeState
+
+ /**
+ * @param options - The field-change hook and the readers of whether the camera's accessory is published, published by default, and whether its source
+ * is away, not away by default.
+ * @param options.fieldChanged - Called once for each change of a field, after its subscribers and before the state-change delegate, a restore and a
+ * reset storing every field they write before the first call they make. Each call of theirs reads the camera's whole restored or reset state.
+ * @param options.published - Whether the camera's accessory is published, read at each query of whether the camera is in service.
+ * @param options.sourceAway - Whether the camera's source is stated away, read at each query of whether the camera is in service.
+ */
+ constructor({ fieldChanged, published = () => true, sourceAway = () => false }: OperatingModePolicyOptions = {}) {
+ this.fieldChanged = fieldChanged
+ this.published = published
+ this.sourceAway = sourceAway
+ }
+
+ /**
+ * Whether recording is active, as `CameraRecordingManagement`'s `Active` projects it.
+ */
+ get recordingActive(): boolean {
+ return this.read('recordingActive')
+ }
+
+ /**
+ * Whether recordings carry audio, as `CameraRecordingManagement`'s `RecordingAudioActive` projects it.
+ */
+ get recordingAudioActive(): boolean {
+ return this.read('recordingAudioActive')
+ }
+
+ /**
+ * Whether event snapshots are allowed, as `CameraOperatingMode`'s `EventSnapshotsActive` projects it.
+ */
+ get eventSnapshotsActive(): boolean {
+ return this.read('eventSnapshotsActive')
+ }
+
+ /**
+ * Whether the camera is on, as each `HomeKitCameraActive` projects it.
+ */
+ get homeKitCameraActive(): boolean {
+ return this.read('homeKitCameraActive')
+ }
+
+ /**
+ * Whether periodic snapshots are allowed, as `CameraOperatingMode`'s `PeriodicSnapshotsActive` projects it.
+ */
+ get periodicSnapshotsActive(): boolean {
+ return this.read('periodicSnapshotsActive')
+ }
+
+ /**
+ * Whether the camera streams at all, as `CameraGlobalOperatingMode`'s `StreamingEnabled` projects it.
+ */
+ get globalStreamingEnabled(): boolean {
+ return this.read('globalStreamingEnabled')
+ }
+
+ /**
+ * Whether the camera's status light is on, as each `CameraOperatingModeIndicator` projects it.
+ */
+ get operatingModeIndicator(): boolean {
+ return this.read('operatingModeIndicator')
+ }
+
+ /**
+ * Whether the camera is manually disabled, as each `ManuallyDisabled` projects it.
+ */
+ get manuallyDisabled(): boolean {
+ return this.read('manuallyDisabled')
+ }
+
+ /**
+ * Whether night vision is on, as each `NightVision` projects it.
+ */
+ get nightVision(): boolean {
+ return this.read('nightVision')
+ }
+
+ /**
+ * Whether another ecosystem is using the camera, as each `ThirdPartyCameraActive` projects it.
+ */
+ get thirdPartyCameraActive(): boolean {
+ return this.read('thirdPartyCameraActive')
+ }
+
+ /**
+ * Whether motion detection is on, as the motion sensor's `MotionEnabled` projects it.
+ */
+ get motionEnabled(): boolean {
+ return this.read('motionEnabled')
+ }
+
+ /**
+ * Whether a legacy stream's `Active` is on.
+ * @param index - The stream's index.
+ * @returns The stream's `Active`.
+ */
+ streamActive(index: number): boolean {
+ return !!this.streams[index].value
+ }
+
+ /**
+ * The legacy streaming rule: a stream is disabled while its `Active`, the camera or streaming as a whole is off, or while the camera is manually disabled.
+ * @param index - The stream's index.
+ * @returns Whether the stream refuses to stream.
+ */
+ legacyStreamingDisabled(index: number): boolean {
+ return !this.streamActive(index) || !this.homeKitCameraActive || !this.globalStreamingEnabled || this.manuallyDisabled
+ }
+
+ /**
+ * Whether the camera lets any stream run: it is on, streaming as a whole is on, and it is not manually disabled.
+ * @returns Whether streaming is allowed.
+ */
+ streamingAllowed(): boolean {
+ return this.homeKitCameraActive && this.globalStreamingEnabled && !this.manuallyDisabled
+ }
+
+ /**
+ * Whether the camera lets a recording run: recording is active, the camera is on, and it is not manually disabled.
+ * @returns Whether recording is allowed.
+ */
+ recordingAllowed(): boolean {
+ return this.recordingActive && this.homeKitCameraActive && !this.manuallyDisabled
+ }
+
+ /**
+ * Whether the camera is in service: its accessory is published and its source is not stated away.
+ * @returns Whether the camera is in service.
+ */
+ inService(): boolean {
+ return this.published() && !this.sourceAway()
+ }
+
+ /**
+ * Whether the library's own streams may run: streaming is allowed and the camera is in service.
+ * @returns Whether streaming is allowed and the camera is in service.
+ */
+ streamingInService(): boolean {
+ return this.streamingAllowed() && this.inService()
+ }
+
+ /**
+ * Whether the library's own recordings may run: recording is allowed and the camera is in service.
+ * @returns Whether recording is allowed and the camera is in service.
+ */
+ recordingInService(): boolean {
+ return this.recordingAllowed() && this.inService()
+ }
+
+ /**
+ * Whether a hub's clips may run: recording is allowed and the camera's accessory is published, whatever the plugin states of the camera's source. A
+ * clip a hub uploads finishes with what its recording served while the source is away, and the user's switches and an unpublish still end it.
+ * @returns Whether recording is allowed and the accessory is published.
+ */
+ recordingPublished(): boolean {
+ return this.recordingAllowed() && this.published()
+ }
+
+ /**
+ * A stream service's Status Active: its gate is not switched off, which means it follows the user's switches and the service's own Streaming Enabled alone and
+ * stays on while the camera is out of service.
+ * @param serviceKey - The stream service's key in the camera's service map.
+ * @returns Whether the user's switches and the service's Streaming Enabled allow the service to stream.
+ */
+ statusActive(serviceKey: string): boolean {
+ return this.streamGate(serviceKey) !== 'switched off'
+ }
+
+ /**
+ * Whether a stream service may start or hold a stream: its gate is open, the user's switches and its own Streaming Enabled allowing it and the camera in
+ * service.
+ * @param serviceKey - The stream service's key in the camera's service map.
+ * @returns Whether the service may start or hold a stream.
+ */
+ streamOpen(serviceKey: string): boolean {
+ return this.streamGate(serviceKey) === 'open'
+ }
+
+ /**
+ * A stream service's gate: `switched off` while streaming is not allowed or the service's own `StreamingEnabled` is off, `out of service` while the
+ * user's switches allow it and the camera is out of service, and `open` otherwise. A service's Status Active reads it not switched off, a service starts
+ * or holds a stream where it reads open, and a Setup Endpoints or a Solicit Offer write fails with the communication failure where it reads out of
+ * service, a WebRTC service's Solicit Offer answering Privacy Mode Active where it reads switched off.
+ * @param serviceKey - The stream service's key in the camera's service map.
+ * @returns The service's gate.
+ */
+ streamGate(serviceKey: string): StreamGate {
+ const streamingEnabled = this.streamingEnabled.get(serviceKey)
+
+ if (!this.streamingAllowed() || ((streamingEnabled !== undefined) && !streamingEnabled.characteristic.value)) {
+ return 'switched off'
+ }
+
+ return this.inService()
+ ? 'open'
+ : 'out of service'
+ }
+
+ /**
+ * Recomputes every derivation after a cause of whether the camera is in service changed, telling each listener of a derivation that moved.
+ */
+ serviceChanged(): void {
+ this.recomputeDerivations()
+ }
+
+ /**
+ * Binds each field the recording services project to its characteristic and marks the admin-only ones.
+ * @param recordingManagement - The camera's `CameraRecordingManagement` service.
+ * @param operatingMode - The camera's `CameraOperatingMode` service.
+ */
+ bindRecording(recordingManagement: CameraRecordingManagement, operatingMode: CameraOperatingMode): void {
+ this.cameraOperatingMode = operatingMode
+
+ this.bind('recordingActive', recordingManagement.getCharacteristic(Characteristic.Active), recordingManagement)
+ this.bind('recordingAudioActive', recordingManagement.getCharacteristic(Characteristic.RecordingAudioActive), recordingManagement)
+ this.bind('homeKitCameraActive', operatingMode.getCharacteristic(Characteristic.HomeKitCameraActive), operatingMode)
+ this.bind('eventSnapshotsActive', operatingMode.getCharacteristic(Characteristic.EventSnapshotsActive), operatingMode)
+ this.bind('periodicSnapshotsActive', operatingMode.getCharacteristic(Characteristic.PeriodicSnapshotsActive), operatingMode)
+ }
+
+ /**
+ * Binds the fields `CameraGlobalOperatingMode` projects, then the optional characteristics of a recording camera's `CameraOperatingMode`, which only a
+ * camera with the global service projects, and follows each of the services' configuration changes. A field characteristic a plugin adds later is
+ * bound and one it removes is dropped.
+ * @param service - The camera's `CameraGlobalOperatingMode` service.
+ */
+ bindGlobalOperatingMode(service: CameraGlobalOperatingMode): void {
+ this.globalOperatingMode = service
+
+ this.bind('homeKitCameraActive', service.getCharacteristic(Characteristic.HomeKitCameraActive), service)
+ this.bind('globalStreamingEnabled', service.getCharacteristic(Characteristic.StreamingEnabled), service)
+ this.bind('operatingModeIndicator', service.getCharacteristic(Characteristic.CameraOperatingModeIndicator), service)
+ this.follow(service, globalOperatingModeFields)
+
+ if (this.cameraOperatingMode) {
+ this.follow(this.cameraOperatingMode, cameraOperatingModeFields)
+ }
+ }
+
+ /**
+ * Binds `CameraCapabilities`' `ManuallyDisabled` while the service carries it and follows the service's configuration changes, as the global service's
+ * bind does.
+ * @param service - The camera's `CameraCapabilities` service.
+ */
+ bindCameraCapabilities(service: CameraCapabilities): void {
+ this.follow(service, cameraCapabilitiesFields)
+ }
+
+ /**
+ * Binds the motion sensor's `MotionEnabled`, adding it when the service lacks it, and follows the service's configuration changes, as the global service's
+ * bind does. Only a camera with the capabilities block calls it.
+ * @param service - The camera's `MotionSensor` service.
+ */
+ bindMotionSensor(service: MotionSensor): void {
+ const added = !service.testCharacteristic(Characteristic.MotionEnabled)
+ const characteristic = service.getCharacteristic(Characteristic.MotionEnabled)
+
+ // A new boolean characteristic reads false, and the first projection becomes the field's source, which is why one this bind adds takes the field's reading first.
+ // A value a restore held reaches it at the bind.
+ if (added) {
+ characteristic.updateValue(this.read('motionEnabled'))
+ }
+
+ this.follow(service, motionSensorFields)
+ }
+
+ /**
+ * Binds a stream service's `StreamingEnabled`, which {@link streamGate} reads for the service's key. A change of it recomputes that key's derivations
+ * alone, whether it may stream and then its Status Active, because the stream service that owns it saves it in its own slice. Binding the key to another
+ * characteristic removes the policy's listener from the earlier one at once, and a write to that one tells the key's derivations nothing.
+ * @param serviceKey - The stream service's key in the camera's service map.
+ * @param characteristic - The service's `StreamingEnabled`.
+ */
+ bindStreamingEnabled(serviceKey: string, characteristic: Characteristic): void {
+ const previous = this.streamingEnabled.get(serviceKey)
+
+ if (previous?.characteristic === characteristic) {
+ return
+ }
+
+ previous?.characteristic.removeListener(CharacteristicEventTypes.CHANGE, previous.listener)
+
+ const listener = (): void => this.notifyService(serviceKey)
+ characteristic.on(CharacteristicEventTypes.CHANGE, listener)
+ this.listeners.defer(() => characteristic.removeListener(CharacteristicEventTypes.CHANGE, listener))
+ this.streamingEnabled.set(serviceKey, { characteristic, listener })
+ this.notifyService(serviceKey)
+ }
+
+ /**
+ * Binds a legacy stream's `Active`, which {@link streamActive} and {@link legacyStreamingDisabled} read for the stream's index.
+ * @param index - The stream's index.
+ * @param service - The stream's `CameraRTPStreamManagement` service.
+ */
+ bindStream(index: number, service: CameraRTPStreamManagement): void {
+ this.streams[index] = service.getCharacteristic(Characteristic.Active)
+ }
+
+ /**
+ * Registers a side effect of a field, run once for each change of the field, before the state-change delegate.
+ * @param field - The field.
+ * @param subscriber - The side effect, given the field's new value.
+ */
+ subscribe(field: OperatingModeField, subscriber: OperatingModeSubscriber): void {
+ const subscribers = this.subscribers.get(field)
+ if (subscribers) {
+ subscribers.push(subscriber)
+ } else {
+ this.subscribers.set(field, [subscriber])
+ }
+ }
+
+ /**
+ * Registers a listener of a derivation of the whole camera, told the new value each time it moves: `streamingAllowed` and `recordingAllowed`, the
+ * user's switches alone, `streamingInService` and `recordingInService`, each of those together with the camera in service, or `recordingPublished`,
+ * recording allowed together with the accessory published, which reads nothing of the source and is told after `recordingInService`.
+ * @param derivation - The derivation.
+ * @param listener - The listener.
+ */
+ subscribeDerivation(derivation: CameraDerivation, listener: DerivationListener): void
+ /**
+ * Registers a listener of a stream service's derivation, told the new value each time it moves: `statusActive`, its Status Active, which the user's
+ * switches and its own Streaming Enabled move, or `streamOpen`, whether it may start or hold a stream, which the camera's service moves as well. Every
+ * key's `streamOpen` listeners are told before any key's `statusActive` listeners.
+ * @param derivation - `statusActive` or `streamOpen`.
+ * @param listener - The listener.
+ * @param serviceKey - The stream service's key in the camera's service map.
+ */
+ subscribeDerivation(derivation: 'statusActive' | 'streamOpen', listener: DerivationListener, serviceKey: string): void
+ subscribeDerivation(derivation: CameraDerivation | ServiceDerivation, listener: DerivationListener, serviceKey = ''): void {
+ if ((derivation !== 'statusActive') && (derivation !== 'streamOpen')) {
+ let camera = this.cameraDerivations.get(derivation)
+ if (!camera) {
+ camera = this.derivation(() => this[derivation]())
+ this.cameraDerivations.set(derivation, camera)
+ }
+
+ camera.listeners.push(listener)
+ return
+ }
+
+ const keyed = this.serviceDerivations[derivation]
+ let service = keyed.get(serviceKey)
+ if (!service) {
+ service = this.derivation(() => this[derivation](serviceKey))
+ keyed.set(serviceKey, service)
+ }
+
+ service.listeners.push(listener)
+ }
+
+ /**
+ * Restores a persisted operating mode, writing each field the slice defines and leaving a field it lacks as the policy holds it. Every field it writes is
+ * stored before any is told: a subscriber, a derivation listener and the field-change hook each read the whole restored state at every change it
+ * tells, and a derivation it moves is told once, a write made from a characteristic's own change event while it stores apart, as the class comment
+ * states. On a camera without the capabilities block, which the policy knows by the absence of the global service's bind, a slice that defines a field
+ * only the block projects is carried for {@link serialize}. On a camera with the block, such a field none of the camera's characteristics projects is
+ * held for {@link serialize} and for its first projection, which the bind seeds with it, and reaches no gate meanwhile.
+ * @param state - The persisted operating mode.
+ */
+ restore(state: Partial): void {
+ if (!this.globalOperatingMode) {
+ this.carried = CAPABILITY_BLOCK_FIELDS.some(field => state[field] !== undefined)
+ ? this.carry(state)
+ : undefined
+ }
+
+ const writes: FieldWrite[] = []
+
+ for (const field of WRITE_ORDER) {
+ const value = state[field]
+
+ if (value === undefined) {
+ continue
+ }
+
+ if (this.globalOperatingMode && (this.projections.get(field) ?? []).length === 0 && (CAPABILITY_BLOCK_FIELDS as readonly OperatingModeField[]).includes(field)) {
+ this.held.set(field, value)
+ } else {
+ writes.push({ field, value })
+ }
+ }
+
+ this.writeAll(writes, 'restore')
+ }
+
+ /**
+ * Gives every field its default and drops a carried slice and every held field, as a factory reset does. Every default is stored before any field is
+ * told, as at a restore, and each change reads the whole reset state.
+ */
+ reset(): void {
+ this.carried = undefined
+ this.held.clear()
+ this.writeAll(WRITE_ORDER.map(field => ({ field, value: DEFAULTS[field] })), 'reset')
+ }
+
+ /**
+ * The operating mode to persist: the fields while a characteristic projects any, a held field at the value a restore held for it, each field only a camera
+ * with the capabilities block projects taken from a carried slice on a camera without the block, and otherwise the carried slice.
+ * @returns The operating mode, or `undefined` when no characteristic projects it and no slice is carried.
+ */
+ serialize(): OperatingModeState | undefined {
+ if (!this.projected()) {
+ return this.carried && { ...this.carried }
+ }
+
+ const state: OperatingModeState = {
+ recordingActive: this.recordingActive,
+ recordingAudioActive: this.recordingAudioActive,
+ eventSnapshotsActive: this.eventSnapshotsActive,
+ homeKitCameraActive: this.homeKitCameraActive,
+ periodicSnapshotsActive: this.periodicSnapshotsActive,
+ }
+
+ for (const field of CAPABILITY_BLOCK_FIELDS) {
+ const value = this.globalOperatingMode
+ ? this.held.get(field) ?? this.read(field)
+ : this.carried?.[field]
+
+ if (value !== undefined) {
+ state[field] = value
+ }
+ }
+
+ return state
+ }
+
+ /**
+ * Sets the delegate each change of a field calls after the field's side effects, which is how the camera's state is saved.
+ * @param delegate - The delegate, or `undefined` to call none.
+ */
+ setupStateChangeDelegate(delegate?: StateChangeDelegate): void {
+ this.stateChangeDelegate = delegate
+ }
+
+ /**
+ * Removes every listener the policy added and drops every subscriber, every derivation listener, the field-change hook and the state-change delegate.
+ * No change reaches anyone afterward. It keeps answering reads through the characteristics it bound, because a stream a removed camera held still
+ * queries it. Safe to call more than once.
+ */
+ [Symbol.dispose](): void {
+ this.listeners.dispose()
+ this.subscribers.clear()
+ this.cameraDerivations.clear()
+
+ for (const name of SERVICE_DERIVATIONS) {
+ this.serviceDerivations[name].clear()
+ }
+
+ this.fieldChanged = undefined
+ this.stateChangeDelegate = undefined
+ }
+
+ private projected(): boolean {
+ for (const projections of this.projections.values()) {
+ if (projections.length > 0) {
+ return true
+ }
+ }
+
+ return false
+ }
+
+ private read(field: OperatingModeField): boolean {
+ const projections = this.projections.get(field) ?? []
+
+ switch (projections.length) {
+ case 0:
+ return DEFAULTS[field]
+ case 1:
+ return !!projections[0].characteristic.value
+ default:
+ return this.stored.get(field) ?? DEFAULTS[field]
+ }
+ }
+
+ // A change event's path, which tells of the field as soon as it stores it. The event names its origin, which the store skips, since it holds the value
+ // already.
+ private write(field: OperatingModeField, value: boolean, reason: CameraChangeReason, origin?: Characteristic): void {
+ if (this.store(field, value, origin)) {
+ this.tell(field, value, reason)
+ }
+ }
+
+ // A restore's and a reset's path. It stores every write and then tells of each stored field in the order it was handed: each change it tells is read
+ // against the camera's whole restored or reset state. A field that reads another value than the one stored here was written by a listener since, and
+ // that write told of it already, which is why the field is skipped.
+ private writeAll(writes: readonly FieldWrite[], reason: CameraChangeReason): void {
+ const stored: FieldWrite[] = []
+
+ for (const write of writes) {
+ if (this.store(write.field, write.value)) {
+ stored.push(write)
+ }
+ }
+
+ for (const { field, value } of stored) {
+ if (this.read(field) === value) {
+ this.tell(field, value, reason)
+ }
+ }
+ }
+
+ // Writes the value to the field's projections, every one but a change event's origin, and answers whether any characteristic projects the field, since
+ // a field none projects reads its default and has nothing to tell.
+ private store(field: OperatingModeField, value: boolean, origin?: Characteristic): boolean {
+ const projections = this.projections.get(field) ?? []
+
+ if (projections.length === 0) {
+ return false
+ }
+
+ if (projections.length > 1) {
+ this.stored.set(field, value)
+ this.refresh(field, value, projections.filter(projection => projection.characteristic !== origin))
+ } else if (!origin) {
+ this.refresh(field, value, projections)
+ }
+
+ return true
+ }
+
+ // Tells of a stored field in one order: its subscribers, the derivations, the field-change hook, then the state-change delegate.
+ private tell(field: OperatingModeField, value: boolean, reason: CameraChangeReason): void {
+ for (const subscriber of this.subscribers.get(field) ?? []) {
+ subscriber(value)
+ }
+
+ this.recomputeDerivations()
+ this.fieldChanged?.({ field, value, reason })
+ this.stateChangeDelegate?.()
+ }
+
+ // Writes the value to each projection under the guard, put back afterward: the change event each write causes returns at the listener.
+ private refresh(field: OperatingModeField, value: boolean, projections: readonly Projection[]): void {
+ const previous = this.refreshing
+ this.refreshing = field
+
+ try {
+ for (const { characteristic } of projections) {
+ characteristic.updateValue(projectedValue(characteristic, value))
+ }
+ } finally {
+ this.refreshing = previous
+ }
+ }
+
+ // Refreshes only the projections that read a value other than the field's, as a bind or an unbind does, and one that agrees fires no change event.
+ private align(field: OperatingModeField, value: boolean, projections: readonly Projection[]): void {
+ this.refresh(field, value, projections.filter(projection => !!projection.characteristic.value !== value))
+ }
+
+ private bind(field: OperatingModeField, characteristic: Characteristic, service: Service): void {
+ let projections = this.projections.get(field)
+ if (!projections) {
+ projections = []
+ this.projections.set(field, projections)
+ }
+
+ if (projections.some(projection => projection.characteristic === characteristic)) {
+ return
+ }
+
+ projections.push({ characteristic, service })
+
+ const listener = (change: CharacteristicChange): void => {
+ if (this.refreshing !== field) {
+ this.write(field, !!change.newValue, changeReason(change.reason), characteristic)
+ }
+ }
+ characteristic.on(CharacteristicEventTypes.CHANGE, listener)
+ this.listeners.defer(() => characteristic.removeListener(CharacteristicEventTypes.CHANGE, listener))
+
+ // The first projection becomes the field's source, taking under the refresh guard a value a restore held for it, and the seed runs no write. The second
+ // seeds the stored value from the first, and a later one takes the stored value.
+ if (projections.length === 1) {
+ const held = this.held.get(field)
+
+ if (held !== undefined) {
+ this.held.delete(field)
+ this.refresh(field, held, projections)
+ }
+
+ this.recomputeDerivations()
+ } else {
+ if (projections.length === 2) {
+ this.stored.set(field, !!projections[0].characteristic.value)
+ }
+
+ this.align(field, this.stored.get(field) ?? DEFAULTS[field], [projections[projections.length - 1]])
+ }
+
+ // The mark lands after the bind, and the configuration change its setProps emits finds the characteristic already held.
+ if (ADMIN_ONLY_FIELDS.has(field)) {
+ characteristic.setProps({
+ adminOnlyAccess: [Access.WRITE],
+ })
+ }
+ }
+
+ // The listeners a removed characteristic carried went with it, and dropping it leaves only the field's source to settle.
+ private unbind(field: OperatingModeField, projection: Projection): void {
+ const projections = this.projections.get(field) ?? []
+ projections.splice(projections.indexOf(projection), 1)
+
+ if (projections.length === 0) {
+ this.recomputeDerivations()
+ } else if (projections.length === 1) {
+ const value = this.stored.get(field) ?? DEFAULTS[field]
+ this.stored.delete(field)
+ this.align(field, value, projections)
+ }
+ }
+
+ // Runs one pass over the service at once and another at each of its configuration changes. A pass that finds the projections unchanged does nothing: a
+ // change that adds or removes no field characteristic, the admin-only mark's own setProps among them, costs nothing.
+ private follow(service: Service, fields: () => FieldCharacteristic[]): void {
+ this.reconcile(service, fields())
+
+ const listener = (): void => this.reconcile(service, fields())
+ service.on(ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE, listener)
+ this.listeners.defer(() => service.removeListener(ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE, listener))
+ }
+
+ // Drops each projection whose characteristic the service has removed, then binds each field characteristic it carries that the policy does not hold,
+ // telling them apart by identity, which is why a characteristic a plugin replaces is dropped and its replacement bound.
+ private reconcile(service: Service, fields: readonly FieldCharacteristic[]): void {
+ for (const [field] of fields) {
+ const dropped = (this.projections.get(field) ?? [])
+ .filter(projection => projection.service === service && !service.characteristics.includes(projection.characteristic))
+
+ for (const projection of dropped) {
+ this.unbind(field, projection)
+ }
+ }
+
+ for (const [field, type] of fields) {
+ const characteristic = service.characteristics.find(candidate => candidate.UUID === type.UUID)
+
+ if (characteristic) {
+ this.bind(field, characteristic, service)
+ }
+ }
+ }
+
+ private derivation(compute: () => boolean): Derivation {
+ return {
+ compute,
+ listeners: [],
+ last: compute(),
+ }
+ }
+
+ // The camera's own derivations first, then every key's derivations of each kind in turn: every key's streamOpen listeners hear before any key's
+ // statusActive listeners.
+ private recomputeDerivations(): void {
+ for (const name of CAMERA_DERIVATIONS) {
+ this.notify(this.cameraDerivations.get(name))
+ }
+
+ for (const name of SERVICE_DERIVATIONS) {
+ for (const derivation of this.serviceDerivations[name].values()) {
+ this.notify(derivation)
+ }
+ }
+ }
+
+ // One key's derivations, at a change of the service's own Streaming Enabled, which moves nothing of any other key.
+ private notifyService(serviceKey: string): void {
+ for (const name of SERVICE_DERIVATIONS) {
+ this.notify(this.serviceDerivations[name].get(serviceKey))
+ }
+ }
+
+ private notify(derivation?: Derivation): void {
+ if (!derivation) {
+ return
+ }
+
+ const value = derivation.compute()
+ if (value === derivation.last) {
+ return
+ }
+
+ derivation.last = value
+ for (const listener of derivation.listeners) {
+ listener(value)
+ }
+ }
+
+ // A carried slice keeps every field the restored slice defines and fills a persisted field it lacks with the policy's reading. The slice serialize
+ // writes back is whole.
+ private carry(state: Partial): OperatingModeState {
+ const carried: OperatingModeState = {
+ recordingActive: state.recordingActive ?? this.recordingActive,
+ recordingAudioActive: state.recordingAudioActive ?? this.recordingAudioActive,
+ eventSnapshotsActive: state.eventSnapshotsActive ?? this.eventSnapshotsActive,
+ homeKitCameraActive: state.homeKitCameraActive ?? this.homeKitCameraActive,
+ periodicSnapshotsActive: state.periodicSnapshotsActive ?? this.periodicSnapshotsActive,
+ }
+
+ for (const field of CAPABILITY_BLOCK_FIELDS) {
+ const value = state[field]
+
+ if (value !== undefined) {
+ carried[field] = value
+ }
+ }
+
+ return carried
+ }
+}
diff --git a/src/lib/camera/RTPStreamManagement.spec.ts b/src/lib/camera/RTPStreamManagement.spec.ts
index d5787d558..222e981a1 100644
--- a/src/lib/camera/RTPStreamManagement.spec.ts
+++ b/src/lib/camera/RTPStreamManagement.spec.ts
@@ -1,198 +1,91 @@
import type { MockInstance } from 'vitest'
-import type {
- CameraRecordingOptions,
- RecordingPacket,
-} from '../camera/index.js'
-import type {
- CameraControllerOptions,
- CameraRecordingDelegate,
- CameraStreamingDelegate,
- PrepareStreamCallback,
-} from '../controller/index.js'
+import type { CameraControllerOptions, PrepareStreamCallback } from '../controller/index.js'
import type { HAPConnection } from '../util/eventedhttp.js'
-import type {
- CameraStreamingOptions,
- RTPStreamManagement,
-} from './RTPStreamManagement.js'
+import type { CameraStreamingOptions, PrepareStreamRequest, PrepareStreamResponse } from './RTPStreamManagement.js'
import { Buffer } from 'node:buffer'
-import util from 'node:util'
+import { format } from 'node:util'
import createDebug from 'debug'
+import tweetnacl from 'tweetnacl'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { Accessory } from '../Accessory.js'
import {
- AudioBitrate,
- AudioRecordingCodecType,
- AudioRecordingSamplerate,
+ buildMockConnection,
+ buildSetupEndpointsTlv,
+ createCameraControllerOptions,
+ MockDelegate,
+ mockRecordingOptions,
+ mockStreamingOptions,
+ SETUP_ENDPOINTS_DISABLED_SUITE,
+ SETUP_ENDPOINTS_HUB_ANSWER,
+ SETUP_ENDPOINTS_HUB_REQUEST,
+ SETUP_ENDPOINTS_NARROW_PORTS,
+} from '../../test-utils/cameraFixtures.js'
+import { HAPHTTPClient } from '../../test-utils/HAPHTTPClient.js'
+import { PairVerifyClient } from '../../test-utils/PairVerifyClient.js'
+import { Accessory, AccessoryEventTypes, Categories, MDNSAdvertiser } from '../Accessory.js'
+import {
AudioStreamingCodecType,
AudioStreamingSamplerate,
- H264Level,
- H264Profile,
- MediaContainerType,
- VideoCodecType,
} from '../camera/index.js'
import { Characteristic } from '../Characteristic.js'
-import {
- CameraController,
-} from '../controller/index.js'
+import { CameraController } from '../controller/index.js'
import { HAPStatus } from '../HAPServer.js'
+import { AccessoryInfo, PermissionTypes } from '../model/AccessoryInfo.js'
import { IdentifierCache } from '../model/IdentifierCache.js'
+import { awaitEventOnce } from '../util/promise-utils.js'
import * as tlv from '../util/tlv.js'
import * as uuid from '../util/uuid.js'
+import { decodeSetupEndpointsResponse, encodeSetupEndpointsRequest, SetupEndpointsStatus } from './capabilities/setupEndpoints.js'
import RTPProxy from './RTPProxy.js'
-import {
- SRTPCryptoSuites,
-} from './RTPStreamManagement.js'
+import { RTPStreamManagement, SRTPCryptoSuites, StreamRequestTypes } from './RTPStreamManagement.js'
import '../definitions/index.js'
-class MockDelegate implements CameraStreamingDelegate, CameraRecordingDelegate {
- handleSnapshotRequest(): void {
- throw new Error('Unsupported!')
- }
-
- handleStreamRequest(): void {
- throw new Error('Unsupported!')
- }
-
- prepareStream(): void {
- throw new Error('Unsupported!')
- }
-
- async* handleRecordingStreamRequest(): AsyncGenerator {
- yield {
- data: Buffer.alloc(64, 0),
- isLast: true,
- }
- }
-
- closeRecordingStream(): void {}
-
- updateRecordingActive(): void {}
-
- updateRecordingConfiguration(): void {}
+// The keys and salts of the hub request and of the hub answer, each run of bytes counting up from its first.
+const HUB_REQUEST_KEYS = {
+ videoKey: Buffer.from('0102030405060708090a0b0c0d0e0f10', 'hex'),
+ videoSalt: Buffer.from('1112131415161718191a1b1c1d1e', 'hex'),
+ audioKey: Buffer.from('2122232425262728292a2b2c2d2e2f30', 'hex'),
+ audioSalt: Buffer.from('3132333435363738393a3b3c3d3e', 'hex'),
}
-
-const baseStreamingOptions: CameraStreamingOptions = {
- supportedCryptoSuites: [SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80],
- video: {
- codec: {
- profiles: [H264Profile.BASELINE, H264Profile.MAIN, H264Profile.HIGH],
- levels: [H264Level.LEVEL3_1, H264Level.LEVEL3_2, H264Level.LEVEL4_0],
- },
- resolutions: [
- [1920, 1080, 30],
- [1280, 720, 30],
- [320, 240, 15],
- ],
- },
- audio: {
- twoWayAudio: true,
- codecs: [
- {
- type: AudioStreamingCodecType.AAC_ELD,
- samplerate: AudioStreamingSamplerate.KHZ_24,
- },
- ],
- },
+const HUB_ANSWER_KEYS = {
+ videoKey: Buffer.from('a1a2a3a4a5a6a7a8a9aaabacadaeafb0', 'hex'),
+ videoSalt: Buffer.from('b1b2b3b4b5b6b7b8b9babbbcbdbe', 'hex'),
+ audioKey: Buffer.from('c1c2c3c4c5c6c7c8c9cacbcccdcecfd0', 'hex'),
+ audioSalt: Buffer.from('d1d2d3d4d5d6d7d8d9dadbdcddde', 'hex'),
}
-const baseRecordingOptions: CameraRecordingOptions = {
- prebufferLength: 4000,
- mediaContainerConfiguration: [
- {
- type: MediaContainerType.FRAGMENTED_MP4,
- fragmentLength: 8000,
- },
- ],
+// The session the hub request names.
+const HUB_SESSION = 'a1b2c3d4-0000-4000-8000-0000000000b1'
+
+// The prepared stream the hub answer encodes: its ports, SSRCs, keys and salts.
+const HUB_PREPARE_RESPONSE: PrepareStreamResponse = {
video: {
- type: VideoCodecType.H264,
- parameters: baseStreamingOptions.video.codec,
- resolutions: baseStreamingOptions.video.resolutions,
+ port: 51010,
+ ssrc: 0x0A0B0C0D,
+ srtp_key: HUB_ANSWER_KEYS.videoKey,
+ srtp_salt: HUB_ANSWER_KEYS.videoSalt,
},
audio: {
- codecs: [
- {
- type: AudioRecordingCodecType.AAC_ELD,
- audioChannels: 1,
- bitrateMode: AudioBitrate.VARIABLE,
- samplerate: AudioRecordingSamplerate.KHZ_48,
- },
- ],
+ port: 51012,
+ ssrc: 0x0E0F1011,
+ srtp_key: HUB_ANSWER_KEYS.audioKey,
+ srtp_salt: HUB_ANSWER_KEYS.audioSalt,
},
}
-function buildControllerOptions(streamingOptions: CameraStreamingOptions): CameraControllerOptions {
- const delegate = new MockDelegate()
- return {
- cameraStreamCount: 2,
- delegate,
- streamingOptions,
- recording: {
- options: baseRecordingOptions,
- delegate,
- },
- sensors: { motion: true, occupancy: true },
- }
+// The delegate answers each preparation with the hub answer's ports, SSRCs, keys and salts.
+function answerWithHubAnswer(): MockInstance {
+ return vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(((_request: unknown, callback: PrepareStreamCallback) => {
+ callback(undefined, HUB_PREPARE_RESPONSE)
+ }) as () => void)
}
-// matches the private enums in RTPStreamManagement.ts
-const SetupEndpointsTypes = {
- SESSION_ID: 0x01,
- CONTROLLER_ADDRESS: 0x03,
- VIDEO_SRTP_PARAMETERS: 0x04,
- AUDIO_SRTP_PARAMETERS: 0x05,
-} as const
-const AddressTypes = {
- ADDRESS_VERSION: 0x01,
- ADDRESS: 0x02,
- VIDEO_RTP_PORT: 0x03,
- AUDIO_RTP_PORT: 0x04,
-} as const
-const SRTPParametersTypes = {
- SRTP_CRYPTO_SUITE: 0x01,
- MASTER_KEY: 0x02,
- MASTER_SALT: 0x03,
-} as const
-
-function buildSetupEndpointsTlv(withPorts = true, sessionId = '11111111-1111-1111-1111-111111111111'): string {
- const addressTlv = withPorts
- ? tlv.encode(
- AddressTypes.ADDRESS_VERSION, 0x00, // IPV4
- AddressTypes.ADDRESS, '127.0.0.1',
- AddressTypes.VIDEO_RTP_PORT, tlv.writeUInt16(5000),
- AddressTypes.AUDIO_RTP_PORT, tlv.writeUInt16(5001),
- )
- : tlv.encode(
- AddressTypes.ADDRESS_VERSION, 0x00, // IPV4
- AddressTypes.ADDRESS, '127.0.0.1',
- )
- const srtpTlv = tlv.encode(
- SRTPParametersTypes.SRTP_CRYPTO_SUITE, SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80,
- SRTPParametersTypes.MASTER_KEY, Buffer.alloc(16),
- SRTPParametersTypes.MASTER_SALT, Buffer.alloc(14),
- )
- const payload = tlv.encode(
- SetupEndpointsTypes.SESSION_ID, uuid.write(sessionId),
- SetupEndpointsTypes.CONTROLLER_ADDRESS, addressTlv,
- SetupEndpointsTypes.VIDEO_SRTP_PARAMETERS, srtpTlv,
- SetupEndpointsTypes.AUDIO_SRTP_PARAMETERS, srtpTlv,
- )
- return payload.toString('base64')
-}
-
-function buildMockConnection(): HAPConnection {
- return {
- localAddress: '127.0.0.1',
- getLocalAddress: vi.fn().mockReturnValue('127.0.0.1'),
- setMaxListeners: vi.fn(),
- getMaxListeners: vi.fn().mockReturnValue(10),
- on: vi.fn(),
- removeListener: vi.fn(),
- } as unknown as HAPConnection
+function buildControllerOptions(streamingOptions: CameraStreamingOptions): CameraControllerOptions {
+ return createCameraControllerOptions(mockRecordingOptions, streamingOptions)
}
function prepareOk(_request: unknown, callback: PrepareStreamCallback) {
@@ -245,7 +138,7 @@ describe('RTPStreamManagement', () => {
describe('streaming options shared by all streams', () => {
it('should leave the lists of the plugin alone', () => {
const options: CameraStreamingOptions = {
- ...baseStreamingOptions,
+ ...mockStreamingOptions,
supportedCryptoSuites: [],
audio: {
codecs: [],
@@ -268,7 +161,7 @@ describe('RTPStreamManagement', () => {
{ type: AudioStreamingCodecType.OPUS, samplerate: AudioStreamingSamplerate.KHZ_24 },
]
const options: CameraStreamingOptions = {
- ...baseStreamingOptions,
+ ...mockStreamingOptions,
audio: { codecs },
}
@@ -287,7 +180,7 @@ describe('RTPStreamManagement', () => {
let controller: CameraController
beforeEach(() => {
- controller = new CameraController(buildControllerOptions(baseStreamingOptions))
+ controller = new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions))
controller.constructServices()
controller.configureServices()
})
@@ -332,25 +225,56 @@ describe('RTPStreamManagement', () => {
describe('debug output', () => {
it('should not contain the SRTP keys of a stream', () => {
- const controller = new CameraController(buildControllerOptions(baseStreamingOptions))
+ const controller = new CameraController(buildControllerOptions(mockStreamingOptions))
controller.constructServices()
controller.configureServices()
const rtp = controller.streamManagements[0] as RTPStreamManagement
vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(() => undefined)
+ // Each stream's key and salt is a run of bytes no other field of the request holds, so finding one in the output can only mean it was printed.
+ const request = encodeSetupEndpointsRequest({
+ sessionIdentifier: '11111111-1111-1111-1111-111111111111',
+ controllerAddress: {
+ addressVersion: 'ipv4',
+ address: '127.0.0.1',
+ videoRTPPort: 5000,
+ audioRTPPort: 5001,
+ },
+ videoSRTPParameters: {
+ cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80,
+ masterKey: HUB_REQUEST_KEYS.videoKey,
+ masterSalt: HUB_REQUEST_KEYS.videoSalt,
+ },
+ audioSRTPParameters: {
+ cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80,
+ masterKey: HUB_REQUEST_KEYS.audioKey,
+ masterSalt: HUB_REQUEST_KEYS.audioSalt,
+ },
+ })
const namespaces = createDebug.disable()
createDebug.enable('HAP-NodeJS:Camera:RTPStreamManagement')
const lines: string[] = []
const log = vi.spyOn(createDebug, 'log').mockImplementation((...args: unknown[]) => {
- lines.push(util.format(...args))
+ lines.push(format(...args))
})
try {
// @ts-expect-error: private method access
- rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), vi.fn(), buildMockConnection())
+ rtp.handleSetupEndpoints(request, vi.fn(), buildMockConnection())
const output = lines.join('\n')
expect(output).toContain('11111111-1111-1111-1111-111111111111') // the line with the session was written
- expect(output).not.toContain('Master')
+ // Every form a debug line could print a secret in: hex, the spaced hex of a buffer's inspection, base64, the raw bytes and the decimal bytes.
+ for (const secret of Object.values(HUB_REQUEST_KEYS)) {
+ for (const form of [
+ secret.toString('hex'),
+ [...secret].map(byte => byte.toString(16).padStart(2, '0')).join(' '),
+ secret.toString('base64'),
+ secret.toString('latin1'),
+ [...secret].join(','),
+ ]) {
+ expect(output).not.toContain(form)
+ }
+ }
expect(output).not.toContain(' {
describe('debug output of the accessory', () => {
it('should not contain the SetupEndpoints value of a write, which holds the SRTP keys', async () => {
const accessory = new Accessory('Cam', uuid.generate('srtp keys in the accessory debug log'))
- const controller = new CameraController(buildControllerOptions(baseStreamingOptions))
+ const controller = new CameraController(buildControllerOptions(mockStreamingOptions))
accessory.configureController(controller)
accessory._identifierCache = new IdentifierCache('AA:BB:CC:DD:EE:FF')
accessory._assignIDs(accessory._identifierCache)
@@ -376,7 +300,7 @@ describe('RTPStreamManagement', () => {
createDebug.enable('HAP-NodeJS:*')
const lines: string[] = []
const log = vi.spyOn(createDebug, 'log').mockImplementation((...args: unknown[]) => {
- lines.push(util.format(...args))
+ lines.push(format(...args))
})
try {
// @ts-expect-error: private method access
@@ -401,7 +325,7 @@ describe('RTPStreamManagement', () => {
describe('a failed reconfigure', () => {
it('should tell the delegate to stop the stream of the session it gives up', () => {
- const controller = new CameraController(buildControllerOptions(baseStreamingOptions))
+ const controller = new CameraController(buildControllerOptions(mockStreamingOptions))
controller.constructServices()
controller.configureServices()
const rtp = controller.streamManagements[0] as RTPStreamManagement
@@ -449,10 +373,10 @@ describe('RTPStreamManagement', () => {
beforeEach(() => {
const proxyOptions: CameraStreamingOptions = {
- ...baseStreamingOptions,
+ ...mockStreamingOptions,
proxy: true,
}
- controller = new CameraController(buildControllerOptions(proxyOptions))
+ controller = new CameraController(createCameraControllerOptions(mockRecordingOptions, proxyOptions))
controller.constructServices()
controller.configureServices()
})
@@ -497,17 +421,17 @@ describe('RTPStreamManagement', () => {
expect(error!.message).toBe('socket creation failed')
})
- it('should set setupEndpointsResponse to ERROR status when proxy setup rejects', async () => {
+ it('answers a read with an ERROR status when proxy setup rejects', async () => {
setupSpy = vi.spyOn(RTPProxy.prototype, 'setup')
.mockImplementation(() => Promise.reject(new Error('bind failed')))
const rtp = controller.streamManagements[0] as RTPStreamManagement
- await new Promise((resolve) => {
- // @ts-expect-error: private method access
- rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), () => resolve(), buildMockConnection())
- })
+ const setupEndpoints = rtp.service.getCharacteristic(Characteristic.SetupEndpoints)
+ const connection = buildMockConnection()
- const response = (rtp as any).setupEndpointsResponse as string
+ await expect(setupEndpoints.handleSetRequest(buildSetupEndpointsTlv(), connection)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+
+ const response = await setupEndpoints.handleGetRequest(connection) as string
const decoded = tlv.decode(Buffer.from(response, 'base64'))
// SetupEndpointsResponseTypes.STATUS = 0x02; SetupEndpointsStatus.ERROR = 0x02
expect(decoded[0x02].readUInt8(0)).toBe(0x02)
@@ -519,7 +443,7 @@ describe('RTPStreamManagement', () => {
beforeEach(() => {
controller = new CameraController(buildControllerOptions({
- ...baseStreamingOptions,
+ ...mockStreamingOptions,
proxy: true,
}))
controller.constructServices()
@@ -568,7 +492,7 @@ describe('RTPStreamManagement', () => {
let controller: CameraController
beforeEach(() => {
- controller = new CameraController(buildControllerOptions(baseStreamingOptions))
+ controller = new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions))
controller.constructServices()
controller.configureServices()
})
@@ -592,11 +516,10 @@ describe('RTPStreamManagement', () => {
expect(rtp.sessionIdentifier).toBeUndefined()
// the next valid request must not be answered with BUSY
- await new Promise((resolve) => {
- // @ts-expect-error: private method access
- rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), () => resolve(), buildMockConnection())
- })
- const decoded = tlv.decode(Buffer.from((rtp as any).setupEndpointsResponse as string, 'base64'))
+ const setupEndpoints = rtp.service.getCharacteristic(Characteristic.SetupEndpoints)
+ const connection = buildMockConnection()
+ await expect(setupEndpoints.handleSetRequest(buildSetupEndpointsTlv(), connection)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ const decoded = tlv.decode(Buffer.from(await setupEndpoints.handleGetRequest(connection) as string, 'base64'))
// SetupEndpointsResponseTypes.STATUS = 0x02; SetupEndpointsStatus.BUSY = 0x01
expect(decoded[0x02].readUInt8(0)).not.toBe(0x01)
})
@@ -606,7 +529,7 @@ describe('RTPStreamManagement', () => {
let controller: CameraController
beforeEach(() => {
- controller = new CameraController(buildControllerOptions(baseStreamingOptions))
+ controller = new CameraController(buildControllerOptions(mockStreamingOptions))
controller.constructServices()
controller.configureServices()
})
@@ -639,19 +562,13 @@ describe('RTPStreamManagement', () => {
const connectionA = buildMockConnection()
const connectionB = buildMockConnection()
- await new Promise((resolve) => {
- // @ts-expect-error: private method access
- rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, sessionA), () => resolve(), connectionA)
- })
+ await characteristic.handleSetRequest(buildSetupEndpointsTlv(true, sessionA), connectionA)
const responseA = await read(connectionA)
// SetupEndpointsResponseTypes: SESSION_ID = 0x01, STATUS = 0x02; SetupEndpointsStatus: SUCCESS = 0x00, BUSY = 0x01
expect(uuid.unparse(responseA[0x01])).toBe(sessionA)
expect(responseA[0x02].readUInt8(0)).toBe(0x00)
- const callbackB = vi.fn()
- // @ts-expect-error: private method access
- rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, sessionB), callbackB, connectionB)
- expect(callbackB).toHaveBeenCalledExactlyOnceWith()
+ await expect(characteristic.handleSetRequest(buildSetupEndpointsTlv(true, sessionB), connectionB)).resolves.toBeUndefined()
// the controller which asked reads the answer for its own request, like before
const responseB = await read(connectionB)
@@ -661,13 +578,12 @@ describe('RTPStreamManagement', () => {
// the session which holds the stream still has its response
expect(await read(connectionA)).toEqual(responseA)
- expect(tlv.decode(Buffer.from(rtp.setupEndpointsResponse, 'base64'))).toEqual(responseA)
expect(await read(connectionB)).toEqual(responseB)
// once the stream is free again, everybody reads the default response, like before
// @ts-expect-error: private method access
rtp.handleSessionClosed()
- const idle = tlv.decode(Buffer.from(rtp.setupEndpointsResponse, 'base64'))
+ const idle = await read(buildMockConnection())
expect(await read(connectionB)).toEqual(idle)
expect(await read(connectionA)).toEqual(idle)
})
@@ -677,7 +593,7 @@ describe('RTPStreamManagement', () => {
let controller: CameraController
beforeEach(() => {
- controller = new CameraController(buildControllerOptions(baseStreamingOptions))
+ controller = new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions))
controller.constructServices()
controller.configureServices()
})
@@ -727,28 +643,31 @@ describe('RTPStreamManagement', () => {
prepareCallbacks.push(callback)
}
vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(prepareStream as () => void)
+ const characteristic = rtp.getService().getCharacteristic(Characteristic.SetupEndpoints)
+ const answers = async (connections: HAPConnection[]) => Promise.all(connections.map(async connection => characteristic.handleGetRequest(connection)))
const sessionA = '11111111-1111-1111-1111-111111111111'
const sessionB = '22222222-2222-2222-2222-222222222222'
+ const connectionA = buildMockConnection()
+ const connectionB = buildMockConnection()
const callbackA = vi.fn()
const callbackB = vi.fn()
- // @ts-expect-error: private method access
- rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, sessionA), callbackA, buildMockConnection())
+ // each write goes through the characteristic, which holds the answer its connection reads
+ characteristic.handleSetRequest(buildSetupEndpointsTlv(true, sessionA), connectionA).then(() => callbackA(), callbackA)
await vi.waitFor(() => expect(prepareCallbacks).toHaveLength(1))
// @ts-expect-error: private method access
rtp.handleSessionClosed() // e.g. the HAP connection closed while the delegate is still preparing
- // @ts-expect-error: private method access
- rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, sessionB), callbackB, buildMockConnection())
+ characteristic.handleSetRequest(buildSetupEndpointsTlv(true, sessionB), connectionB).then(() => callbackB(), callbackB)
await vi.waitFor(() => expect(prepareCallbacks).toHaveLength(2))
- const responseBefore = (rtp as any).setupEndpointsResponse
+ const answersBefore = await answers([connectionA, connectionB])
answer(prepareCallbacks[0]) // the late answer for the first session
- expect(callbackA).toHaveBeenCalledExactlyOnceWith(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ await vi.waitFor(() => expect(callbackA).toHaveBeenCalledExactlyOnceWith(HAPStatus.SERVICE_COMMUNICATION_FAILURE))
expect(callbackB).not.toHaveBeenCalled()
expect(rtp.sessionIdentifier).toEqual(sessionB)
expect(rtp.streamStatus).toBe(1) // StreamingStatus.IN_USE
- expect((rtp as any).setupEndpointsResponse).toBe(responseBefore)
+ expect(await answers([connectionA, connectionB])).toEqual(answersBefore)
})
it('should answer with an error when a delayed response is missing the audio info', async () => {
@@ -766,33 +685,375 @@ describe('RTPStreamManagement', () => {
}
vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(prepareStream as () => void)
+ const setupEndpoints = rtp.service.getCharacteristic(Characteristic.SetupEndpoints)
+ const connection = buildMockConnection()
const errors: Error[] = []
const onUncaught = (error: Error) => errors.push(error)
process.on('uncaughtException', onUncaught)
- try {
- const error = await new Promise((resolve, reject) => {
- setTimeout(() => reject(new Error('SetupEndpoints callback was never called')), 500)
- // @ts-expect-error: private method access
- rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), err => resolve(err as Error | undefined), buildMockConnection())
- })
+ // The write must settle: a callback the management never calls fails the row rather than its timeout.
+ let timer: ReturnType | undefined
+ const neverAnswered = new Promise((_resolve, reject) => {
+ timer = setTimeout(() => reject(new Error('SetupEndpoints callback was never called')), 500)
+ })
- expect(error).toBeInstanceOf(Error)
+ try {
+ await expect(Promise.race([
+ setupEndpoints.handleSetRequest(buildSetupEndpointsTlv(), connection),
+ neverAnswered,
+ ]))
+ .rejects
+ .toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
} finally {
+ clearTimeout(timer)
process.off('uncaughtException', onUncaught)
}
expect(errors).toEqual([])
expect(rtp.streamStatus).toBe(0) // StreamingStatus.AVAILABLE
- const decoded = tlv.decode(Buffer.from((rtp as any).setupEndpointsResponse as string, 'base64'))
+ const decoded = tlv.decode(Buffer.from(await setupEndpoints.handleGetRequest(connection) as string, 'base64'))
// SetupEndpointsResponseTypes.STATUS = 0x02; SetupEndpointsStatus.ERROR = 0x02
expect(decoded[0x02].readUInt8(0)).toBe(0x02)
})
})
+ describe('handleSetupEndpoints over the setup endpoints codec', () => {
+ const ACCESSORY_ADDRESS = '192.0.2.130'
+
+ let controller: CameraController
+ let rtp: RTPStreamManagement
+ let prepareStream: MockInstance
+
+ beforeEach(() => {
+ controller = new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions))
+ controller.constructServices()
+ controller.configureServices()
+ rtp = controller.streamManagements[0]
+ prepareStream = answerWithHubAnswer()
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ controller.handleFactoryReset()
+ })
+
+ // A connection whose local address is the accessory address the answer names.
+ function hubConnection(): HAPConnection {
+ return {
+ ...buildMockConnection(),
+ localAddress: ACCESSORY_ADDRESS,
+ getLocalAddress: vi.fn().mockReturnValue(ACCESSORY_ADDRESS),
+ } as unknown as HAPConnection
+ }
+
+ async function writeSetupEndpoints(value: string, connection: HAPConnection = hubConnection()): Promise {
+ await rtp.service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest(value, connection)
+ }
+
+ async function readSetupEndpoints(connection: HAPConnection): Promise {
+ return rtp.service.getCharacteristic(Characteristic.SetupEndpoints).handleGetRequest(connection)
+ }
+
+ it('answers a hub request with the hub answer and prepares its stream', async () => {
+ const connection = hubConnection()
+ await writeSetupEndpoints(SETUP_ENDPOINTS_HUB_REQUEST, connection)
+
+ await expect(readSetupEndpoints(connection)).resolves.toBe(SETUP_ENDPOINTS_HUB_ANSWER)
+ expect(prepareStream).toHaveBeenCalledTimes(1)
+ expect(prepareStream.mock.calls[0][0]).toEqual({
+ sessionID: HUB_SESSION,
+ sourceAddress: ACCESSORY_ADDRESS,
+ targetAddress: '192.0.2.19',
+ addressVersion: 'ipv4',
+ video: {
+ port: 50010,
+ srtpCryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80,
+ srtp_key: HUB_REQUEST_KEYS.videoKey,
+ srtp_salt: HUB_REQUEST_KEYS.videoSalt,
+ },
+ audio: {
+ port: 50012,
+ srtpCryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80,
+ srtp_key: HUB_REQUEST_KEYS.audioKey,
+ srtp_salt: HUB_REQUEST_KEYS.audioSalt,
+ },
+ } satisfies PrepareStreamRequest)
+ })
+
+ it('answers a second request while busy and an error once the session ends', async () => {
+ const first = hubConnection()
+ const second = hubConnection()
+ const neverWrote = hubConnection()
+ await writeSetupEndpoints(buildSetupEndpointsTlv(), first)
+ await writeSetupEndpoints(buildSetupEndpointsTlv(), second)
+
+ expect(decodeSetupEndpointsResponse(await readSetupEndpoints(first) as string)).toMatchObject({
+ status: SetupEndpointsStatus.SUCCESS,
+ sessionIdentifier: '11111111-1111-1111-1111-111111111111',
+ })
+ await expect(readSetupEndpoints(second)).resolves.toBe('ARARERERERERERERERERERERAgEB')
+
+ rtp.forceStop()
+
+ await expect(readSetupEndpoints(first)).resolves.toBe('AgEC')
+ await expect(readSetupEndpoints(second)).resolves.toBe('AgEC')
+ await expect(readSetupEndpoints(neverWrote)).resolves.toBe('AgEC')
+ })
+
+ it('releases a held answer at a factory reset, its writer then reading an error, and another at destroy the same way', async () => {
+ vi.spyOn(MockDelegate.prototype, 'handleStreamRequest').mockImplementation(() => undefined)
+ const reset = hubConnection()
+ const destroyed = hubConnection()
+
+ await writeSetupEndpoints(SETUP_ENDPOINTS_HUB_REQUEST, reset)
+ await expect(readSetupEndpoints(reset)).resolves.toBe(SETUP_ENDPOINTS_HUB_ANSWER)
+
+ rtp.handleFactoryReset()
+
+ await expect(readSetupEndpoints(reset)).resolves.toBe('AgEC')
+
+ // The reset ended the session with one STOP. The next writer prepares anew and holds a success answer.
+ await writeSetupEndpoints(buildSetupEndpointsTlv(), destroyed)
+ expect(decodeSetupEndpointsResponse(await readSetupEndpoints(destroyed) as string)).toMatchObject({
+ status: SetupEndpointsStatus.SUCCESS,
+ sessionIdentifier: '11111111-1111-1111-1111-111111111111',
+ })
+
+ rtp.destroy()
+
+ await expect(readSetupEndpoints(destroyed)).resolves.toBe('AgEC')
+ })
+
+ it('holds no answer from a prepare that settles after the stream turns off: its writer reads an error then and once the stream is back on', async () => {
+ const handleStreamRequest = vi.spyOn(MockDelegate.prototype, 'handleStreamRequest').mockImplementation(() => undefined)
+ const connection = hubConnection()
+ const prepared = new Promise((resolve) => {
+ prepareStream.mockImplementationOnce((_request: unknown, callback: PrepareStreamCallback) => resolve(callback))
+ })
+ const written = rtp.service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest(SETUP_ENDPOINTS_HUB_REQUEST, connection)
+ const answer = await prepared
+
+ rtp.service.updateCharacteristic(Characteristic.Active, false)
+ answer(undefined, HUB_PREPARE_RESPONSE)
+
+ expect(handleStreamRequest).not.toHaveBeenCalled()
+ await expect(written).resolves.toBeUndefined()
+ await expect(readSetupEndpoints(connection)).resolves.toBe('AgEC')
+ // The session ends with one STOP, sent once the prepare callback has returned, and its close listener stays the connection's only one, because the
+ // late answer holds nothing.
+ expect(rtp.streamStatus).toBe(0)
+ expect(handleStreamRequest).toHaveBeenCalledTimes(1)
+ expect(handleStreamRequest).toHaveBeenCalledWith({ sessionID: HUB_SESSION, type: StreamRequestTypes.STOP }, expect.any(Function))
+ expect(connection.on).toHaveBeenCalledTimes(1)
+
+ rtp.service.updateCharacteristic(Characteristic.Active, true)
+
+ await expect(readSetupEndpoints(connection)).resolves.toBe('AgEC')
+
+ const second = hubConnection()
+ await writeSetupEndpoints(SETUP_ENDPOINTS_HUB_REQUEST, second)
+
+ await expect(readSetupEndpoints(second)).resolves.toBe(SETUP_ENDPOINTS_HUB_ANSWER)
+ })
+
+ it('tells the delegate stop once for a live session at a force-stop and never for a stream without one', async () => {
+ const handleStreamRequest = vi.spyOn(MockDelegate.prototype, 'handleStreamRequest').mockImplementation(() => undefined)
+
+ rtp.forceStop()
+
+ expect(handleStreamRequest).not.toHaveBeenCalled()
+
+ await writeSetupEndpoints(SETUP_ENDPOINTS_HUB_REQUEST)
+ rtp.forceStop()
+ rtp.forceStop()
+
+ expect(handleStreamRequest).toHaveBeenCalledTimes(1)
+ expect(handleStreamRequest).toHaveBeenCalledWith({ sessionID: HUB_SESSION, type: StreamRequestTypes.STOP }, expect.any(Function))
+ expect(rtp.streamStatus).toBe(0)
+ })
+
+ it('tells the delegate stop once for a live session at a factory reset', async () => {
+ const handleStreamRequest = vi.spyOn(MockDelegate.prototype, 'handleStreamRequest').mockImplementation(() => undefined)
+ await writeSetupEndpoints(SETUP_ENDPOINTS_HUB_REQUEST)
+
+ rtp.handleFactoryReset()
+ rtp.handleFactoryReset()
+
+ expect(handleStreamRequest).toHaveBeenCalledTimes(1)
+ expect(handleStreamRequest).toHaveBeenCalledWith({ sessionID: HUB_SESSION, type: StreamRequestTypes.STOP }, expect.any(Function))
+ expect(rtp.streamStatus).toBe(0)
+ })
+
+ it('prepares a stream from one-byte ports and an ipv6 address', async () => {
+ await writeSetupEndpoints(SETUP_ENDPOINTS_NARROW_PORTS)
+
+ expect(prepareStream).toHaveBeenCalledTimes(1)
+ expect(prepareStream.mock.calls[0][0]).toMatchObject({
+ targetAddress: 'fe80::1',
+ addressVersion: 'ipv6',
+ video: { port: 80 },
+ audio: { port: 81 },
+ })
+ })
+
+ it('prepares a stream under the disabled suite with zero-length keys and salts', async () => {
+ await writeSetupEndpoints(SETUP_ENDPOINTS_DISABLED_SUITE)
+
+ const { audio, video } = prepareStream.mock.calls[0][0] as PrepareStreamRequest
+ for (const source of [video, audio]) {
+ expect(source.srtp_key).toEqual(Buffer.alloc(0))
+ expect(source.srtp_salt).toEqual(Buffer.alloc(0))
+ }
+ })
+
+ it('logs the length of each key and salt and never their bytes', async () => {
+ const previousNamespaces = createDebug.disable()
+ const originalLog = createDebug.log
+ const messages: string[] = []
+
+ createDebug.enable('HAP-NodeJS:Camera:RTPStreamManagement')
+ createDebug.log = (...args: unknown[]) => {
+ messages.push(format(...args))
+ }
+
+ try {
+ await writeSetupEndpoints(SETUP_ENDPOINTS_HUB_REQUEST)
+ } finally {
+ createDebug.log = originalLog
+ createDebug.enable(previousNamespaces)
+ }
+
+ const output = messages.join('\n')
+ expect(output).not.toContain(' {
+ // The value a management advertises for a streaming configuration's suites, the video options shared and the suites the row's own.
+ function advertised(srtp: { srtp: boolean } | { supportedCryptoSuites: SRTPCryptoSuites[] }): string {
+ return new RTPStreamManagement(0, { video: mockStreamingOptions.video, ...srtp } as CameraStreamingOptions, new MockDelegate()).supportedRTPConfiguration
+ }
+
+ it('advertises AgEA for srtp, AgEC without it and for an empty suite list, and both suites delimited', () => {
+ expect(advertised({ srtp: true })).toBe('AgEA')
+ expect(advertised({ srtp: false })).toBe('AgEC')
+ expect(advertised({ supportedCryptoSuites: [] })).toBe('AgEC')
+ expect(advertised({
+ supportedCryptoSuites: [SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, SRTPCryptoSuites.NONE],
+ })).toBe('AgEAAAACAQI=')
+ })
+ })
+
+ describe('setup endpoints over paired connections', () => {
+ const serverUsername = 'CA:FE:00:00:00:01'
+ const clientUsername = 'CA:FE:00:00:00:02'
+
+ let accessory: Accessory
+ let accessoryInfo: AccessoryInfo
+ let camera: CameraController
+ let clients: HAPHTTPClient[]
+ let clientInfo: { username: string, privateKey: Buffer, publicKey: Buffer }
+
+ beforeEach(async () => {
+ accessoryInfo = AccessoryInfo.create(serverUsername)
+ // @ts-expect-error: private access
+ accessoryInfo.setupID = Accessory._generateSetupID()
+ accessoryInfo.displayName = 'Camera'
+ accessoryInfo.category = Categories.IP_CAMERA
+ accessoryInfo.pincode = '031-45-154'
+ accessoryInfo.save = vi.fn()
+
+ const clientKeyPair = tweetnacl.sign.keyPair()
+ clientInfo = {
+ username: clientUsername,
+ privateKey: Buffer.from(clientKeyPair.secretKey),
+ publicKey: Buffer.from(clientKeyPair.publicKey),
+ }
+ accessoryInfo.addPairedClient(clientUsername, clientInfo.publicKey, PermissionTypes.ADMIN)
+
+ // The published accessory loads the paired record above in place of a stored one, as the published switch service of the Accessory spec does.
+ vi.spyOn(AccessoryInfo, 'load').mockReturnValue(accessoryInfo)
+ answerWithHubAnswer()
+
+ accessory = new Accessory('Camera', uuid.generate('setup endpoints over paired connections'))
+ camera = new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions))
+ accessory.configureController(camera)
+ clients = []
+ })
+
+ afterEach(async () => {
+ for (const client of clients) {
+ client.destroy()
+ }
+ await accessory.destroy()
+ vi.restoreAllMocks()
+ })
+
+ // A connection that pair-verifies with the published accessory, as a hub's does, and keeps its encrypted session.
+ async function pairedClient(port: number): Promise {
+ const client = new HAPHTTPClient('127.0.0.1', port)
+ await client.connect()
+ clients.push(client)
+ client.enableEncryption(await new PairVerifyClient(client).sendPairVerify({
+ username: serverUsername,
+ publicKey: Buffer.from(accessoryInfo.signPk),
+ }, clientInfo))
+
+ return client
+ }
+
+ it('answers the writer\'s read with its own answer and another paired connection\'s read with an error', async () => {
+ const listening: Promise<[port: number, hostname: string]> = awaitEventOnce(accessory, AccessoryEventTypes.LISTENING)
+ await accessory.publish({
+ username: serverUsername,
+ pincode: accessoryInfo.pincode,
+ category: Categories.IP_CAMERA,
+ advertiser: MDNSAdvertiser.BONJOUR,
+ port: 0,
+ })
+ const [port] = await listening
+
+ const writer = await pairedClient(port)
+ const other = await pairedClient(port)
+ const id = {
+ aid: accessory.aid!,
+ iid: camera.streamManagements[0].service.getCharacteristic(Characteristic.SetupEndpoints).iid!,
+ }
+
+ await writer.sendCharacteristicWrite({
+ characteristics: [
+ { ...id, value: SETUP_ENDPOINTS_HUB_REQUEST },
+ ],
+ })
+
+ // A read's value, or the empty string for a read the accessory refused, which no row expects.
+ const read = async (client: HAPHTTPClient): Promise => {
+ const [data] = (await client.sendCharacteristicRead([id])).body.characteristics
+
+ return 'value' in data
+ ? data.value as string
+ : ''
+ }
+
+ expect(decodeSetupEndpointsResponse(await read(writer))).toMatchObject({
+ status: SetupEndpointsStatus.SUCCESS,
+ sessionIdentifier: HUB_SESSION,
+ })
+ expect(await read(other)).toBe('AgEC')
+ })
+ })
+
describe('a late error answer of a session which already ended', () => {
it('should leave the next session alone when the stop of an ended session fails late', async () => {
- const controller = new CameraController(buildControllerOptions(baseStreamingOptions))
+ const controller = new CameraController(buildControllerOptions(mockStreamingOptions))
controller.constructServices()
controller.configureServices()
const rtp = controller.streamManagements[0] as RTPStreamManagement
@@ -825,7 +1086,7 @@ describe('RTPStreamManagement', () => {
})
it('should leave the next session alone when the start of an ended session fails late', async () => {
- const controller = new CameraController(buildControllerOptions(baseStreamingOptions))
+ const controller = new CameraController(buildControllerOptions(mockStreamingOptions))
controller.constructServices()
controller.configureServices()
const rtp = controller.streamManagements[0] as RTPStreamManagement
@@ -867,7 +1128,7 @@ describe('RTPStreamManagement', () => {
describe('handleSetupEndpoints in proxy mode for a camera without audio', () => {
it('should answer the setup instead of failing on the missing audio response', async () => {
const options: CameraStreamingOptions = {
- ...baseStreamingOptions,
+ ...mockStreamingOptions,
proxy: true,
audio: { codecs: [] },
}
diff --git a/src/lib/camera/RTPStreamManagement.ts b/src/lib/camera/RTPStreamManagement.ts
index a4c3c13d3..e239cc479 100644
--- a/src/lib/camera/RTPStreamManagement.ts
+++ b/src/lib/camera/RTPStreamManagement.ts
@@ -1,9 +1,11 @@
import type { CharacteristicValue } from '../../types.js'
import type { CharacteristicSetCallback } from '../Characteristic.js'
-import type { CameraStreamingDelegate, ResourceRequestReason } from '../controller/CameraController.js'
-import type { StateChangeDelegate } from '../controller/Controller.js'
+import type { CameraStreamingDelegate } from '../controller/CameraController.js'
+import type { ControllerServiceMap, StateChangeDelegate } from '../controller/Controller.js'
import type { CameraRTPStreamManagement } from '../definitions/index.js'
import type { HAPConnection } from '../util/eventedhttp.js'
+import type { SetupEndpointsRequest } from './capabilities/setupEndpoints.js'
+import type { ResourceRequestReason } from './StreamingOptions.js'
import assert from 'node:assert'
import { Buffer } from 'node:buffer'
@@ -20,11 +22,23 @@ import { errorMessage } from '../util/errors.js'
import { HAPConnectionEvent } from '../util/eventedhttp.js'
import { HapStatusError } from '../util/hapStatusError.js'
import { once } from '../util/once.js'
+import { callDelegate, logDelegateRejection } from '../util/promise-utils.js'
import * as tlv from '../util/tlv.js'
import * as uuid from '../util/uuid.js'
+import {
+ decodeSetupEndpointsRequest,
+ encodeSetupEndpointsResponse,
+ SETUP_ENDPOINTS_ERROR,
+ SetupEndpointsStatus,
+ SRTPCryptoSuites,
+} from './capabilities/setupEndpoints.js'
+import { encodeSupportedRTPConfiguration } from './capabilities/supportedRtpConfiguration.js'
import RTPProxy from './RTPProxy.js'
const debug = createDebug('HAP-NodeJS:Camera:RTPStreamManagement')
+
+// The start of every stream's key in the camera's service map, which the stream's index ends.
+const SERVICE_KEY_PREFIX = 'streamManagement'
// ---------------------------------- TLV DEFINITIONS START ----------------------------------
enum StreamingStatusTypes {
@@ -152,61 +166,7 @@ export enum AudioSamplerate {
// ----------
-enum SupportedRTPConfigurationTypes {
- SRTP_CRYPTO_SUITE = 0x02,
-}
-
-/**
- * @group Camera
- */
-export enum SRTPCryptoSuites { // public API
- AES_CM_128_HMAC_SHA1_80 = 0x00,
- AES_CM_256_HMAC_SHA1_80 = 0x01,
- NONE = 0x02,
-}
-
-// ----------
-
-enum SetupEndpointsTypes {
- SESSION_ID = 0x01,
- CONTROLLER_ADDRESS = 0x03,
- VIDEO_SRTP_PARAMETERS = 0x04,
- AUDIO_SRTP_PARAMETERS = 0x05,
-}
-
-enum AddressTypes {
- ADDRESS_VERSION = 0x01,
- ADDRESS = 0x02,
- VIDEO_RTP_PORT = 0x03,
- AUDIO_RTP_PORT = 0x04,
-}
-
-enum IPAddressVersion {
- IPV4 = 0x00,
- IPV6 = 0x01,
-}
-
-enum SRTPParametersTypes {
- SRTP_CRYPTO_SUITE = 0x01,
- MASTER_KEY = 0x02, // 16 bytes for AES_CM_128_HMAC_SHA1_80; 32 bytes for AES_256_CM_HMAC_SHA1_80
- MASTER_SALT = 0x03, // 14 bytes
-}
-
-enum SetupEndpointsResponseTypes {
- SESSION_ID = 0x01,
- STATUS = 0x02,
- ACCESSORY_ADDRESS = 0x03,
- VIDEO_SRTP_PARAMETERS = 0x04,
- AUDIO_SRTP_PARAMETERS = 0x05,
- VIDEO_SSRC = 0x06,
- AUDIO_SSRC = 0x07,
-}
-
-enum SetupEndpointsStatus {
- SUCCESS = 0x00,
- BUSY = 0x01,
- ERROR = 0x02,
-}
+export { SRTPCryptoSuites } from './capabilities/setupEndpoints.js'
// ----------
@@ -575,12 +535,6 @@ export class RTPStreamManagement {
private ipVersion?: 'ipv4' | 'ipv6' // ip version for the current session
selectedConfiguration = '' // base64 representation of the currently selected configuration
- setupEndpointsResponse = '' // response of the SetupEndpoints Characteristic
- /**
- * The BUSY answers for the connections which asked for a stream while another session held it.
- * They are kept apart from {@link setupEndpointsResponse}, which belongs to the session which holds the stream.
- */
- private busySetupEndpointsResponses = new WeakMap()
/**
* @private
@@ -592,18 +546,16 @@ export class RTPStreamManagement {
videoProxy?: RTPProxy
/**
- * A RTPStreamManagement is considered disabled if `HomeKitCameraActive` is set to false.
- * We use a closure based approach to retrieve the value of this characteristic.
- * The characteristic is managed by the RecordingManagement.
+ * Answers whether streaming is disabled, when the owner of the operating mode supplies it. Without it, the management reads its own `Active`.
*/
- private readonly disabledThroughOperatingMode?: () => boolean
+ private readonly streamingDisabled?: () => boolean
constructor(
id: number,
options: CameraStreamingOptions,
delegate: CameraStreamingDelegate,
service?: CameraRTPStreamManagement,
- disabledThroughOperatingMode?: () => boolean,
+ streamingDisabled?: () => boolean,
) {
this.id = id
this.delegate = delegate
@@ -626,7 +578,11 @@ export class RTPStreamManagement {
throw new Error('Video parameters cannot be undefined in options')
}
- this.supportedRTPConfiguration = RTPStreamManagement._supportedRTPConfiguration(this.supportedCryptoSuites)
+ if (this.supportedCryptoSuites.length === 1 && this.supportedCryptoSuites[0] === SRTPCryptoSuites.NONE) {
+ debug('Client claims it doesn\'t support SRTP. The stream may stop working with future iOS releases.')
+ }
+
+ this.supportedRTPConfiguration = encodeSupportedRTPConfiguration(this.supportedCryptoSuites)
this.supportedVideoStreamConfiguration = RTPStreamManagement._supportedVideoStreamConfiguration(options.video)
this.supportedAudioStreamConfiguration = this._supportedAudioStreamConfiguration(options.audio)
@@ -635,14 +591,68 @@ export class RTPStreamManagement {
this.service = service || this.constructService(id)
this.setupServiceHandlers()
- this.resetSetupEndpointsResponse()
this.resetSelectedStreamConfiguration()
- this.disabledThroughOperatingMode = disabledThroughOperatingMode
+ this.streamingDisabled = streamingDisabled
+ }
+
+ /**
+ * The key a stream's service carries in the camera's service map.
+ * @param index - The stream's index.
+ * @returns `streamManagement` followed by the index.
+ * @private
+ */
+ static serviceKey(index: number): string {
+ return `${SERVICE_KEY_PREFIX}${index}`
+ }
+
+ /**
+ * Reconciles the stream services of a restored service map: a stream below the count is adopted from its saved service or created and inserted, and
+ * every saved stream whose index is at or past the count is deleted, whatever gaps the saved indexes leave. The map keeps no stream the camera does
+ * not run, none at all for a count of 0.
+ * @param serviceMap - The camera's service map, changed in place.
+ * @param count - The number of streams the camera runs.
+ * @param create - Builds a stream's management over its saved service, or over a new one when it is given none.
+ * @returns Whether the map changed.
+ * @private
+ */
+ static reconcile(serviceMap: ControllerServiceMap, count: number, create: (index: number, service?: CameraRTPStreamManagement) => RTPStreamManagement): boolean {
+ let modified = false
+
+ for (let i = 0; i < count; i++) {
+ const key = RTPStreamManagement.serviceKey(i)
+ const saved = serviceMap[key]
+
+ if (saved) {
+ create(i, saved)
+ } else {
+ serviceMap[key] = create(i).getService()
+ modified = true
+ }
+ }
+
+ // A saved key is a stream's when it is the key of its own index, which is why the walk reads every key the map holds rather than stopping at a gap.
+ for (const key of Object.keys(serviceMap)) {
+ const index = Number(key.slice(SERVICE_KEY_PREFIX.length))
+
+ if (key.startsWith(SERVICE_KEY_PREFIX) && (index >= count) && (key === RTPStreamManagement.serviceKey(index))) {
+ delete serviceMap[key]
+ modified = true
+ }
+ }
+
+ return modified
}
+ /**
+ * Ends the stream's session: a live session's delegate is told STOP for the stream it prepared, and a stream without one releases what it holds.
+ */
public forceStop(): void {
- this.handleSessionClosed()
+ if (this.activeConnection) {
+ this._handleStopStream()
+ } else {
+ this.handleSessionClosed()
+ }
}
getService(): CameraRTPStreamManagement {
@@ -650,17 +660,23 @@ export class RTPStreamManagement {
}
handleFactoryReset(): void {
+ // A reset ends a live session first and tells its delegate STOP for the stream it prepared, and no session outlives the reset in use.
+ if (this.activeConnection) {
+ this._handleStopStream()
+ }
+
this.resetSelectedStreamConfiguration()
- this.resetSetupEndpointsResponse()
+ this.releaseSetupEndpointsAnswers()
this.service.updateCharacteristic(Characteristic.Active, true)
- // on a factory reset the assumption is that all connections were already terminated and thus "_handleStopStream" was already called
}
public destroy(): void {
if (this.activeConnection) {
this._handleStopStream()
}
+
+ this.releaseSetupEndpointsAnswers()
}
private constructService(id: number): CameraRTPStreamManagement {
@@ -678,8 +694,15 @@ export class RTPStreamManagement {
// the active characteristic might not be present on some older configurations.
this.service.setCharacteristic(Characteristic.Active, true)
}
+ // The release comes before the state-change delegate, whose throw would otherwise leave a disabled stream's answers held.
this.service.getCharacteristic(Characteristic.Active)
- .on(CharacteristicEventTypes.CHANGE, () => this.stateChangeDelegate?.())
+ .on(CharacteristicEventTypes.CHANGE, () => {
+ if (this.streamingIsDisabled()) {
+ this.releaseSetupEndpointsAnswers()
+ }
+
+ this.stateChangeDelegate?.()
+ })
.setProps({
adminOnlyAccess: [Access.WRITE],
})
@@ -690,7 +713,6 @@ export class RTPStreamManagement {
this.service.setCharacteristic(Characteristic.SupportedAudioStreamConfiguration, this.supportedAudioStreamConfiguration)
this._updateStreamStatus(StreamingStatus.AVAILABLE) // reset streaming status to available
- this.service.setCharacteristic(Characteristic.SetupEndpoints, this.setupEndpointsResponse) // reset SetupEndpoints to default
this.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration)
.on(CharacteristicEventTypes.GET, (callback) => {
@@ -707,17 +729,11 @@ export class RTPStreamManagement {
})
.on(CharacteristicEventTypes.SET, this._handleSelectedStreamConfigurationWrite.bind(this))
+ // Setup Endpoints is transient and sensitive by its definition: a writer's answer is held for it and served ahead of this listener, which every
+ // other read reaches.
this.service.getCharacteristic(Characteristic.SetupEndpoints)
- .on(CharacteristicEventTypes.GET, (callback, _context, connection) => {
- if (this.streamingIsDisabled()) {
- callback(null, tlv.encode(
- SetupEndpointsResponseTypes.STATUS, SetupEndpointsStatus.ERROR,
- ).toString('base64'))
- return
- }
-
- // a connection which was told that the stream is busy reads that answer, everybody else the one of the session
- callback(null, (connection && this.busySetupEndpointsResponses.get(connection)) ?? this.setupEndpointsResponse)
+ .on(CharacteristicEventTypes.GET, (callback) => {
+ callback(null, SETUP_ENDPOINTS_ERROR)
})
.on(CharacteristicEventTypes.SET, (value, callback, _context, connection) => {
if (!connection) {
@@ -731,7 +747,8 @@ export class RTPStreamManagement {
private handleSessionClosed(): void { // called when the streaming was ended or aborted and needs to be cleaned up
this.resetSelectedStreamConfiguration()
- this.resetSetupEndpointsResponse()
+ // The class runs one session at a time. Every answer it holds names this session or a Busy this session caused, and none outlives it.
+ this.releaseSetupEndpointsAnswers()
if (this.activeConnection) {
this.activeConnection.removeListener(HAPConnectionEvent.CLOSED, this.activeConnectionClosedListener)
@@ -754,21 +771,15 @@ export class RTPStreamManagement {
}
private streamingIsDisabled(callback?: CharacteristicSetCallback): boolean {
- if (!this.service.getCharacteristic(Characteristic.Active).value) {
- if (callback) {
- callback(new HapStatusError(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE))
- }
- return true
- }
+ const disabled = this.streamingDisabled
+ ? this.streamingDisabled()
+ : !this.service.getCharacteristic(Characteristic.Active).value
- if (this.disabledThroughOperatingMode?.()) {
- if (callback) {
- callback(new HapStatusError(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE))
- }
- return true
+ if (disabled && callback) {
+ callback(new HapStatusError(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE))
}
- return false
+ return disabled
}
private _handleSelectedStreamConfigurationWrite(value: CharacteristicValue, callback: CharacteristicSetCallback): void {
@@ -1003,7 +1014,7 @@ export class RTPStreamManagement {
audio: audioInfo,
}
- this.delegate.handleStreamRequest(request, error => callback(error))
+ this.forwardStreamRequest(request, callback)
}
private handleReconfigureStream(videoConfiguration: Record, callback: CharacteristicSetCallback): void {
@@ -1038,7 +1049,7 @@ export class RTPStreamManagement {
video: reconfiguredVideoInfo,
}
- this.delegate.handleStreamRequest(request, error => callback(error))
+ this.forwardStreamRequest(request, callback)
}
private _handleStopStream(callback?: CharacteristicSetCallback): void {
@@ -1049,9 +1060,18 @@ export class RTPStreamManagement {
this.handleSessionClosed()
- this.delegate.handleStreamRequest(request, error => callback
- ? callback(error)
- : undefined)
+ this.forwardStreamRequest(request, callback)
+ }
+
+ // A stream request that answers a write leaves a synchronous throw to the write's handler, which answers HomeKit with the failure, and logs a rejection,
+ // which nothing awaits. A stop at a closed connection or a teardown answers no write, and callDelegate takes its throw as well.
+ private forwardStreamRequest(request: StreamingRequest, callback?: CharacteristicSetCallback): void {
+ const failure = `CameraStreamingDelegate failed to handle a ${request.type} stream request`
+ if (callback) {
+ logDelegateRejection(this.delegate.handleStreamRequest(request, error => callback(error)), failure)
+ } else {
+ callDelegate(() => this.delegate.handleStreamRequest(request, () => undefined), failure)
+ }
}
private handleSetupEndpoints(value: CharacteristicValue, callback: CharacteristicSetCallback, connection: HAPConnection): void {
@@ -1059,37 +1079,20 @@ export class RTPStreamManagement {
return
}
- let request: ReturnType
+ let request: SetupEndpointsRequest
try {
// parse and check every field before changing any state, so a malformed request can't leave the stream stuck as busy
- request = this.parseSetupEndpointsRequest(value)
+ request = decodeSetupEndpointsRequest(value as string)
} catch (error) {
debug('Failed to parse SetupEndpoints request: %s', errorMessage(error))
callback(HAPStatus.INVALID_VALUE_IN_REQUEST)
return
}
- const {
- sessionIdentifier,
- addressVersion,
- controllerAddress,
- targetVideoPort,
- targetAudioPort,
- videoCryptoSuite,
- videoMasterKey,
- videoMasterSalt,
- audioCryptoSuite,
- audioMasterKey,
- audioMasterSalt,
- } = request
+ const { sessionIdentifier, controllerAddress, videoSRTPParameters, audioSRTPParameters } = request
if (this.streamStatus !== StreamingStatus.AVAILABLE) {
- // only the connection which asked reads this answer: the response of the session which holds the stream stays
- this.busySetupEndpointsResponses.set(connection, tlv.encode(
- SetupEndpointsResponseTypes.SESSION_ID, uuid.write(sessionIdentifier),
- SetupEndpointsResponseTypes.STATUS, SetupEndpointsStatus.BUSY,
- ).toString('base64'))
- callback()
+ callback(undefined, encodeSetupEndpointsResponse({ status: SetupEndpointsStatus.BUSY, sessionIdentifier }))
return
}
@@ -1103,37 +1106,39 @@ export class RTPStreamManagement {
this.sessionIdentifier = sessionIdentifier
this._updateStreamStatus(StreamingStatus.IN_USE)
+ // The keys and salts are secrets and a debug log is often shared in public, which is why the line names each one's length and never its bytes.
debug(
'Session: ', sessionIdentifier,
- '\nControllerAddress: ', controllerAddress,
- '\nVideoPort: ', targetVideoPort,
- '\nAudioPort: ', targetAudioPort,
- '\nVideo Crypto: ', videoCryptoSuite,
- '\nAudio Crypto: ', audioCryptoSuite,
- // the SRTP master keys and salts are left out on purpose: debug logs get posted in public
+ '\nControllerAddress: ', controllerAddress.address,
+ '\nVideoPort: ', controllerAddress.videoRTPPort,
+ '\nAudioPort: ', controllerAddress.audioRTPPort,
+ '\nVideo Crypto: ', videoSRTPParameters.cryptoSuite,
+ '\nVideo Master Key Length: ', videoSRTPParameters.masterKey.length,
+ '\nVideo Master Salt Length: ', videoSRTPParameters.masterSalt.length,
+ '\nAudio Crypto: ', audioSRTPParameters.cryptoSuite,
+ '\nAudio Master Key Length: ', audioSRTPParameters.masterKey.length,
+ '\nAudio Master Salt Length: ', audioSRTPParameters.masterSalt.length,
)
const prepareRequest: PrepareStreamRequest = {
sessionID: sessionIdentifier,
sourceAddress: connection.localAddress,
- targetAddress: controllerAddress,
- addressVersion: addressVersion === IPAddressVersion.IPV6
- ? 'ipv6'
- : 'ipv4',
+ targetAddress: controllerAddress.address,
+ addressVersion: controllerAddress.addressVersion,
video: { // if suite is NONE, keys and salts are zero-length
- port: targetVideoPort,
+ port: controllerAddress.videoRTPPort,
- srtpCryptoSuite: videoCryptoSuite,
- srtp_key: videoMasterKey,
- srtp_salt: videoMasterSalt,
+ srtpCryptoSuite: videoSRTPParameters.cryptoSuite,
+ srtp_key: videoSRTPParameters.masterKey,
+ srtp_salt: videoSRTPParameters.masterSalt,
},
audio: {
- port: targetAudioPort,
+ port: controllerAddress.audioRTPPort,
- srtpCryptoSuite: audioCryptoSuite,
- srtp_key: audioMasterKey,
- srtp_salt: audioMasterSalt,
+ srtpCryptoSuite: audioSRTPParameters.cryptoSuite,
+ srtp_key: audioSRTPParameters.masterKey,
+ srtp_salt: audioSRTPParameters.masterSalt,
},
}
@@ -1144,9 +1149,7 @@ export class RTPStreamManagement {
if (this.requireProxy) {
try {
- prepareRequest.targetAddress = connection.getLocalAddress(addressVersion === IPAddressVersion.IPV6
- ? 'ipv6'
- : 'ipv4') // ip versions must be the same
+ prepareRequest.targetAddress = connection.getLocalAddress(controllerAddress.addressVersion) // ip versions must be the same
} catch (error) {
// the stream is marked as in use by now: free it and answer, or it stays blocked until the connection closes
debug(`Could not find the local address for the RTP proxy: ${errorMessage(error)}`)
@@ -1158,8 +1161,8 @@ export class RTPStreamManagement {
}
this.videoProxy = videoProxy = new RTPProxy({
- outgoingAddress: controllerAddress,
- outgoingPort: targetVideoPort,
+ outgoingAddress: controllerAddress.address,
+ outgoingPort: controllerAddress.videoRTPPort,
outgoingSSRC: crypto.randomBytes(4).readUInt32LE(0), // videoSSRC
disabled: false,
})
@@ -1168,8 +1171,8 @@ export class RTPStreamManagement {
if (!this.disableAudioProxy) {
this.audioProxy = audioProxy = new RTPProxy({
- outgoingAddress: controllerAddress,
- outgoingPort: targetAudioPort,
+ outgoingAddress: controllerAddress.address,
+ outgoingPort: controllerAddress.audioRTPPort,
outgoingSSRC: crypto.randomBytes(4).readUInt32LE(0), // audioSSRC
disabled: this.videoOnly,
})
@@ -1196,7 +1199,9 @@ export class RTPStreamManagement {
prepareRequest.audio.proxy_rtcp = audioProxy.incomingRTCPPort()
}
- this.delegate.prepareStream(prepareRequest, once((error?: Error, response?: PrepareStreamResponse) => {
+ // A throw from the delegate reaches the catch below, which answers the write, and the rejection of the promise an async delegate returns, which nothing
+ // awaits, is logged.
+ logDelegateRejection(this.delegate.prepareStream(prepareRequest, once((error?: Error, response?: PrepareStreamResponse) => {
if (this.sessionIdentifier !== sessionIdentifier) {
// The session ended while the delegate was preparing it (e.g. the connection closed), and another one
// may have started since. This answer must not touch that one.
@@ -1207,7 +1212,8 @@ export class RTPStreamManagement {
if (error || !response) {
debug(`PrepareStream request encountered an error: ${error ? error.message : undefined}`)
- this.handleSessionClosed() // resets the SetupEndpoints answer to a plain error
+
+ this.handleSessionClosed()
// an answer with neither an error nor a response must not tell the controller that the setup worked
callback(error ?? HAPStatus.SERVICE_COMMUNICATION_FAILURE)
} else {
@@ -1216,75 +1222,28 @@ export class RTPStreamManagement {
} catch (error) {
// the delegate usually calls back asynchronously, so nothing up the stack would catch this
debug(`Failed to build the SetupEndpoints response from the PrepareStreamResponse: ${errorMessage(error)}`)
- this.handleSessionClosed() // resets the SetupEndpoints answer to a plain error
+
+ this.handleSessionClosed()
callback(error instanceof Error
? error
: new Error(String(error)))
}
}
- }))
- }).catch((error: Error) => {
- debug(`RTP proxy setup failed: ${error.message}`)
+ })), 'CameraStreamingDelegate failed to prepare a stream')
+ }).catch((error: Error | undefined) => {
+ debug(`RTP proxy setup failed: ${errorMessage(error)}`)
+
+ // As above: the answer for a session that is no longer current leaves the current session alone.
if (this.sessionIdentifier !== sessionIdentifier) {
- callback(HAPStatus.SERVICE_COMMUNICATION_FAILURE) // as above: not the current session anymore
+ callback(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
return
}
- this.handleSessionClosed() // resets the SetupEndpoints answer to a plain error
+
+ this.handleSessionClosed()
callback(error)
})
}
- private parseSetupEndpointsRequest(value: CharacteristicValue) {
- const data = Buffer.from(value as string, 'base64')
- const objects = tlv.decode(data)
-
- const sessionIdentifier = uuid.unparse(objects[SetupEndpointsTypes.SESSION_ID])
-
- // Address
- const targetAddressPayload = objects[SetupEndpointsTypes.CONTROLLER_ADDRESS]
- const processedAddressInfo = tlv.decode(targetAddressPayload)
- const addressVersion = processedAddressInfo[AddressTypes.ADDRESS_VERSION].readUInt8(0)
- const controllerAddress = processedAddressInfo[AddressTypes.ADDRESS].toString('utf8')
- const targetVideoPort = processedAddressInfo[AddressTypes.VIDEO_RTP_PORT].readUInt16LE(0)
- const targetAudioPort = processedAddressInfo[AddressTypes.AUDIO_RTP_PORT].readUInt16LE(0)
-
- // Video SRTP Params
- const videoSRTPPayload = objects[SetupEndpointsTypes.VIDEO_SRTP_PARAMETERS]
- const processedVideoInfo = tlv.decode(videoSRTPPayload)
- const videoCryptoSuite: SRTPCryptoSuites = processedVideoInfo[SRTPParametersTypes.SRTP_CRYPTO_SUITE].readUInt8(0)
- const videoMasterKey = processedVideoInfo[SRTPParametersTypes.MASTER_KEY]
- const videoMasterSalt = processedVideoInfo[SRTPParametersTypes.MASTER_SALT]
-
- // Audio SRTP Params
- const audioSRTPPayload = objects[SetupEndpointsTypes.AUDIO_SRTP_PARAMETERS]
- const processedAudioInfo = tlv.decode(audioSRTPPayload)
- const audioCryptoSuite: SRTPCryptoSuites = processedAudioInfo[SRTPParametersTypes.SRTP_CRYPTO_SUITE].readUInt8(0)
- const audioMasterKey = processedAudioInfo[SRTPParametersTypes.MASTER_KEY]
- const audioMasterSalt = processedAudioInfo[SRTPParametersTypes.MASTER_SALT]
-
- // if the suite is NONE, keys and salts are zero-length
- if (videoCryptoSuite !== SRTPCryptoSuites.NONE && (!videoMasterKey || !videoMasterSalt)) {
- throw new Error('Video SRTP master key or salt is missing')
- }
- if (audioCryptoSuite !== SRTPCryptoSuites.NONE && (!audioMasterKey || !audioMasterSalt)) {
- throw new Error('Audio SRTP master key or salt is missing')
- }
-
- return {
- sessionIdentifier,
- addressVersion,
- controllerAddress,
- targetVideoPort,
- targetAudioPort,
- videoCryptoSuite,
- videoMasterKey,
- videoMasterSalt,
- audioCryptoSuite,
- audioMasterKey,
- audioMasterSalt,
- }
- }
-
private generateSetupEndpointResponse(
connection: HAPConnection,
identifier: StreamSessionIdentifier,
@@ -1402,38 +1361,37 @@ export class RTPStreamManagement {
}
this.ipVersion = addressVersion // we need to save this in order to calculate some default mtu values later
- const accessoryAddress = tlv.encode(
- AddressTypes.ADDRESS_VERSION, addressVersion === 'ipv4'
- ? IPAddressVersion.IPV4
- : IPAddressVersion.IPV6,
- AddressTypes.ADDRESS, address,
- AddressTypes.VIDEO_RTP_PORT, tlv.writeUInt16(videoPort),
- AddressTypes.AUDIO_RTP_PORT, tlv.writeUInt16(audioPort),
- )
-
- const videoSRTPParameters = tlv.encode(
- SRTPParametersTypes.SRTP_CRYPTO_SUITE, videoCryptoSuite,
- SRTPParametersTypes.MASTER_KEY, videoSRTPKey,
- SRTPParametersTypes.MASTER_SALT, videoSRTPSalt,
- )
-
- const audioSRTPParameters = tlv.encode(
- SRTPParametersTypes.SRTP_CRYPTO_SUITE, audioCryptoSuite,
- SRTPParametersTypes.MASTER_KEY, audioSRTPKey,
- SRTPParametersTypes.MASTER_SALT, audioSRTPSalt,
- )
+ // A prepare that settles while streaming is disabled holds no answer: its writer's read answers the Error TLV as every read while disabled does, and no
+ // answer carrying the accessory's keys outlives the release the disable ran. The force-stop it queues ends the session, whose slot would otherwise stay in
+ // use until its connection closes, and runs a microtask later so the delegate's prepare callback returns before its STOP arrives.
+ if (this.streamingIsDisabled()) {
+ callback()
+ queueMicrotask(() => this.forceStop())
+ return
+ }
- this.busySetupEndpointsResponses.delete(connection) // it reads the response of its session from now on
- this.setupEndpointsResponse = tlv.encode(
- SetupEndpointsResponseTypes.SESSION_ID, uuid.write(identifier),
- SetupEndpointsResponseTypes.STATUS, SetupEndpointsStatus.SUCCESS,
- SetupEndpointsResponseTypes.ACCESSORY_ADDRESS, accessoryAddress,
- SetupEndpointsResponseTypes.VIDEO_SRTP_PARAMETERS, videoSRTPParameters,
- SetupEndpointsResponseTypes.AUDIO_SRTP_PARAMETERS, audioSRTPParameters,
- SetupEndpointsResponseTypes.VIDEO_SSRC, tlv.writeUInt32(videoSSRC),
- SetupEndpointsResponseTypes.AUDIO_SSRC, tlv.writeUInt32(audioSSRC),
- ).toString('base64')
- callback()
+ callback(undefined, encodeSetupEndpointsResponse({
+ status: SetupEndpointsStatus.SUCCESS,
+ sessionIdentifier: identifier,
+ accessoryAddress: {
+ addressVersion,
+ address,
+ videoRTPPort: videoPort,
+ audioRTPPort: audioPort,
+ },
+ videoSRTPParameters: {
+ cryptoSuite: videoCryptoSuite,
+ masterKey: videoSRTPKey,
+ masterSalt: videoSRTPSalt,
+ },
+ audioSRTPParameters: {
+ cryptoSuite: audioCryptoSuite,
+ masterKey: audioSRTPKey,
+ masterSalt: audioSRTPSalt,
+ },
+ videoSSRC,
+ audioSSRC,
+ }))
}
private _updateStreamStatus(status: StreamingStatus): void {
@@ -1444,14 +1402,6 @@ export class RTPStreamManagement {
).toString('base64'))
}
- private static _supportedRTPConfiguration(supportedCryptoSuites: SRTPCryptoSuites[]): string {
- if (supportedCryptoSuites.length === 1 && supportedCryptoSuites[0] === SRTPCryptoSuites.NONE) {
- debug('Client claims it doesn\'t support SRTP. The stream may stop working with future iOS releases.')
- }
-
- return tlv.encode(SupportedRTPConfigurationTypes.SRTP_CRYPTO_SUITE, supportedCryptoSuites).toString('base64')
- }
-
private static _supportedVideoStreamConfiguration(videoOptions: VideoStreamingOptions): string {
if (!videoOptions.codec) {
throw new Error('Video codec cannot be undefined')
@@ -1620,12 +1570,9 @@ export class RTPStreamManagement {
).toString('base64')
}
- private resetSetupEndpointsResponse(): void {
- this.busySetupEndpointsResponses = new WeakMap() // every connection reads the default response again
- this.setupEndpointsResponse = tlv.encode(
- SetupEndpointsResponseTypes.STATUS, SetupEndpointsStatus.ERROR,
- ).toString('base64')
- this.service.updateCharacteristic(Characteristic.SetupEndpoints, this.setupEndpointsResponse)
+ // Releases the Setup Endpoints answer every connection holds, at each boundary that ends or bounds the answers a session made.
+ private releaseSetupEndpointsAnswers(): void {
+ this.service.getCharacteristic(Characteristic.SetupEndpoints).releaseTransientAnswers()
}
private resetSelectedStreamConfiguration(): void {
diff --git a/src/lib/camera/RecordingManagement.spec.ts b/src/lib/camera/RecordingManagement.spec.ts
index e430c776c..5ef860526 100644
--- a/src/lib/camera/RecordingManagement.spec.ts
+++ b/src/lib/camera/RecordingManagement.spec.ts
@@ -1,28 +1,183 @@
-import type {
- CameraRecordingConfiguration,
- RecordingPacket,
-} from './RecordingManagement.js'
+import type { Mock, MockInstance } from 'vitest'
+
+import type { CameraControllerServiceMap, CameraRecordingDelegate, CameraStreamingDelegate } from '../controller/index.js'
+import type { AccessoryInformation } from '../definitions/index.js'
+import type { BufferRecorder, RecordingAdmission } from './recording/BufferRecorder.js'
+import type { CameraRecordingConfiguration, RecordingManagementState, RecordingPacket } from './RecordingManagement.js'
+import type { CameraSnapshotRequest } from './StreamingOptions.js'
import { Buffer } from 'node:buffer'
-import { EventEmitter } from 'node:events'
+import crypto from 'node:crypto'
import process from 'node:process'
+import { ReadableStream } from 'node:stream/web'
+import { format } from 'node:util'
-import { describe, expect, it, vi } from 'vitest'
+import createDebug from 'debug'
+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'
+import {
+ bufferCamera,
+ createCameraControllerOptions,
+ FIRST_VIDEO_SENSOR,
+ frames,
+ handPublishedContext,
+ MockDelegate,
+ mockRecordingOptions,
+ mockStreamingOptions,
+ NUMBERED_ACCESSORY_UUID,
+} from '../../test-utils/cameraFixtures.js'
+import { DataStreamClient } from '../../test-utils/dataStreamClient.js'
+import { captureDebug } from '../../test-utils/engineDebug.js'
+import { skeletonPackets, TIER_STREAM_PARAMETER_SETS, tierStreamInitialization } from '../../test-utils/mp4Fixtures.js'
+import { problemsOf, REPORTER_ACCESSORY_UUID } from '../../test-utils/reporterFixtures.js'
+import { deferred, settle } from '../../test-utils/settle.js'
import { Characteristic } from '../Characteristic.js'
-import { MockDelegate, mockRecordingOptions } from '../controller/CameraController.spec.js'
+import { CameraController, ResourceRequestReason } from '../controller/index.js'
+import {
+ DataStreamManagement,
+ HDSConnectionError,
+ HDSConnectionErrorType,
+ HDSProtocolError,
+ HDSProtocolSpecificErrorReason,
+ HDSStatus,
+ Protocols,
+ Topics,
+} from '../datastream/index.js'
import { HAPStatus } from '../HAPServer.js'
+import { Service, ServiceEventTypes } from '../Service.js'
import { HapStatusError } from '../util/hapStatusError.js'
+import { onCameraProblem } from './diagnostics/problems.js'
+import { OperatingModePolicy } from './OperatingModePolicy.js'
+import { ServedRecording, ServedRecordings } from './recording/ServedRecording.js'
import {
AudioRecordingCodecType,
AudioRecordingSamplerate,
EventTriggerOption,
MediaContainerType,
+ PacketDataType,
RecordingManagement,
} from './RecordingManagement.js'
import { AudioBitrate, H264Level, H264Profile, VideoCodecType } from './RTPStreamManagement.js'
+const SELECTED_CONFIGURATION = 'AR0BBKAPAAACCAEAAAAAAAAAAwsBAQACBgEEoA8AAAIkAQEAAhIBAQECAQIDBNAHAAAEBKAPAAADCwECsAQCAkAGAwEYAxQBAQACDwEBAQIBAAMBAwQEQAAAAA=='
+const OPEN_RECORDING = {
+ reason: 'motion',
+ streamId: 1,
+ target: 'controller',
+ type: 'ipcamera.recording',
+}
+const MAX_CHUNK = 0x40000
+
+type RecordingRequest = CameraRecordingDelegate['handleRecordingStreamRequest']
+
+// A delegate whose recording is the row's own, every call it hears a spy.
+type RecordingDelegate = MockDelegate & {
+ acknowledgeStream: Mock>
+ closeRecordingStream: Mock
+ handleRecordingStreamRequest: Mock
+}
+
+function recordingDelegate(record: RecordingRequest): RecordingDelegate {
+ return Object.assign(new MockDelegate(), {
+ acknowledgeStream: vi.fn>(),
+ closeRecordingStream: vi.fn(),
+ handleRecordingStreamRequest: vi.fn(record),
+ })
+}
+
+// A standalone camera that records: a configuration selected and recording switched on, each through its characteristic, its management made with the
+// capabilities a row hands, and none otherwise.
+function recordingCamera(delegate: CameraRecordingDelegate, capabilities?: ConstructorParameters[5]): RecordingManagement {
+ const management = new RecordingManagement(mockRecordingOptions, delegate, new Set([EventTriggerOption.MOTION]), undefined, undefined, capabilities)
+
+ management.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION)
+ management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE)
+
+ return management
+}
+
+function packet(length: number, isLast = false): RecordingPacket {
+ return {
+ data: crypto.randomBytes(length),
+ isLast,
+ }
+}
+
+function aborted(signal: AbortSignal): Promise {
+ return new Promise(resolve => signal.addEventListener('abort', () => resolve(), { once: true }))
+}
+
+function open(client: DataStreamClient, streamId = 1, overrides: Record = {}): number {
+ return client.request(Protocols.DATA_SEND, Topics.OPEN, {
+ ...OPEN_RECORDING,
+ streamId,
+ ...overrides,
+ })
+}
+
+function acknowledge(client: DataStreamClient, streamId = 1): void {
+ client.event(Protocols.DATA_SEND, Topics.ACK, { endOfStream: true, streamId })
+}
+
+function hubClose(client: DataStreamClient, streamId: number, reason: HDSProtocolSpecificErrorReason): void {
+ client.event(Protocols.DATA_SEND, Topics.CLOSE, { reason, streamId })
+}
+
+// The status an open was answered with, and the reason a refusal carries.
+function answer(client: DataStreamClient, id: number): { reason?: number, status?: number } {
+ const written = client.answerTo(id)
+
+ return { reason: written?.message.status, status: written?.header.status }
+}
+
+function dataEvents(client: DataStreamClient): Record[] {
+ return client.events(Protocols.DATA_SEND, Topics.DATA)
+}
+
+function closeEvents(client: DataStreamClient): Record[] {
+ return client.events(Protocols.DATA_SEND, Topics.CLOSE)
+}
+
+// Each data event's chunk as the hub reads it: its metadata and whether it ends the stream.
+function chunks(client: DataStreamClient): Record[] {
+ return dataEvents(client).map(({ endOfStream, packets: [{ metadata }], streamId }) => ({ endOfStream, metadata, streamId }))
+}
+
+function signalOf(delegate: RecordingDelegate, call = 0): AbortSignal {
+ return delegate.handleRecordingStreamRequest.mock.calls[call][1]!
+}
+
+function recordingStreamOf(management: RecordingManagement): unknown {
+ // @ts-expect-error: private access
+ return management.recordingStream
+}
+
describe('RecordingManagement', () => {
+ it('leaves each sensor\'s status active at the policy\'s camera state when it restores a legacy layout without one', () => {
+ const policy = new OperatingModePolicy()
+ const management = new RecordingManagement(mockRecordingOptions, new MockDelegate(), new Set([EventTriggerOption.MOTION]), undefined, policy)
+ const sensor = new Service.MotionSensor('', '')
+ const legacyLayout = {
+ configurationHash: { algorithm: 'sha256' as const, hash: '' },
+ recordingAudioActive: false,
+ eventSnapshotsActive: true,
+ periodicSnapshotsActive: true,
+ }
+ sensor.setCharacteristic(Characteristic.StatusActive, false)
+ management.sensorServices.push(sensor)
+
+ management.deserialize(legacyLayout)
+
+ expect(sensor.getCharacteristic(Characteristic.StatusActive).value).toBe(true)
+
+ management.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF)
+ sensor.setCharacteristic(Characteristic.StatusActive, true)
+ management.deserialize(legacyLayout)
+
+ expect(policy.homeKitCameraActive).toBe(false)
+ expect(sensor.getCharacteristic(Characteristic.StatusActive).value).toBe(false)
+ })
+
it('handleSelectedCameraRecordingConfiguration', () => {
const base64Input = 'AR0BBKAPAAACCAEAAAAAAAAAAwsBAQACBgEEoA8AAAIkAQEAAhIBAQECAQIDBNAHAAAEBKAPAAADCwECsAQCAkAGAwEYAxQBAQACDwEBAQIBAAMBAwQEQAAAAA=='
@@ -104,235 +259,159 @@ describe('RecordingManagement', () => {
})
describe('dataSend open', () => {
- function managementReadyToRecord(delegate = new MockDelegate()): RecordingManagement {
- const management = new RecordingManagement(
- mockRecordingOptions,
- delegate,
- new Set([EventTriggerOption.MOTION, EventTriggerOption.DOORBELL]),
- )
- const internals = management as any
- internals.recordingActive = true
- internals.selectedConfiguration = {}
- internals.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value = true
- return management
- }
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
- function fakeConnection(sendResponse: () => void) {
- return Object.assign(new EventEmitter(), {
- remoteAddress: '127.0.0.1',
- sendResponse: vi.fn(sendResponse),
- sendEvent: vi.fn(),
- addProtocolHandler: vi.fn(() => true),
- removeProtocolHandler: vi.fn(),
- isConsideredClosed: () => false,
- })
+ // A recording that yields one packet and then holds until the row releases it.
+ function heldRecording(): { delegate: RecordingDelegate, release: () => void } {
+ const held = deferred()
+
+ return {
+ delegate: recordingDelegate(async function* () {
+ yield packet(10)
+ await held.promise
+ }),
+ release: () => held.resolve(),
+ }
}
it('should free the stream instead of rejecting when the open response can not be sent', async () => {
const unhandled: unknown[] = []
const onUnhandled = (reason: unknown) => unhandled.push(reason)
process.on('unhandledRejection', onUnhandled)
- const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
try {
- const management = managementReadyToRecord()
- const connection = fakeConnection(() => {
+ const management = recordingCamera(recordingDelegate(async function* () {
+ yield packet(10, true)
+ }))
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const sendResponse = vi.spyOn(client.connection, 'sendResponse').mockImplementationOnce(() => {
throw new Error('Cannot send message on closing/closed socket!')
})
- ;(management as any).handleDataSendOpen(connection, 1, {
- streamId: 5,
- type: 'ipcamera.recording',
- target: 'controller',
- reason: 'record',
- })
- await new Promise(resolve => setTimeout(resolve, 10))
+ open(client, 5)
+ await settle()
- expect(connection.sendResponse).toHaveBeenCalledTimes(1)
+ expect(sendResponse).toHaveBeenCalledTimes(1)
expect(unhandled).toEqual([])
- expect((management as any).recordingStream).toBeUndefined() // the next open is not answered with "busy"
+ expect(recordingStreamOf(management)).toBeUndefined() // the next open is not answered with "busy"
} finally {
process.off('unhandledRejection', onUnhandled)
- error.mockRestore()
}
})
it('should signal the end of the stream when the last packet has no data', async () => {
- class EmptyLastPacketDelegate extends MockDelegate {
- override async* handleRecordingStreamRequest(): AsyncGenerator {
- yield {
- data: Buffer.alloc(100, 1),
- isLast: false,
- }
- yield {
- data: Buffer.alloc(0),
- isLast: false,
- } // skipped, without using up a sequence number
- yield {
- data: Buffer.alloc(50, 2),
- isLast: false,
- }
- yield {
- data: Buffer.alloc(0),
- isLast: true,
- }
+ const management = recordingCamera(recordingDelegate(async function* () {
+ yield {
+ data: Buffer.alloc(100, 1),
+ isLast: false,
}
- }
- const management = managementReadyToRecord(new EmptyLastPacketDelegate())
- const connection = fakeConnection(() => undefined)
+ yield {
+ data: Buffer.alloc(0),
+ isLast: false,
+ } // skipped, without using up a sequence number
+ yield {
+ data: Buffer.alloc(50, 2),
+ isLast: false,
+ }
+ yield {
+ data: Buffer.alloc(0),
+ isLast: true,
+ }
+ }))
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
- ;(management as any).handleDataSendOpen(connection, 1, {
- streamId: 5,
- type: 'ipcamera.recording',
- target: 'controller',
- reason: 'record',
- })
- await new Promise(resolve => setTimeout(resolve, 10))
+ open(client, 5)
+ await settle()
- const events = connection.sendEvent.mock.calls.map(call => ({
- length: call[2].packets[0].data.length,
- sequenceNumber: call[2].packets[0].metadata.dataSequenceNumber,
- endOfStream: call[2].endOfStream,
- }))
- expect(events).toEqual([
+ expect(dataEvents(client).map(({ endOfStream, packets: [{ data, metadata }] }) => ({
+ length: data.length,
+ sequenceNumber: metadata.dataSequenceNumber,
+ endOfStream,
+ }))).toEqual([
{ length: 100, sequenceNumber: 1, endOfStream: false },
{ length: 50, sequenceNumber: 2, endOfStream: false },
{ length: 0, sequenceNumber: 3, endOfStream: true },
])
- ;(management as any).recordingStream?.close(0)
+ acknowledge(client, 5)
})
it('should ignore an acknowledgment for another stream', async () => {
- class WaitingDelegate extends MockDelegate {
- acknowledgeStream = vi.fn()
-
- override async* handleRecordingStreamRequest(): AsyncGenerator {
- yield {
- data: Buffer.alloc(10, 1),
- isLast: false,
- }
- await new Promise(resolve => setTimeout(resolve, 1000)) // still recording
- }
- }
- const delegate = new WaitingDelegate()
- const management = managementReadyToRecord(delegate)
- const connection = fakeConnection(() => undefined)
+ const { delegate, release } = heldRecording()
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
- ;(management as any).handleDataSendOpen(connection, 1, {
- streamId: 5,
- type: 'ipcamera.recording',
- target: 'controller',
- reason: 'record',
- })
- await new Promise(resolve => setTimeout(resolve, 10))
- const stream = (management as any).recordingStream
+ open(client, 5)
+ await settle()
+ const stream = recordingStreamOf(management)
- stream.handleDataSendAck({ streamId: 999, endOfStream: true })
+ acknowledge(client, 999)
expect(delegate.acknowledgeStream).not.toHaveBeenCalled()
- expect((management as any).recordingStream).toBe(stream)
+ expect(recordingStreamOf(management)).toBe(stream)
- stream.handleDataSendAck({ streamId: 5, endOfStream: true })
+ acknowledge(client, 5)
expect(delegate.acknowledgeStream).toHaveBeenCalledExactlyOnceWith(5)
- expect((management as any).recordingStream).toBeUndefined()
+ expect(recordingStreamOf(management)).toBeUndefined()
+ release()
})
it('should not keep the process alive while it waits for the home hub to close a finished stream', async () => {
- class FinishedDelegate extends MockDelegate {
- override async* handleRecordingStreamRequest(): AsyncGenerator {
- yield {
- data: Buffer.alloc(10, 1),
- isLast: true,
- }
- }
- }
- const management = managementReadyToRecord(new FinishedDelegate())
- const connection = fakeConnection(() => undefined)
+ const management = recordingCamera(recordingDelegate(async function* () {
+ yield packet(10, true)
+ }))
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const timers = vi.spyOn(globalThis, 'setTimeout')
- ;(management as any).handleDataSendOpen(connection, 1, {
- streamId: 5,
- type: 'ipcamera.recording',
- target: 'controller',
- reason: 'record',
- })
- await new Promise(resolve => setTimeout(resolve, 10))
- const stream = (management as any).recordingStream
+ open(client, 5)
+ await settle()
- expect(stream.closingTimeout.hasRef()).toBe(false)
- stream.close(0)
+ // The close wait is the 12 second timer the finished stream armed, read through the handle setTimeout answered.
+ const closeWait = timers.mock.calls.findLastIndex(([, delay]) => delay === 12000)
+
+ expect(closeWait).toBeGreaterThanOrEqual(0)
+ expect((timers.mock.results[closeWait].value as ReturnType).hasRef()).toBe(false)
+ acknowledge(client, 5)
})
it('should not keep the process alive while it waits for the generator of a closed stream', async () => {
- let finish = (): void => undefined
- class WaitingDelegate extends MockDelegate {
- override async* handleRecordingStreamRequest(): AsyncGenerator {
- yield {
- data: Buffer.alloc(10, 1),
- isLast: false,
- }
- await new Promise(resolve => finish = resolve) // still recording
- }
- }
- const management = managementReadyToRecord(new WaitingDelegate())
- const connection = fakeConnection(() => undefined)
+ const { delegate, release } = heldRecording()
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
- ;(management as any).handleDataSendOpen(connection, 1, {
- streamId: 5,
- type: 'ipcamera.recording',
- target: 'controller',
- reason: 'record',
- })
- await new Promise(resolve => setTimeout(resolve, 10))
- const stream = (management as any).recordingStream
+ open(client, 5)
+ await settle()
+ const stream = recordingStreamOf(management) as { generatorTimeout?: ReturnType }
- stream.close(0)
- expect(stream.generatorTimeout.hasRef()).toBe(false)
- finish()
- await new Promise(resolve => setTimeout(resolve, 10))
+ hubClose(client, 5, HDSProtocolSpecificErrorReason.NORMAL)
+ expect(stream.generatorTimeout?.hasRef()).toBe(false)
+ release()
+ await settle()
})
it('should hand a close reason which is not a number to the delegate as a missing reason', async () => {
- class WaitingDelegate extends MockDelegate {
- override closeRecordingStream = vi.fn()
-
- override async* handleRecordingStreamRequest(): AsyncGenerator {
- yield {
- data: Buffer.alloc(10, 1),
- isLast: false,
- }
- await new Promise(resolve => setTimeout(resolve, 1000)) // still recording
- }
- }
- const delegate = new WaitingDelegate()
- const management = managementReadyToRecord(delegate)
- const connection = fakeConnection(() => undefined)
+ const { delegate, release } = heldRecording()
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
- ;(management as any).handleDataSendOpen(connection, 1, {
- streamId: 5,
- type: 'ipcamera.recording',
- target: 'controller',
- reason: 'record',
- })
- await new Promise(resolve => setTimeout(resolve, 10))
-
- ;(management as any).recordingStream.handleDataSendClose({ streamId: 5, reason: 'because' })
+ open(client, 5)
+ await settle()
+ client.event(Protocols.DATA_SEND, Topics.CLOSE, { reason: 'because', streamId: 5 })
expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(5, undefined)
- expect((management as any).recordingStream).toBeUndefined()
+ expect(recordingStreamOf(management)).toBeUndefined()
+ release()
})
- it('should reject an open without a numeric stream id', () => {
- const management = managementReadyToRecord()
- const connection = fakeConnection(() => undefined)
-
- ;(management as any).handleDataSendOpen(connection, 1, {
- streamId: 'five',
- type: 'ipcamera.recording',
- target: 'controller',
- })
+ it('should reject an open without a numeric stream id', async () => {
+ const management = recordingCamera(recordingDelegate(async function* () {
+ yield packet(10, true)
+ }))
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const id = open(client, 1, { streamId: 'five' })
- expect(connection.sendResponse).toHaveBeenCalledExactlyOnceWith('dataSend', 'open', 1, 6, {
- status: 5,
- })
- expect((management as any).recordingStream).toBeUndefined()
+ expect(answer(client, id)).toEqual({ reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR })
+ expect(client.written.filter(({ header }) => header.response !== undefined && header.id === id)).toHaveLength(1)
+ expect(recordingStreamOf(management)).toBeUndefined()
})
})
@@ -400,4 +479,2154 @@ describe('RecordingManagement', () => {
+ 'MBGAAAAwsBArAEAgJABgMBDwAAAwsBAjgEAgKgBQMBDwAAAwsBAsADAgIABQMBDwAAAwsBAgADAgIABAMBDw==')
expect(supportedAudio).toEqual('AQ4BAQACCQEBAQIBAAMBAw==')
})
+
+ describe('a recording management without the legacy recording options', () => {
+ const CONFIGURATION_CHARACTERISTICS = [
+ Characteristic.SupportedCameraRecordingConfiguration,
+ Characteristic.SupportedVideoRecordingConfiguration,
+ Characteristic.SupportedAudioRecordingConfiguration,
+ Characteristic.SelectedCameraRecordingConfiguration,
+ ]
+
+ // The cameras a row builds, removed after it. No stream or policy outlives its row.
+ const cameras: CameraController[] = []
+
+ afterEach(() => {
+ for (const camera of cameras.splice(0)) {
+ camera.handleControllerRemoved()
+ }
+
+ vi.restoreAllMocks()
+ })
+
+ function slim(delegate: CameraRecordingDelegate = new MockDelegate(), policy?: OperatingModePolicy): RecordingManagement {
+ return new RecordingManagement(undefined, delegate, new Set([EventTriggerOption.MOTION]), undefined, policy)
+ }
+
+ function configurationCharacteristics(service: Service): boolean[] {
+ return CONFIGURATION_CHARACTERISTICS.map(type => service.testCharacteristic(type))
+ }
+
+ it('builds its recording service with Active and Recording Audio Active and none of the configuration characteristics', () => {
+ const management = slim()
+
+ expect(management.options).toBeUndefined()
+ expect(management.recordingManagementService.characteristics.map(({ UUID }) => UUID)).toEqual([
+ Characteristic.Active.UUID,
+ Characteristic.RecordingAudioActive.UUID,
+ ])
+ expect(configurationCharacteristics(management.recordingManagementService)).toEqual([false, false, false, false])
+ })
+
+ it('removes the configuration characteristics from an adopted recording service that carries them, each raising the service\'s configuration change', async () => {
+ const legacy = new RecordingManagement(mockRecordingOptions, new MockDelegate(), new Set([EventTriggerOption.MOTION]))
+ const { recordingManagementService, operatingModeService } = legacy
+ // Each configuration change is read with the configuration characteristics the service still holds at it, and each removal's own change shows.
+ const heldAtChange: number[] = []
+
+ recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE)
+ await settle()
+ legacy.destroy()
+ recordingManagementService.on(ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE, () => {
+ heldAtChange.push(configurationCharacteristics(recordingManagementService).filter(Boolean).length)
+ })
+
+ const management = new RecordingManagement(undefined, new MockDelegate(), new Set([EventTriggerOption.MOTION]), {
+ dataStreamManagement: new DataStreamManagement(legacy.dataStreamManagement.getService()),
+ operatingMode: operatingModeService,
+ recordingManagement: recordingManagementService,
+ })
+
+ expect(configurationCharacteristics(management.recordingManagementService)).toEqual([false, false, false, false])
+ expect(heldAtChange).toEqual(expect.arrayContaining([3, 2, 1, 0]))
+ expect(management.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE)
+ })
+
+ it('serves a recording with none selected, the open\'s other checks standing', async () => {
+ const delegate = recordingDelegate(async function* () {
+ yield packet(100, true)
+ })
+ const management = slim(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const refused = open(client)
+
+ await settle()
+
+ expect(answer(client, refused)).toEqual({ reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR })
+
+ management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE)
+ await settle()
+
+ const served = open(client)
+
+ await settle()
+
+ expect(answer(client, served)).toEqual({ reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS })
+ expect(delegate.handleRecordingStreamRequest).toHaveBeenCalledExactlyOnceWith(1, expect.any(AbortSignal))
+ expect(chunks(client).map(({ endOfStream }) => endOfStream)).toEqual([true])
+
+ acknowledge(client)
+
+ expect(delegate.acknowledgeStream).toHaveBeenCalledExactlyOnceWith(1)
+ })
+
+ it('answers an open its capabilities\' admit refuses with the refusal\'s reason, telling the delegate nothing and holding no stream, and serves one it '
+ + 'admits through the admission\'s serving function, while a management whose capabilities hold no admit asks its delegate', async () => {
+ const { reporter } = problemsOf()
+ const capabilities = {
+ feed: new ServedRecordings({ reporter, sensorUUID: FIRST_VIDEO_SENSOR.uuid }),
+ reporter,
+ }
+ const serve = vi.fn(async function* (signal?: AbortSignal): AsyncGenerator {
+ await aborted(signal!)
+ })
+ const answers: RecordingAdmission[] = [
+ { admitted: false, reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED },
+ { admitted: false, reason: HDSProtocolSpecificErrorReason.BUSY },
+ { admitted: true, serve },
+ ]
+ const admit = vi.fn<(streamId: number) => RecordingAdmission>(() => answers.shift()!)
+ const delegate = recordingDelegate(async function* () {
+ yield packet(100, true)
+ })
+ const updateRecordingActive = vi.spyOn(delegate, 'updateRecordingActive')
+ const management = new RecordingManagement(undefined, delegate, new Set([EventTriggerOption.MOTION]), undefined, undefined, { ...capabilities, admit })
+
+ // Active is assigned directly: the policy reads recording allowed and the delegate has heard nothing of it before an open the management lets
+ // through.
+ management.recordingManagementService.getCharacteristic(Characteristic.Active).value = Characteristic.Active.ACTIVE
+
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const refusals = [
+ open(client, 1),
+ open(client, 2),
+ ]
+
+ await settle()
+
+ expect(refusals.map(id => answer(client, id))).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR },
+ { reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR },
+ ])
+ expect(updateRecordingActive).not.toHaveBeenCalled()
+ expect(recordingStreamOf(management)).toBeUndefined()
+
+ const admitted = open(client, 3)
+
+ await settle()
+
+ expect(answer(client, admitted)).toEqual({ reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS })
+ expect(admit.mock.calls).toEqual([
+ [1],
+ [2],
+ [3],
+ ])
+ expect(updateRecordingActive.mock.calls).toEqual([
+ [true],
+ ])
+ expect(serve).toHaveBeenCalledExactlyOnceWith(expect.any(AbortSignal))
+
+ const [signal] = serve.mock.calls[0]
+
+ expect(signal!.aborted).toBe(false)
+
+ hubClose(client, 3, HDSProtocolSpecificErrorReason.NORMAL)
+ await settle()
+
+ expect(signal!.aborted).toBe(true)
+ expect(delegate.handleRecordingStreamRequest).not.toHaveBeenCalled()
+
+ const asked = recordingDelegate(async function* () {
+ yield packet(100, true)
+ })
+ const plain = new RecordingManagement(undefined, asked, new Set([EventTriggerOption.MOTION]), undefined, undefined, capabilities)
+
+ plain.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE)
+
+ const plainClient = await DataStreamClient.connect(plain.dataStreamManagement)
+ const served = open(plainClient)
+
+ await settle()
+
+ expect(answer(plainClient, served)).toEqual({ reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS })
+ expect(asked.handleRecordingStreamRequest).toHaveBeenCalledExactlyOnceWith(1, expect.any(AbortSignal))
+
+ acknowledge(plainClient)
+ })
+
+ it('saves no recording state', () => {
+ expect(slim().serialize()).toBeUndefined()
+ })
+
+ it('reports recording Active to its delegate and never a configuration, its factory reset\'s report included', async () => {
+ const delegate = new MockDelegate()
+ const updateRecordingActive = vi.spyOn(delegate, 'updateRecordingActive')
+ const updateRecordingConfiguration = vi.spyOn(delegate, 'updateRecordingConfiguration')
+ const management = slim(delegate)
+
+ management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE)
+ await settle()
+ management.handleFactoryReset()
+
+ expect(updateRecordingActive.mock.calls).toEqual([
+ [true],
+ [false],
+ ])
+ expect(updateRecordingConfiguration).not.toHaveBeenCalled()
+ })
+
+ it('restores the operating mode, the sensors\' Status Active and recording Active, reading neither a stored configuration hash nor a selection', () => {
+ const delegate = new MockDelegate()
+ const updateRecordingActive = vi.spyOn(delegate, 'updateRecordingActive')
+ const updateRecordingConfiguration = vi.spyOn(delegate, 'updateRecordingConfiguration')
+ const policy = new OperatingModePolicy()
+ const management = slim(delegate, policy)
+ const sensor = new Service.MotionSensor('', '')
+
+ management.sensorServices.push(sensor)
+ management.deserialize({
+ configurationHash: { algorithm: 'sha256', hash: 'a hash of the options the camera gave before' },
+ selectedConfiguration: SELECTED_CONFIGURATION,
+ }, {
+ eventSnapshotsActive: false,
+ homeKitCameraActive: false,
+ periodicSnapshotsActive: true,
+ recordingActive: true,
+ recordingAudioActive: true,
+ })
+
+ expect(management.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE)
+ expect(management.recordingManagementService.getCharacteristic(Characteristic.RecordingAudioActive).value).toBe(Characteristic.RecordingAudioActive.ENABLE)
+ expect(management.operatingModeService.getCharacteristic(Characteristic.EventSnapshotsActive).value).toBe(Characteristic.EventSnapshotsActive.DISABLE)
+ expect(policy.homeKitCameraActive).toBe(false)
+ expect(sensor.getCharacteristic(Characteristic.StatusActive).value).toBe(false)
+ expect(updateRecordingActive.mock.calls).toEqual([
+ [true],
+ ])
+ expect(updateRecordingConfiguration).not.toHaveBeenCalled()
+ expect(configurationCharacteristics(management.recordingManagementService)).toEqual([false, false, false, false])
+
+ // A state with no configuration hash, which no camera with the options writes, restores as well.
+ expect(() => management.deserialize({} as RecordingManagementState)).not.toThrow()
+ })
+ })
+
+ describe('a recording over a data stream connection', () => {
+ beforeEach(() => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ it('answers the open, then sends each packet in chunks of 256 KiB labeled by position, numbered and sized as the hub reads them', async () => {
+ const packets = [
+ packet(MAX_CHUNK + 1),
+ packet(MAX_CHUNK),
+ packet(100, true),
+ ]
+ const delegate = recordingDelegate(async function* () {
+ yield* packets
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const id = open(client)
+
+ await settle()
+
+ expect(client.written[1]).toEqual({
+ header: {
+ id,
+ protocol: Protocols.DATA_SEND,
+ response: Topics.OPEN,
+ status: HDSStatus.SUCCESS,
+ },
+ message: { status: HDSStatus.SUCCESS },
+ })
+ expect(chunks(client)).toEqual([
+ {
+ metadata: {
+ dataChunkSequenceNumber: 1,
+ dataSequenceNumber: 1,
+ dataTotalSize: MAX_CHUNK + 1,
+ dataType: PacketDataType.MEDIA_INITIALIZATION,
+ isLastDataChunk: false,
+ },
+ streamId: 1,
+ },
+ {
+ endOfStream: false,
+ metadata: {
+ dataChunkSequenceNumber: 2,
+ dataSequenceNumber: 1,
+ dataType: PacketDataType.MEDIA_FRAGMENT,
+ isLastDataChunk: true,
+ },
+ streamId: 1,
+ },
+ {
+ endOfStream: false,
+ metadata: {
+ dataChunkSequenceNumber: 1,
+ dataSequenceNumber: 2,
+ dataTotalSize: MAX_CHUNK,
+ dataType: PacketDataType.MEDIA_FRAGMENT,
+ isLastDataChunk: true,
+ },
+ streamId: 1,
+ },
+ {
+ endOfStream: true,
+ metadata: {
+ dataChunkSequenceNumber: 1,
+ dataSequenceNumber: 3,
+ dataTotalSize: 100,
+ dataType: PacketDataType.MEDIA_FRAGMENT,
+ isLastDataChunk: true,
+ },
+ streamId: 1,
+ },
+ ])
+
+ const sent = dataEvents(client).map(({ packets: [{ data }] }) => data)
+
+ expect(Buffer.concat(sent.slice(0, 2))).toEqual(packets[0].data)
+ expect(sent[2]).toEqual(packets[1].data)
+ expect(sent[3]).toEqual(packets[2].data)
+ })
+
+ it('sends each packet of a muxer\'s recording byte for byte on a camera without the capabilities block', async () => {
+ const packets = skeletonPackets()
+ const delegate = recordingDelegate(async function* () {
+ yield { data: packets[0], isLast: false }
+ yield { data: packets[1], isLast: false }
+ yield { data: packets[2], isLast: true }
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ expect(dataEvents(client).map(({ packets: [{ data }] }) => data)).toEqual(packets)
+ })
+
+ it('writes its own producer reference time box before each fragment, with a capability camera\'s box writing turned on', async () => {
+ const [muxed, first, muxedSecond] = skeletonPackets()
+ // The skeleton's packets without the muxer's own producer reference time boxes, as the library's recorder writes none.
+ const initialization = muxed.subarray(0, muxed.length - 32)
+ const second = muxedSecond.subarray(32)
+ const delegate = recordingDelegate(async function* () {
+ yield { data: initialization, isLast: false }
+ yield { data: first, isLast: false }
+ yield { data: second, isLast: true }
+ })
+ const management = recordingCamera(delegate)
+
+ // @ts-expect-error: private access
+ management.producerReferenceTime = true
+ vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-11-12T00:00:00.000Z'))
+
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ const sent = dataEvents(client).map(({ packets: [{ data }] }) => data as Buffer)
+
+ expect(sent[0]).toEqual(initialization)
+ expect(sent[1].subarray(0, 32).toString('hex')).toBe('00000020707266740100001800000001ee9f8000000000000000000000000000')
+ expect(sent[1].subarray(32)).toEqual(first)
+ expect(sent[2].subarray(0, 32).toString('hex')).toBe('00000020707266740100001800000001ee9f800410666666000000000000f3d8')
+ expect(sent[2].subarray(32)).toEqual(second)
+ expect(chunks(client).map(({ metadata }) => metadata)).toEqual(sent.map((data, index) => ({
+ dataChunkSequenceNumber: 1,
+ dataSequenceNumber: index + 1,
+ dataTotalSize: data.length,
+ dataType: index === 0
+ ? PacketDataType.MEDIA_INITIALIZATION
+ : PacketDataType.MEDIA_FRAGMENT,
+ isLastDataChunk: true,
+ })))
+ })
+
+ it('closes a recording as an unexpected failure at a fragment before any initialization segment, with a capability camera\'s box writing turned on', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const [, first] = skeletonPackets()
+ const delegate = recordingDelegate(async function* () {
+ yield { data: first, isLast: false }
+ })
+ const management = recordingCamera(delegate)
+
+ // @ts-expect-error: private access
+ management.producerReferenceTime = true
+
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ expect(dataEvents(client)).toEqual([])
+ expect(closeEvents(client)).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, streamId: 1 },
+ ])
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE)
+ expect(error.mock.calls).toEqual([
+ [
+ expect.stringContaining('[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: Error: '
+ + 'The recording yielded a media fragment before any initialization segment.'),
+ ],
+ ])
+ })
+
+ it('sends nothing for an empty packet, which takes no sequence number, ends the stream at once at an empty last packet, and closes it as cancelled once the '
+ + 'hub has left it open 12 seconds', async () => {
+ const delegate = recordingDelegate(async function* () {
+ yield packet(100)
+ yield packet(0)
+ yield packet(100)
+ yield packet(0, true)
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ expect(chunks(client).map(({ endOfStream, metadata }) => ({ endOfStream, sequence: (metadata as { dataSequenceNumber: number }).dataSequenceNumber })))
+ .toEqual([
+ { endOfStream: false, sequence: 1 },
+ { endOfStream: false, sequence: 2 },
+ { endOfStream: true, sequence: 3 },
+ ])
+
+ vi.advanceTimersByTime(12000)
+
+ expect(closeEvents(client)).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.CANCELLED, streamId: 1 },
+ ])
+ })
+
+ it('stamps and serves each packet with data on a stamping camera, an empty packet taking no sequence number and an empty last packet ending the stream '
+ + 'at once with no data', async () => {
+ const [muxed, first, muxedSecond] = skeletonPackets()
+ // The skeleton's packets without the muxer's own producer reference time boxes, as the library's recorder writes none.
+ const initialization = muxed.subarray(0, muxed.length - 32)
+ const second = muxedSecond.subarray(32)
+ const delegate = recordingDelegate(async function* () {
+ yield { data: initialization, isLast: false }
+ yield { data: first, isLast: false }
+ yield packet(0)
+ yield { data: second, isLast: false }
+ yield packet(0, true)
+ })
+ const { reporter } = problemsOf()
+ const management = recordingCamera(delegate, {
+ feed: new ServedRecordings({ reporter, sensorUUID: FIRST_VIDEO_SENSOR.uuid }),
+ reporter,
+ })
+ const served = vi.spyOn(ServedRecording.prototype, 'add')
+
+ // @ts-expect-error: private access
+ management.producerReferenceTime = true
+ vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-11-12T00:00:00.000Z'))
+
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ const sent = dataEvents(client).map(({ packets: [{ data }] }) => data as Buffer)
+
+ expect(chunks(client).map(({ endOfStream, metadata }) => ({ endOfStream, sequence: (metadata as { dataSequenceNumber: number }).dataSequenceNumber })))
+ .toEqual([
+ { endOfStream: false, sequence: 1 },
+ { endOfStream: false, sequence: 2 },
+ { endOfStream: false, sequence: 3 },
+ { endOfStream: true, sequence: 4 },
+ ])
+ expect(sent[1].subarray(0, 32).toString('hex')).toBe('00000020707266740100001800000001ee9f8000000000000000000000000000')
+ expect(sent[1].subarray(32)).toEqual(first)
+ expect(sent[2].subarray(0, 32).toString('hex')).toBe('00000020707266740100001800000001ee9f800410666666000000000000f3d8')
+ expect(sent[2].subarray(32)).toEqual(second)
+ expect(sent[3]).toHaveLength(0)
+ expect(served.mock.calls.map(([written]) => written.bytes)).toEqual(sent)
+ })
+
+ it('tells the delegate of the hub\'s acknowledgement alone, aborts nothing and frees the camera', async () => {
+ const delegate = recordingDelegate(async function* () {
+ yield packet(100, true)
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+ acknowledge(client)
+
+ expect(delegate.acknowledgeStream).toHaveBeenCalledExactlyOnceWith(1)
+ expect(delegate.closeRecordingStream).not.toHaveBeenCalled()
+ expect(signalOf(delegate).aborted).toBe(false)
+
+ const next = open(client, 2)
+
+ await settle()
+
+ expect(answer(client, next).status).toBe(HDSStatus.SUCCESS)
+ })
+
+ it('ignores an acknowledgement naming another stream, after its loop and while it runs', async () => {
+ const finished = recordingDelegate(async function* () {
+ yield packet(100, true)
+ })
+ const first = recordingCamera(finished)
+ const firstClient = await DataStreamClient.connect(first.dataStreamManagement)
+
+ open(firstClient)
+ await settle()
+ acknowledge(firstClient, 99)
+ vi.advanceTimersByTime(12000)
+
+ expect(finished.acknowledgeStream).not.toHaveBeenCalled()
+ expect(closeEvents(firstClient)).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.CANCELLED, streamId: 1 },
+ ])
+ expect(finished.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.CANCELLED)
+
+ const held = deferred()
+ const running = recordingDelegate(async function* () {
+ yield packet(100)
+ await held.promise
+ yield packet(100, true)
+ })
+ const second = recordingCamera(running)
+ const secondClient = await DataStreamClient.connect(second.dataStreamManagement)
+
+ open(secondClient)
+ await settle()
+ acknowledge(secondClient, 99)
+ held.resolve()
+ await settle()
+
+ expect(running.acknowledgeStream).not.toHaveBeenCalled()
+ expect(signalOf(running).aborted).toBe(false)
+ expect(chunks(secondClient).map(({ endOfStream }) => endOfStream)).toEqual([false, true])
+ })
+
+ it('stops a recording at the hub\'s close: the delegate told its reason while the camera is busy, its signal aborted and no packet sent after', async () => {
+ let reached = 0
+ let released = false
+ const delegate = recordingDelegate(async function* (_streamId, signal) {
+ try {
+ yield packet(100)
+ await aborted(signal!)
+ reached++
+ yield packet(100)
+ reached++
+ yield packet(100, true)
+ } finally {
+ released = true
+ }
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const atCall: unknown[] = []
+
+ delegate.closeRecordingStream.mockImplementation(() => {
+ atCall.push({ aborted: signalOf(delegate).aborted, busy: recordingStreamOf(management) !== undefined })
+ })
+
+ open(client)
+ await settle()
+ hubClose(client, 99, HDSProtocolSpecificErrorReason.TIMEOUT)
+ await settle()
+
+ expect(delegate.closeRecordingStream).not.toHaveBeenCalled()
+
+ hubClose(client, 1, HDSProtocolSpecificErrorReason.TIMEOUT)
+ await settle()
+
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.TIMEOUT)
+ expect(atCall).toEqual([
+ { aborted: true, busy: true },
+ ])
+ expect(released).toBe(true)
+ expect(reached).toBe(1)
+ expect(dataEvents(client)).toHaveLength(1)
+ expect(answer(client, open(client, 2)).status).toBe(HDSStatus.SUCCESS)
+ })
+
+ it('stops a recording when its connection closes: the delegate told with no reason while the camera is busy, its signal aborted', async () => {
+ const delegate = recordingDelegate(async function* (_streamId, signal) {
+ yield packet(100)
+ await aborted(signal!)
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const other = await DataStreamClient.connect(management.dataStreamManagement)
+ const atCall: unknown[] = []
+
+ delegate.closeRecordingStream.mockImplementation(() => {
+ atCall.push({ aborted: signalOf(delegate).aborted, busy: recordingStreamOf(management) !== undefined })
+ })
+
+ open(client)
+ await settle()
+ client.closeSocket()
+ await settle()
+
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, undefined)
+ expect(atCall).toEqual([
+ { aborted: true, busy: true },
+ ])
+ expect(answer(other, open(other)).status).toBe(HDSStatus.SUCCESS)
+ })
+
+ it('reports a delegate\'s throw at a stream\'s close as the library\'s failure on the channel of a camera whose management holds its reporter, and logs '
+ + 'it where the management holds none', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { problems, reporter } = problemsOf()
+ const failure = new Error('The delegate failed to close the recording.')
+ // A recording that waits for its close, whose delegate throws as it is told of it.
+ const closing = (): RecordingDelegate => {
+ const delegate = recordingDelegate(async function* (_streamId, signal) {
+ await aborted(signal!)
+ })
+
+ delegate.closeRecordingStream.mockImplementation(() => {
+ throw failure
+ })
+
+ return delegate
+ }
+ const reporting = recordingCamera(closing(), {
+ feed: new ServedRecordings({ reporter, sensorUUID: FIRST_VIDEO_SENSOR.uuid }),
+ reporter,
+ })
+ const legacy = recordingCamera(closing())
+ const sentence = '[HDS 192.0.2.1] CameraRecordingDelegate failed to handle closing the stream 1: Error: The delegate failed to close the recording.'
+
+ for (const management of [reporting, legacy]) {
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+ hubClose(client, 1, HDSProtocolSpecificErrorReason.NORMAL)
+ await settle()
+ }
+
+ expect(problems.map(problem => ({ ...problem, sentence: problem.sentence.split('\n')[0] }))).toEqual([
+ {
+ accessoryUUID: REPORTER_ACCESSORY_UUID,
+ error: failure,
+ kind: 'library-failure',
+ level: 'error',
+ sentence,
+ },
+ ])
+ expect(error.mock.calls.map(([line]) => String(line).split('\n')[0])).toEqual([sentence])
+ })
+
+ it('closes a recording with not allowed at a write of HomeKit Camera Active off, the close sent before the delegate hears it', async () => {
+ const delegate = recordingDelegate(async function* (_streamId, signal) {
+ yield packet(100)
+ await aborted(signal!)
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const atCall: unknown[] = []
+
+ delegate.closeRecordingStream.mockImplementation(() => {
+ atCall.push({
+ busy: recordingStreamOf(management) !== undefined,
+ closes: closeEvents(client),
+ })
+ })
+
+ open(client)
+ await settle()
+ management.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).setValue(Characteristic.HomeKitCameraActive.OFF)
+
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.NOT_ALLOWED)
+ expect(atCall).toEqual([
+ {
+ busy: true,
+ closes: [
+ { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, streamId: 1 },
+ ],
+ },
+ ])
+ })
+
+ it('closes a finished recording the hub does not acknowledge as cancelled 12 seconds after its loop, warning of one that ends without its last packet', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const marked = recordingDelegate(async function* () {
+ yield packet(100, true)
+ })
+ const unmarked = recordingDelegate(async function* () {
+ yield packet(100)
+ })
+
+ for (const delegate of [marked, unmarked]) {
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+ vi.advanceTimersByTime(11999)
+
+ expect(closeEvents(client)).toEqual([])
+ expect(delegate.closeRecordingStream).not.toHaveBeenCalled()
+
+ vi.advanceTimersByTime(1)
+
+ expect(closeEvents(client)).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.CANCELLED, streamId: 1 },
+ ])
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.CANCELLED)
+ expect(signalOf(delegate).aborted).toBe(false)
+ }
+
+ expect(warn.mock.calls).toEqual([
+ ['[HDS 192.0.2.1] Delegate finished streaming for 1 without setting RecordingPacket.isLast. Can\'t notify Controller about endOfStream!'],
+ ])
+ })
+
+ it('logs a delegate still running 10 seconds after its recording closed, and not one that settles at its signal', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const held = deferred()
+ const ignoring = recordingDelegate(async function* () {
+ yield packet(100)
+ await held.promise
+ })
+ const settling = recordingDelegate(async function* (_streamId, signal) {
+ yield packet(100)
+ await aborted(signal!)
+ })
+ const first = recordingCamera(ignoring)
+ const firstClient = await DataStreamClient.connect(first.dataStreamManagement)
+
+ open(firstClient)
+ await settle()
+ hubClose(firstClient, 1, HDSProtocolSpecificErrorReason.NORMAL)
+ await settle()
+ vi.advanceTimersByTime(9999)
+
+ expect(error).not.toHaveBeenCalled()
+
+ vi.advanceTimersByTime(1)
+
+ expect(error.mock.calls).toEqual([
+ [
+ '[HDS %s] Recording download stream %d is still awaiting generator although stream was closed 10s ago! '
+ + 'This is a programming mistake by the camera implementation which prevents freeing up resources.',
+ '192.0.2.1',
+ 1,
+ ],
+ ])
+
+ held.resolve()
+ error.mockClear()
+
+ const second = recordingCamera(settling)
+ const secondClient = await DataStreamClient.connect(second.dataStreamManagement)
+
+ open(secondClient)
+ await settle()
+ hubClose(secondClient, 1, HDSProtocolSpecificErrorReason.NORMAL)
+ await settle()
+ vi.advanceTimersByTime(10000)
+
+ expect(error).not.toHaveBeenCalled()
+ })
+
+ it('closes a recording whose delegate throws with the reason it names, as an unexpected failure, or at 12 seconds for a closed socket', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const throwing = (failure: Error): RecordingDelegate => recordingDelegate(async function* () {
+ yield packet(100)
+ throw failure
+ })
+ const named = throwing(new HDSProtocolError(HDSProtocolSpecificErrorReason.TIMEOUT))
+ const unexpected = throwing(new Error('The recording failed.'))
+ const closedSocket = throwing(new HDSConnectionError('The socket closed.', HDSConnectionErrorType.CLOSED_SOCKET))
+
+ for (const [delegate, reason] of [
+ [named, HDSProtocolSpecificErrorReason.TIMEOUT],
+ [unexpected, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE],
+ ] as const) {
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ expect(closeEvents(client)).toEqual([
+ { reason, streamId: 1 },
+ ])
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, reason)
+ }
+
+ expect(error.mock.calls).toEqual([
+ [
+ expect.stringContaining('[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: Error: The recording failed.'),
+ ],
+ ])
+ error.mockClear()
+
+ const management = recordingCamera(closedSocket)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+ vi.advanceTimersByTime(11999)
+
+ expect(closeEvents(client)).toEqual([])
+ expect(closedSocket.closeRecordingStream).not.toHaveBeenCalled()
+
+ vi.advanceTimersByTime(1)
+
+ expect(closeEvents(client)).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.CANCELLED, streamId: 1 },
+ ])
+ expect(closedSocket.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.CANCELLED)
+ expect(error).not.toHaveBeenCalled()
+ expect(warn).not.toHaveBeenCalled()
+ })
+
+ it('leaves a running recording to its socket\'s close at destroy, telling the delegate nothing until then and reading no later frame', async () => {
+ const delegate = recordingDelegate(async function* (_streamId, signal) {
+ yield packet(100)
+ await aborted(signal!)
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+ management.destroy()
+
+ expect(client.socket.end).toHaveBeenCalledTimes(1)
+ expect(delegate.closeRecordingStream).not.toHaveBeenCalled()
+
+ acknowledge(client)
+
+ expect(delegate.acknowledgeStream).not.toHaveBeenCalled()
+
+ client.closeSocket()
+
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, undefined)
+ })
+
+ it('keeps a running recording through a factory reset', async () => {
+ const held = deferred()
+ const delegate = recordingDelegate(async function* () {
+ yield packet(100)
+ await held.promise
+ yield packet(100, true)
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+ management.handleFactoryReset()
+ held.resolve()
+ await settle()
+
+ expect(dataEvents(client)).toHaveLength(2)
+ expect(closeEvents(client)).toEqual([])
+ expect(delegate.closeRecordingStream).not.toHaveBeenCalled()
+ })
+
+ it('writes every chunk of a packet to a socket that reports a full buffer before it pulls the next packet', async () => {
+ const writesAtPull: number[] = []
+ let client: DataStreamClient | undefined
+ const delegate = recordingDelegate(async function* () {
+ yield packet(3 * MAX_CHUNK)
+ writesAtPull.push(client!.socket.write.mock.calls.length)
+ yield packet(100, true)
+ })
+ const management = recordingCamera(delegate)
+
+ client = await DataStreamClient.connect(management.dataStreamManagement)
+ client.socket.write.mockReturnValue(false)
+
+ const before = client.socket.write.mock.calls.length
+
+ open(client)
+ await settle()
+
+ // The open's answer, then the packet's three chunks.
+ expect(writesAtPull).toEqual([before + 4])
+ })
+
+ it('releases the delegate\'s recording at the break that follows its last packet', async () => {
+ let released = false
+ const delegate = recordingDelegate(async function* () {
+ try {
+ yield packet(100, true)
+ yield packet(100)
+ } finally {
+ released = true
+ }
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ expect(released).toBe(true)
+ })
+
+ it('answers each open on a running recording\'s own connection by the open\'s checks, the recording running on', async () => {
+ const delegate = recordingDelegate(async function* (_streamId, signal) {
+ yield packet(100)
+ await aborted(signal!)
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ const second = open(client, 2)
+ const snapshot = open(client, 3, { type: 'ipcamera.snapshot' })
+
+ management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.INACTIVE)
+ await settle()
+
+ const switchedOff = open(client, 4)
+
+ expect([second, snapshot, switchedOff].map(id => answer(client, id))).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR },
+ { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR },
+ { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR },
+ ])
+ expect(recordingStreamOf(management)).toBeDefined()
+ expect(delegate.closeRecordingStream).not.toHaveBeenCalled()
+ })
+
+ it('refuses an open as not allowed unless recording is active and the camera is on, and lets one through with both', async () => {
+ const answers: unknown[] = []
+
+ for (const recordingActive of [false, true]) {
+ for (const cameraActive of [false, true]) {
+ const management = recordingCamera(recordingDelegate(async function* () {
+ yield packet(100, true)
+ }))
+
+ management.recordingManagementService.getCharacteristic(Characteristic.Active)
+ .setValue(recordingActive ? Characteristic.Active.ACTIVE : Characteristic.Active.INACTIVE)
+ management.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive)
+ .setValue(cameraActive ? Characteristic.HomeKitCameraActive.ON : Characteristic.HomeKitCameraActive.OFF)
+
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ answers.push(answer(client, open(client)))
+ }
+ }
+
+ const notAllowed = { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }
+
+ expect(answers).toEqual([
+ notAllowed,
+ notAllowed,
+ notAllowed,
+ { reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS },
+ ])
+ })
+
+ it('refuses an open by the first check it fails: target, recording allowed, busy, configuration, a later check failing too where it can', async () => {
+ const delegate = recordingDelegate(async function* (_streamId, signal) {
+ yield packet(100)
+ await aborted(signal!)
+ })
+ const management = recordingCamera(delegate)
+ const recording = await DataStreamClient.connect(management.dataStreamManagement)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const refused = (overrides: Record = {}): { reason?: number, status?: number } => answer(client, open(client, 2, overrides))
+ const specificError = (reason: HDSProtocolSpecificErrorReason): { reason: number, status: number } => ({
+ reason,
+ status: HDSStatus.PROTOCOL_SPECIFIC_ERROR,
+ })
+
+ open(recording)
+ await settle()
+
+ // A factory reset clears the configuration and switches recording off, and leaves the recording running.
+ management.handleFactoryReset()
+
+ expect(refused({ target: 'accessory' })).toEqual(specificError(HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE))
+ expect(refused()).toEqual(specificError(HDSProtocolSpecificErrorReason.NOT_ALLOWED))
+
+ management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE)
+ await settle()
+
+ expect(refused()).toEqual(specificError(HDSProtocolSpecificErrorReason.BUSY))
+
+ // HomeKit Camera Active off closes the running recording.
+ management.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).setValue(Characteristic.HomeKitCameraActive.OFF)
+
+ expect(refused()).toEqual(specificError(HDSProtocolSpecificErrorReason.NOT_ALLOWED))
+
+ management.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).setValue(Characteristic.HomeKitCameraActive.ON)
+
+ expect(refused()).toEqual(specificError(HDSProtocolSpecificErrorReason.INVALID_CONFIGURATION))
+ })
+
+ it('lets a stream go from its route and the camera at a delegate\'s synchronous throw, and a route go from the management at its connection\'s close', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => undefined)
+
+ const delegate = recordingDelegate(() => {
+ throw new Error('The recording could not start.')
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ // @ts-expect-error: private access
+ const routes: Map }> = management.routes
+
+ expect(routes.get(client.connection)?.streams.size).toBe(0)
+ expect(recordingStreamOf(management)).toBeUndefined()
+
+ client.closeSocket()
+
+ expect(routes.size).toBe(0)
+ })
+
+ it('serves a second recording on one connection after the first, its acknowledgement its own', async () => {
+ const delegate = recordingDelegate(async function* () {
+ yield packet(100, true)
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+ acknowledge(client)
+
+ expect(answer(client, open(client, 9, { type: 'ipcamera.snapshot' }))).toEqual({
+ reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE,
+ status: HDSStatus.PROTOCOL_SPECIFIC_ERROR,
+ })
+
+ open(client, 2)
+ await settle()
+ acknowledge(client, 2)
+ vi.advanceTimersByTime(12000)
+
+ expect(delegate.acknowledgeStream.mock.calls).toEqual([
+ [1],
+ [2],
+ ])
+ expect(closeEvents(client)).toEqual([])
+ })
+
+ it('closes a recording as an unexpected failure when its release at the last packet throws, after the end was sent', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const delegate = recordingDelegate(async function* () {
+ try {
+ yield packet(100, true)
+ } finally {
+ // eslint-disable-next-line no-unsafe-finally
+ throw new Error('The recording could not be released.')
+ }
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ const topics = client.written.slice(2).map(({ header, message }) => [header.event, message.endOfStream ?? message.reason])
+
+ expect(topics).toEqual([
+ [Topics.DATA, true],
+ [Topics.CLOSE, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE],
+ ])
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE)
+ expect(error.mock.calls).toEqual([
+ [
+ expect.stringContaining('[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: Error: The recording could not be released.'),
+ ],
+ ])
+ })
+
+ it('keeps the error of a recording\'s packet over the error of its release', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const delegate = recordingDelegate(async function* () {
+ try {
+ yield undefined as unknown as RecordingPacket
+ } finally {
+ // eslint-disable-next-line no-unsafe-finally
+ throw new Error('The recording could not be released.')
+ }
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ expect(error.mock.calls).toEqual([
+ [
+ expect.stringContaining('[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: TypeError: '),
+ ],
+ ])
+ expect(error.mock.calls[0][0]).not.toContain('The recording could not be released.')
+ expect(closeEvents(client)).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, streamId: 1 },
+ ])
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE)
+ })
+
+ it('streams a synchronous recording, an array or a generator of promised packets, as it streams a generator', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const array = recordingDelegate(() => [
+ packet(100),
+ packet(100, true),
+ ] as unknown as AsyncGenerator)
+ const promised = recordingDelegate(function* () {
+ yield Promise.resolve(packet(100))
+ yield Promise.resolve(packet(100, true))
+ } as unknown as RecordingRequest)
+
+ for (const delegate of [array, promised]) {
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+ acknowledge(client)
+
+ expect(chunks(client).map(({ endOfStream, metadata }) => [(metadata as { dataSequenceNumber: number }).dataSequenceNumber, endOfStream]))
+ .toEqual([
+ [1, false],
+ [2, true],
+ ])
+ expect(delegate.acknowledgeStream).toHaveBeenCalledExactlyOnceWith(1)
+ }
+
+ expect(error).not.toHaveBeenCalled()
+ expect(warn).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('a recording\'s timers', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ it('leaves no timer holding the process once a recording closes at the hub\'s acknowledgement, the hub\'s close or the connection\'s close', async () => {
+ const finished = recordingDelegate(async function* () {
+ yield packet(100)
+ yield packet(100, true)
+ })
+ // Parked on its signal: each close comes while the loop runs and arms the watchdog the loop's exit clears.
+ const parked = recordingDelegate(async function* (_streamId, signal) {
+ yield packet(100)
+ await aborted(signal!)
+ })
+ const closes: [RecordingDelegate, (client: DataStreamClient) => void][] = [
+ [
+ finished,
+ client => acknowledge(client),
+ ],
+ [
+ parked,
+ client => hubClose(client, 1, HDSProtocolSpecificErrorReason.NORMAL),
+ ],
+ [
+ parked,
+ client => client.closeSocket(),
+ ],
+ ]
+
+ // The fake clock, installed after the connect, counts each timer armed through the global setTimeout from then on, referenced or not, and none armed
+ // through Node's own timers, as the runner's are. The count at the close reads the recording's timers alone.
+ for (const [delegate, close] of closes) {
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+
+ const before = vi.getTimerCount()
+
+ open(client)
+ await settle()
+ close(client)
+ await settle()
+
+ expect(vi.getTimerCount()).toBe(before)
+ vi.useRealTimers()
+ }
+ })
+ })
+
+ describe('a recording\'s failures that reach the process', () => {
+ // The listener collects each rejection no handler takes during a row, any of which would end a Homebridge process, and Vitest reports none of them while
+ // it stands.
+ const unhandled: unknown[] = []
+ const collect = (reason: unknown): void => {
+ unhandled.push(reason)
+ }
+
+ // The debug lines of the data stream server, whose dispatch reports a handler that throws, and of the recording management, which reports a failed
+ // return of a closed recording.
+ const logged: string[] = []
+ let enabled: string
+ let log: (...args: unknown[]) => void
+
+ beforeEach(() => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ unhandled.length = 0
+ logged.length = 0
+ process.on('unhandledRejection', collect)
+ enabled = createDebug.disable()
+ log = (createDebug as unknown as { log: typeof log }).log;
+ (createDebug as unknown as { log: typeof log }).log = (...args: unknown[]) => {
+ logged.push(format(...args))
+ }
+ createDebug.enable('HAP-NodeJS:DataStream:Server,HAP-NodeJS:Camera:RecordingManagement')
+ })
+
+ afterEach(() => {
+ (createDebug as unknown as { log: typeof log }).log = log
+ createDebug.disable()
+
+ if (enabled) {
+ createDebug.enable(enabled)
+ }
+
+ process.off('unhandledRejection', collect)
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ // An answer whose iterator is an object of its own with no return: it hands one packet and then waits for the row.
+ function iterableWithoutReturn(held: Promise): AsyncGenerator {
+ return {
+ [Symbol.asyncIterator]: () => {
+ let sent = false
+
+ return {
+ next: async (): Promise> => {
+ if (!sent) {
+ sent = true
+
+ return {
+ done: false,
+ value: packet(100),
+ }
+ }
+
+ await held
+
+ return { done: true, value: undefined }
+ },
+ }
+ },
+ } as unknown as AsyncGenerator
+ }
+
+ // An answer that is its own iterator, handing one packet and then waiting, with the return the row gives it.
+ function selfIterator(onReturn: () => unknown): AsyncGenerator {
+ let sent = false
+ const iterator = {
+ [Symbol.asyncIterator]: () => iterator,
+ next: async (): Promise> => {
+ if (!sent) {
+ sent = true
+
+ return {
+ done: false,
+ value: packet(100),
+ }
+ }
+
+ return new Promise(() => undefined)
+ },
+ return: onReturn,
+ }
+
+ return iterator as unknown as AsyncGenerator
+ }
+
+ it('ends a stream whose open\'s answer finds its connection closing, with no close event, nothing told to the delegate and nothing unhandled', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const delegate = recordingDelegate(async function* () {
+ yield packet(100, true)
+ })
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const other = await DataStreamClient.connect(management.dataStreamManagement)
+
+ management.dataStreamManagement.onEventMessage('test', 'shut', connection => connection.close())
+ client.send(client.eventFrame('test', 'shut'), client.requestFrame(Protocols.DATA_SEND, Topics.OPEN, OPEN_RECORDING))
+ await settle()
+
+ expect(unhandled).toEqual([])
+ expect(delegate.handleRecordingStreamRequest).not.toHaveBeenCalled()
+ expect(recordingStreamOf(management)).toBeUndefined()
+
+ client.closeSocket()
+
+ expect(closeEvents(client)).toEqual([])
+ expect(delegate.closeRecordingStream).not.toHaveBeenCalled()
+ expect(answer(other, open(other)).status).toBe(HDSStatus.SUCCESS)
+ expect(warn).not.toHaveBeenCalled()
+ expect(error).not.toHaveBeenCalled()
+ })
+
+ describe('a recording whose answer is not a generator', () => {
+ it('frees the camera with the delegate told at the hub\'s close, the library\'s close and the connection\'s close of an iterator with no return', async () => {
+ const held = deferred()
+ const delegate = recordingDelegate(() => iterableWithoutReturn(held.promise))
+ const hub = recordingCamera(delegate)
+ const hubClient = await DataStreamClient.connect(hub.dataStreamManagement)
+
+ open(hubClient)
+ await settle()
+ hubClose(hubClient, 1, HDSProtocolSpecificErrorReason.NORMAL)
+ await settle()
+
+ expect(answer(hubClient, open(hubClient, 2)).status).toBe(HDSStatus.SUCCESS)
+
+ const library = recordingCamera(delegate)
+ const libraryClient = await DataStreamClient.connect(library.dataStreamManagement)
+
+ open(libraryClient)
+ await settle()
+
+ await expect(library.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).handleSetRequest(Characteristic.HomeKitCameraActive.OFF))
+ .resolves
+ .toBeUndefined()
+ expect(closeEvents(libraryClient)).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, streamId: 1 },
+ ])
+ expect(recordingStreamOf(library)).toBeUndefined()
+
+ const connection = recordingCamera(delegate)
+ const connectionClient = await DataStreamClient.connect(connection.dataStreamManagement)
+ const other = await DataStreamClient.connect(connection.dataStreamManagement)
+
+ open(connectionClient)
+ await settle()
+
+ expect(() => connectionClient.closeSocket()).not.toThrow()
+ expect(answer(other, open(other)).status).toBe(HDSStatus.SUCCESS)
+ expect(delegate.closeRecordingStream.mock.calls).toEqual([
+ [1, HDSProtocolSpecificErrorReason.NORMAL],
+ [1, HDSProtocolSpecificErrorReason.NOT_ALLOWED],
+ [1, undefined],
+ ])
+ expect(logged.join('\n')).not.toContain('TypeError')
+ expect(unhandled).toEqual([])
+ })
+
+ it('frees the camera with the delegate told at an iterator whose next rejects and at a delegate answering a promise, closing as unexpected', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const rejecting = recordingDelegate(() => ({
+ [Symbol.asyncIterator]: () => ({
+ next: async (): Promise> => {
+ throw new Error('The recording failed.')
+ },
+ }),
+ }) as unknown as AsyncGenerator)
+ const promising = recordingDelegate((async () => packet(100, true)) as unknown as RecordingRequest)
+
+ for (const delegate of [rejecting, promising]) {
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ expect(closeEvents(client)).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, streamId: 1 },
+ ])
+ expect(recordingStreamOf(management)).toBeUndefined()
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE)
+ }
+
+ expect(error.mock.calls).toEqual([
+ [
+ expect.stringContaining('[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: Error: The recording failed.'),
+ ],
+ [
+ expect.stringContaining('[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: TypeError: '),
+ ],
+ ])
+ expect(unhandled).toEqual([])
+ })
+
+ it('frees the camera with the delegate told at the hub\'s close of an iterator whose return throws, answers a plain object or rejects', async () => {
+ const throwing = recordingDelegate(() => selfIterator(() => {
+ throw new Error('The recording could not stop.')
+ }))
+ const plain = recordingDelegate(() => selfIterator(() => ({ done: true, value: undefined })))
+ const rejecting = recordingDelegate(() => selfIterator(async () => {
+ throw new Error('The recording could not stop.')
+ }))
+
+ for (const [delegate, failed] of [
+ [throwing, true],
+ [plain, false],
+ [rejecting, true],
+ ] as const) {
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ logged.length = 0
+ open(client)
+ await settle()
+ hubClose(client, 1, HDSProtocolSpecificErrorReason.NORMAL)
+ await settle()
+
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.NORMAL)
+ expect(answer(client, open(client, 2)).status).toBe(HDSStatus.SUCCESS)
+ expect(logged.join('\n').includes('Error while closing the recording of stream 1: Error: The recording could not stop.')).toBe(failed)
+ }
+
+ expect(unhandled).toEqual([])
+ })
+
+ it('takes one iterator from a recording that makes a fresh one at each call, and asks that one to stop at the hub\'s close', async () => {
+ let made = 0
+ let returned = 0
+ const delegate = recordingDelegate(() => ({
+ [Symbol.asyncIterator]: () => {
+ let sent = false
+
+ made++
+
+ return {
+ next: async (): Promise> => {
+ if (!sent) {
+ sent = true
+
+ return {
+ done: false,
+ value: packet(100),
+ }
+ }
+
+ return new Promise(() => undefined)
+ },
+ return: async (): Promise> => {
+ returned++
+
+ return { done: true, value: undefined }
+ },
+ }
+ },
+ }) as unknown as AsyncGenerator)
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+ hubClose(client, 1, HDSProtocolSpecificErrorReason.NORMAL)
+ await settle()
+
+ expect(made).toBe(1)
+ expect(returned).toBe(1)
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.NORMAL)
+ expect(unhandled).toEqual([])
+ })
+
+ it('streams an answer whose async iterator method reads undefined or null by its iterator, and closes at a non-object with the library\'s sentence', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+
+ for (const method of [undefined, null]) {
+ const synchronous = recordingDelegate(() => ({
+ [Symbol.asyncIterator]: method,
+ * [Symbol.iterator]() {
+ yield packet(100)
+ yield packet(100, true)
+ },
+ }) as unknown as AsyncGenerator)
+ const management = recordingCamera(synchronous)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+ acknowledge(client)
+
+ expect(chunks(client).map(({ endOfStream }) => endOfStream)).toEqual([false, true])
+ expect(synchronous.acknowledgeStream).toHaveBeenCalledExactlyOnceWith(1)
+ }
+
+ for (const value of [undefined, 'a recording']) {
+ const delegate = recordingDelegate(() => value as unknown as AsyncGenerator)
+ const refused = recordingCamera(delegate)
+ const refusedClient = await DataStreamClient.connect(refused.dataStreamManagement)
+
+ open(refusedClient)
+ await settle()
+
+ expect(closeEvents(refusedClient)).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, streamId: 1 },
+ ])
+ expect(recordingStreamOf(refused)).toBeUndefined()
+ expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE)
+ }
+
+ const sentence = '[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: TypeError: '
+ + 'The recording delegate answered a value that is neither an async iterable nor an iterable.'
+
+ expect(error.mock.calls).toEqual([
+ [
+ expect.stringContaining(sentence),
+ ],
+ [
+ expect.stringContaining(sentence),
+ ],
+ ])
+ expect(unhandled).toEqual([])
+ })
+
+ // The delegate is typed against the interface with no cast, and the spec typecheck reads whether the interface takes an async iterable that is no
+ // generator.
+ it('streams a recording a delegate answers as a readable stream, an async iterable that is no generator', async () => {
+ const delegate = recordingDelegate(() => new ReadableStream({
+ start(controller) {
+ controller.enqueue(packet(100))
+ controller.enqueue(packet(100, true))
+ controller.close()
+ },
+ }))
+ const management = recordingCamera(delegate)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+ acknowledge(client)
+
+ expect(chunks(client).map(({ endOfStream }) => endOfStream)).toEqual([false, true])
+ expect(delegate.acknowledgeStream).toHaveBeenCalledExactlyOnceWith(1)
+ expect(recordingStreamOf(management)).toBeUndefined()
+ expect(unhandled).toEqual([])
+ })
+ })
+ })
+
+ describe('a snapshot over a data stream connection', () => {
+ const PICTURE = crypto.randomBytes(1000)
+
+ // The cameras a row builds, removed after it. No stream or policy outlives its row.
+ const cameras: CameraController[] = []
+
+ beforeEach(() => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout'],
+ })
+ })
+
+ afterEach(() => {
+ for (const camera of cameras.splice(0)) {
+ camera.handleControllerRemoved()
+ }
+
+ vi.restoreAllMocks()
+ vi.useRealTimers()
+ })
+
+ type SnapshotHandler = CameraStreamingDelegate['handleSnapshotRequest']
+
+ type SnapshotDelegate = RecordingDelegate & { handleSnapshotRequest: Mock }
+
+ type SnapshotFunction = (request: CameraSnapshotRequest, signal: AbortSignal) => Promise
+
+ // The calls of a camera's recording delegate a row reads, each a spy.
+ type RecordingCalls = { [Method in 'acknowledgeStream' | 'closeRecordingStream' | 'handleRecordingStreamRequest']: MockInstance }
+
+ /* A recording camera, handed a published context, its recording switched on and its services kept, whose snapshots are answered with the row's
+ * picture, each call a spy. With the capabilities block the block's snapshot function answers them, the camera keeping the legacy delegate its fixture
+ * gives, and it records from its camera buffer, whose recorded tier holds a keyframe so its recorder serves a recording. A legacy camera, when the row
+ * asks for one, answers them through its delegate's handler and records through that delegate, whose recording yields an initialization segment and
+ * then waits on its signal. The delegate is handed to no camera with the block, and the function to no legacy camera.
+ */
+ function snapshotCamera(capabilities = true, picture = PICTURE): {
+ camera: CameraController
+ delegate: SnapshotDelegate
+ management: RecordingManagement
+ map: CameraControllerServiceMap
+ recording: RecordingCalls
+ snapshot: Mock
+ } {
+ const delegate: SnapshotDelegate = Object.assign(recordingDelegate(async function* (_streamId, signal) {
+ yield { data: skeletonPackets()[0], isLast: false }
+ await aborted(signal!)
+ }), {
+ handleSnapshotRequest: vi.fn((_request, callback) => callback(undefined, picture)),
+ })
+ const snapshot = vi.fn(async () => picture)
+ const buffered = bufferCamera({ prebuffer: 0 })
+ const camera = new CameraController(capabilities
+ ? {
+ ...buffered.options,
+ cameraCapabilities: { ...buffered.options.cameraCapabilities, snapshot },
+ }
+ : createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate))
+
+ cameras.push(camera)
+
+ const map = camera.constructServices()
+
+ camera.configureServices()
+ handPublishedContext(camera)
+
+ const management = camera.recordingManagement!
+
+ if (!capabilities) {
+ management.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION)
+ management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE)
+
+ return {
+ camera,
+ delegate,
+ management,
+ map,
+ recording: delegate,
+ snapshot,
+ }
+ }
+
+ const recorder = management.delegate as BufferRecorder
+
+ management.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE)
+ buffered.stream().write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS }))
+ frames(buffered.stream(), 0, 1)
+
+ return {
+ camera,
+ delegate,
+ management,
+ map,
+ recording: {
+ acknowledgeStream: vi.spyOn(recorder, 'acknowledgeStream'),
+ closeRecordingStream: vi.spyOn(recorder, 'closeRecordingStream'),
+ handleRecordingStreamRequest: vi.spyOn(recorder, 'handleRecordingStreamRequest'),
+ },
+ snapshot,
+ }
+ }
+
+ function openSnapshot(client: DataStreamClient, streamId = 2, metadata: Record = { imageHeight: 360, imageWidth: 640, reason: 1 }): number {
+ return client.request(Protocols.DATA_SEND, Topics.OPEN, {
+ metadata,
+ reason: 'snapshot',
+ streamId,
+ target: 'controller',
+ type: 'ipcamera.snapshot',
+ })
+ }
+
+ function streamEvents(client: DataStreamClient, topic: string, streamId = 2): Record[] {
+ return client.events(Protocols.DATA_SEND, topic).filter(event => event.streamId === streamId)
+ }
+
+ it('waits for the hub\'s acknowledgement of a sent snapshot on a timer that keeps no process alive', async () => {
+ const { management } = snapshotCamera()
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const timers = vi.spyOn(globalThis, 'setTimeout')
+
+ openSnapshot(client)
+ await settle()
+
+ // The wait is the 12 second timer the sent snapshot armed, read through the handle setTimeout answered.
+ const wait = timers.mock.calls.findLastIndex(([, delay]) => delay === 12000)
+
+ expect(streamEvents(client, Topics.DATA)).toHaveLength(1)
+ expect(wait).toBeGreaterThanOrEqual(0)
+ expect((timers.mock.results[wait].value as ReturnType).hasRef()).toBe(false)
+ })
+
+ it('answers a snapshot open with one data event carrying no data type while a recording runs on the same connection', async () => {
+ const { management, snapshot } = snapshotCamera()
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ const id = openSnapshot(client)
+
+ await settle()
+
+ expect(answer(client, id)).toEqual({ reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS })
+ expect(snapshot).toHaveBeenCalledExactlyOnceWith({
+ height: 360,
+ keyframe: expect.objectContaining({ height: 36, width: 64 }),
+ reason: ResourceRequestReason.EVENT,
+ sensorUUID: FIRST_VIDEO_SENSOR.uuid.toLowerCase(),
+ width: 640,
+ }, expect.any(AbortSignal))
+ expect(streamEvents(client, Topics.DATA)).toEqual([
+ {
+ endOfStream: true,
+ packets: [
+ {
+ data: PICTURE,
+ metadata: {
+ dataChunkSequenceNumber: 1,
+ dataSequenceNumber: 1,
+ dataTotalSize: PICTURE.length,
+ isLastDataChunk: true,
+ },
+ },
+ ],
+ streamId: 2,
+ },
+ ])
+ expect(recordingStreamOf(management)).toBeDefined()
+ })
+
+ it('sends a picture above 256 KiB in chunks of one data sequence, the last alone ending it', async () => {
+ const picture = crypto.randomBytes(MAX_CHUNK + 100)
+ const { management } = snapshotCamera(true, picture)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ openSnapshot(client)
+ await settle()
+
+ expect(streamEvents(client, Topics.DATA).map(({ endOfStream, packets: [{ data, metadata }] }) => ({ endOfStream, length: data.length, metadata }))).toEqual([
+ {
+ endOfStream: undefined,
+ length: MAX_CHUNK,
+ metadata: {
+ dataChunkSequenceNumber: 1,
+ dataSequenceNumber: 1,
+ dataTotalSize: picture.length,
+ isLastDataChunk: false,
+ },
+ },
+ {
+ endOfStream: true,
+ length: 100,
+ metadata: { dataChunkSequenceNumber: 2, dataSequenceNumber: 1, isLastDataChunk: true },
+ },
+ ])
+ })
+
+ it('serves a snapshot while the global service allows streaming, and refuses one while its Streaming Enabled reads off', async () => {
+ const { management, map, snapshot } = snapshotCamera()
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ openSnapshot(client)
+ await settle()
+
+ expect(streamEvents(client, Topics.DATA)).toHaveLength(1)
+
+ map['cameraCapabilities:globalOperatingMode']!.updateCharacteristic(Characteristic.StreamingEnabled, false)
+
+ const refused = openSnapshot(client, 3)
+
+ await settle()
+
+ expect(answer(client, refused)).toEqual({ reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR })
+ expect(streamEvents(client, Topics.DATA, 3)).toEqual([])
+ expect(snapshot).toHaveBeenCalledTimes(1)
+ })
+
+ it('refuses a snapshot of a camera out of service as busy over the data stream and with the communication failure over the resource request, '
+ + 'calling no snapshot function and writing why to the debug log', async () => {
+ const { camera, management, snapshot } = snapshotCamera()
+ // The capture begins after the camera's setup, and it reads every line the channel writes from there on.
+ const lines = captureDebug('HAP-NodeJS:Camera:Controller')
+ const accessoryInformation = new Service.AccessoryInformation() as AccessoryInformation
+
+ // The camera's accessory is unpublished: its context reads not published, under the name the data stream's refusal reads.
+ accessoryInformation.setCharacteristic(Characteristic.Name, 'Front Door')
+ camera.handleAccessoryContext({
+ accessoryInformation,
+ accessoryUUID: 'b1b2c3d4-0000-4000-8000-000000000002',
+ published: false,
+ username: undefined,
+ })
+
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const refused = openSnapshot(client)
+
+ await settle()
+
+ expect(answer(client, refused)).toEqual({ reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR })
+ expect(streamEvents(client, Topics.DATA)).toEqual([])
+ await expect(camera.handleSnapshotRequest(360, 640, 'Front Door', ResourceRequestReason.EVENT)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(snapshot).not.toHaveBeenCalled()
+ expect(lines).toEqual([
+ '[Front Door] Rejecting snapshot as the camera is out of service.',
+ '[Front Door] Rejecting snapshot as the camera is out of service.',
+ ])
+ })
+
+ it('refuses a snapshot of a camera whose source is stated away as busy over the data stream and with the communication failure over the resource '
+ + 'request, calling no snapshot function, and refuses its recording in the answer to the hub\'s open as busy, raising no alert and telling of no '
+ + 'recording, as it does for a camera out of service', async () => {
+ const { camera, management, snapshot } = snapshotCamera()
+ // The capture begins after the camera's setup, and it reads every line the channel writes from there on.
+ const lines = captureDebug('HAP-NodeJS:Camera:Controller')
+ const told: string[] = []
+ const problems = onCameraProblem(NUMBERED_ACCESSORY_UUID, ({ kind }) => told.push(kind))
+
+ onTestFinished(() => {
+ problems[Symbol.dispose]()
+ })
+ camera.on('recording-started', () => told.push('recording-started'))
+ camera.on('recording-ended', () => told.push('recording-ended'))
+ camera.updateSourceState('away')
+
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const refused = openSnapshot(client)
+ const recordingRefused = open(client)
+
+ await settle()
+
+ expect(answer(client, refused)).toEqual({ reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR })
+ await expect(camera.handleSnapshotRequest(360, 640, 'Front Door', ResourceRequestReason.EVENT)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
+ expect(snapshot).not.toHaveBeenCalled()
+ expect(streamEvents(client, Topics.DATA, 2)).toEqual([])
+ expect(answer(client, recordingRefused)).toEqual({ reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR })
+ expect(streamEvents(client, Topics.DATA, 1)).toEqual([])
+ expect(told).toEqual([])
+ expect(lines.map(line => line.slice(line.indexOf('] ') + 2))).toEqual([
+ 'Rejecting snapshot as the camera is out of service.',
+ 'Rejecting snapshot as the camera is out of service.',
+ ])
+ })
+
+ it('hands the snapshot function a request\'s reason 0 as periodic, 1 as an event and any other value as none', async () => {
+ const { management, snapshot } = snapshotCamera()
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ for (const [streamId, reason] of [
+ [2, 0],
+ [3, 1],
+ [4, 7],
+ ]) {
+ openSnapshot(client, streamId, { imageHeight: 720, imageWidth: 1280, reason })
+ }
+
+ await settle()
+
+ expect(snapshot.mock.calls.map(([{ height, reason, width }]) => ({ height, reason, width }))).toEqual([
+ { height: 720, reason: ResourceRequestReason.PERIODIC, width: 1280 },
+ { height: 720, reason: ResourceRequestReason.EVENT, width: 1280 },
+ { height: 720, reason: undefined, width: 1280 },
+ ])
+ })
+
+ it('ends a snapshot at the hub\'s ack, sending nothing more, and closes one the hub leaves unacknowledged as cancelled twelve seconds after its send', async () => {
+ const { management } = snapshotCamera()
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ openSnapshot(client)
+ openSnapshot(client, 3)
+ await settle()
+ client.event(Protocols.DATA_SEND, Topics.ACK, { endOfStream: true, streamId: 2 })
+ await vi.advanceTimersByTimeAsync(11999)
+
+ expect(client.events(Protocols.DATA_SEND, Topics.CLOSE)).toEqual([])
+
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect(client.events(Protocols.DATA_SEND, Topics.CLOSE)).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.CANCELLED, streamId: 3 },
+ ])
+ })
+
+ it('closes a snapshot whose function rejects as an unexpected failure, sending no picture and logging the rejection once', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { management, snapshot } = snapshotCamera()
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ snapshot.mockRejectedValue(new Error('The camera has no picture.'))
+ openSnapshot(client)
+ await settle()
+
+ expect(streamEvents(client, Topics.DATA)).toEqual([])
+ expect(streamEvents(client, Topics.CLOSE)).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, streamId: 2 },
+ ])
+ expect(error.mock.calls).toEqual([
+ [
+ expect.stringContaining('The snapshot function failed: Error: The camera has no picture.'),
+ ],
+ ])
+ })
+
+ it.each([
+ [
+ 'no size',
+ { reason: 1 },
+ ],
+ [
+ 'a width of zero',
+ { imageHeight: 360, imageWidth: 0, reason: 1 },
+ ],
+ [
+ 'a negative height',
+ { imageHeight: -360, imageWidth: 640, reason: 1 },
+ ],
+ [
+ 'a fractional width',
+ { imageHeight: 360, imageWidth: 640.5, reason: 1 },
+ ],
+ [
+ 'a height that is no number',
+ { imageHeight: 'tall', imageWidth: 640, reason: 1 },
+ ],
+ ])('refuses a snapshot open naming %s as an unexpected failure, joining no stream and fetching nothing', async (_name, metadata) => {
+ const { management, snapshot } = snapshotCamera()
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const refused = openSnapshot(client, 2, metadata)
+
+ await settle()
+
+ expect(answer(client, refused)).toEqual({ reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR })
+ expect(snapshot).not.toHaveBeenCalled()
+ expect(streamEvents(client, Topics.DATA)).toEqual([])
+
+ // The refused open left no stream under its ID. An open naming the same ID with a valid size is served.
+ const served = openSnapshot(client)
+
+ await settle()
+
+ expect(answer(client, served)).toEqual({ reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS })
+ })
+
+ it('closes a snapshot whose function answers an empty picture as an unexpected failure, naming the camera in its error', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { camera, management } = snapshotCamera(true, Buffer.alloc(0))
+ const accessoryInformation = new Service.AccessoryInformation() as AccessoryInformation
+
+ accessoryInformation.setCharacteristic(Characteristic.Name, 'Front Door')
+ camera.handleAccessoryContext({
+ accessoryInformation,
+ accessoryUUID: 'b1b2c3d4-0000-4000-8000-000000000002',
+ published: true,
+ username: undefined,
+ })
+
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ openSnapshot(client)
+ await settle()
+
+ expect(streamEvents(client, Topics.DATA)).toEqual([])
+ expect(streamEvents(client, Topics.CLOSE)).toEqual([
+ { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, streamId: 2 },
+ ])
+ expect(error.mock.calls).toEqual([
+ ['[Front Door] The snapshot function answered no picture, and the snapshot failed.'],
+ ])
+ })
+
+ it('refuses a legacy camera\'s snapshot open as an unexpected failure, a type it does not serve, fetching nothing', async () => {
+ const { delegate, management } = snapshotCamera(false)
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const id = openSnapshot(client)
+
+ await settle()
+
+ expect(answer(client, id)).toEqual({ reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR })
+ expect(delegate.handleSnapshotRequest).not.toHaveBeenCalled()
+ })
+
+ it('aborts a pending snapshot function\'s signal at the hub\'s close, the connection\'s close or the destroy, which closes it as cancelled, and '
+ + 'discards the picture arriving after, sending none', async () => {
+ for (const close of ['hub', 'connection', 'destroy'] as const) {
+ const { management, snapshot } = snapshotCamera()
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const answered = deferred()
+
+ snapshot.mockImplementation(async () => await answered.promise)
+ openSnapshot(client)
+ await settle()
+
+ const [[, signal]] = snapshot.mock.calls
+ const closers = {
+ connection: () => client.closeSocket(),
+ destroy: () => management.destroy(),
+ hub: () => hubClose(client, 2, HDSProtocolSpecificErrorReason.NORMAL),
+ }
+
+ expect(signal.aborted).toBe(false)
+
+ closers[close]()
+ await settle()
+
+ expect(signal.aborted).toBe(true)
+
+ answered.resolve(PICTURE)
+ await settle()
+
+ expect(streamEvents(client, Topics.DATA)).toEqual([])
+ expect(streamEvents(client, Topics.CLOSE)).toEqual(close === 'destroy'
+ ? [
+ { reason: HDSProtocolSpecificErrorReason.CANCELLED, streamId: 2 },
+ ]
+ : [])
+ }
+ })
+
+ it('keeps a pending snapshot function\'s signal unaborted and its stream open through a factory reset and then its source stated away, and aborts it '
+ + 'at the hub\'s close, logging none of its later rejection and leaving the camera no pending call and no timer', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ const { camera, management, snapshot } = snapshotCamera()
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const answered = deferred()
+
+ snapshot.mockImplementation(async () => await answered.promise)
+ openSnapshot(client)
+ await settle()
+
+ const [[, signal]] = snapshot.mock.calls
+
+ camera.handleFactoryReset()
+ await settle()
+
+ expect(signal.aborted).toBe(false)
+ // @ts-expect-error: private access
+ expect(management.snapshotStreams.size).toBe(1)
+
+ camera.updateSourceState('away')
+ await settle()
+
+ expect(signal.aborted).toBe(false)
+ // @ts-expect-error: private access
+ expect(management.snapshotStreams.size).toBe(1)
+
+ hubClose(client, 2, HDSProtocolSpecificErrorReason.NORMAL)
+ await settle()
+
+ expect(signal.aborted).toBe(true)
+
+ answered.reject(new Error('The camera answered after the hub had gone.'))
+ await settle()
+
+ expect(error).not.toHaveBeenCalled()
+ // @ts-expect-error: private access
+ expect(camera.snapshotCalls.size).toBe(0)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('keeps an answered snapshot function\'s signal unaborted through the close of its stream after the picture, by the hub\'s ack, the hub\'s close '
+ + 'or the twelve-second wait', async () => {
+ for (const close of ['ack', 'hub', 'wait'] as const) {
+ const { management, snapshot } = snapshotCamera()
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ openSnapshot(client)
+ await settle()
+
+ const [[, signal]] = snapshot.mock.calls
+ const closers = {
+ ack: async () => client.event(Protocols.DATA_SEND, Topics.ACK, { endOfStream: true, streamId: 2 }),
+ hub: async () => hubClose(client, 2, HDSProtocolSpecificErrorReason.NORMAL),
+ wait: async () => await vi.advanceTimersByTimeAsync(12000),
+ }
+
+ expect(streamEvents(client, Topics.DATA)).toHaveLength(1)
+
+ await closers[close]()
+ await settle()
+
+ // @ts-expect-error: private access
+ expect(management.snapshotStreams.size).toBe(0)
+ expect(signal.aborted).toBe(false)
+ }
+ })
+
+ // An ack ends the recording a later close would name, which is why the ack and the close each reach it in a case of their own.
+ it.each([
+ {
+ called: 'acknowledgeStream' as const,
+ hub: (client: DataStreamClient): void => acknowledge(client),
+ kind: 'ack',
+ with: [1],
+ },
+ {
+ called: 'closeRecordingStream' as const,
+ hub: (client: DataStreamClient): void => hubClose(client, 1, HDSProtocolSpecificErrorReason.NORMAL),
+ kind: 'close',
+ with: [1, HDSProtocolSpecificErrorReason.NORMAL],
+ },
+ ])('refuses as busy a snapshot open naming the running recording\'s stream, whose $kind still reaches the recording', async ({ called, hub, with: args }) => {
+ const { management, recording, snapshot } = snapshotCamera()
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+
+ open(client)
+ await settle()
+
+ const id = openSnapshot(client, 1)
+
+ await settle()
+
+ expect(answer(client, id)).toEqual({ reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR })
+ expect(snapshot).not.toHaveBeenCalled()
+
+ hub(client)
+ await settle()
+
+ expect(recording[called]).toHaveBeenCalledExactlyOnceWith(...args)
+ expect(recordingStreamOf(management)).toBeUndefined()
+ })
+
+ it('refuses as busy a recording open naming a held snapshot\'s stream, starting no recording, the picture still sent under its ID', async () => {
+ const { management, snapshot } = snapshotCamera()
+ const admit = vi.spyOn(management.delegate as BufferRecorder, 'admit')
+ const client = await DataStreamClient.connect(management.dataStreamManagement)
+ const answered = deferred()
+
+ snapshot.mockImplementation(async () => await answered.promise)
+ openSnapshot(client, 1)
+ await settle()
+
+ const id = open(client)
+
+ await settle()
+
+ expect(answer(client, id)).toEqual({ reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR })
+ expect(admit).not.toHaveBeenCalled()
+ expect(recordingStreamOf(management)).toBeUndefined()
+
+ answered.resolve(PICTURE)
+ await settle()
+
+ expect(streamEvents(client, Topics.DATA, 1)).toEqual([
+ {
+ endOfStream: true,
+ packets: [
+ {
+ data: PICTURE,
+ metadata: {
+ dataChunkSequenceNumber: 1,
+ dataSequenceNumber: 1,
+ dataTotalSize: PICTURE.length,
+ isLastDataChunk: true,
+ },
+ },
+ ],
+ streamId: 1,
+ },
+ ])
+ })
+ })
})
diff --git a/src/lib/camera/RecordingManagement.ts b/src/lib/camera/RecordingManagement.ts
index 1f11217a9..6f8e171bd 100644
--- a/src/lib/camera/RecordingManagement.ts
+++ b/src/lib/camera/RecordingManagement.ts
@@ -1,5 +1,5 @@
import type { CharacteristicValue } from '../../types.js'
-import type { CameraRecordingDelegate, StateChangeDelegate } from '../controller/index.js'
+import type { CameraControllerServiceMap, CameraRecordingDelegate, StateChangeDelegate } from '../controller/index.js'
import type {
DataStreamConnection,
DataStreamProtocolHandler,
@@ -8,20 +8,26 @@ import type {
RequestHandler,
} from '../datastream/index.js'
import type { CameraOperatingMode, CameraRecordingManagement } from '../definitions/index.js'
+/* global NodeJS */
+import type { DelegateFailureReport } from '../util/promise-utils.js'
+import type { CameraReporter, DebugWriter } from './diagnostics/CameraReporter.js'
import type { VideoCodecType } from './index.js'
+import type { OperatingModeState } from './OperatingModePolicy.js'
+import type { RecordingAdmission } from './recording/BufferRecorder.js'
+import type { ServedRecording, ServedRecordings } from './recording/ServedRecording.js'
import type { H264CodecParameters, H264Level, H264Profile, Resolution } from './RTPStreamManagement.js'
+import type { SnapshotFetchRequest, SnapshotRefusal } from './StreamingOptions.js'
-/* global NodeJS */
import { Buffer } from 'node:buffer'
import crypto from 'node:crypto'
import { EventEmitter } from 'node:events'
import createDebug from 'debug'
-import { Access, Characteristic, CharacteristicEventTypes } from '../Characteristic.js'
+import { Access, Characteristic } from '../Characteristic.js'
+import { DataStreamManagement } from '../datastream/DataStreamManagement.js'
import {
DataStreamConnectionEvent,
- DataStreamManagement,
HDSConnectionError,
HDSConnectionErrorType,
HDSProtocolError,
@@ -29,19 +35,41 @@ import {
HDSStatus,
Protocols,
Topics,
-} from '../datastream/index.js'
+} from '../datastream/DataStreamServer.js'
import { HAPStatus } from '../HAPServer.js'
import { Service } from '../Service.js'
+import { DisposableStack } from '../util/disposableStack.js'
import { errorMessage, errorStack } from '../util/errors.js'
import { HapStatusError } from '../util/hapStatusError.js'
+import { callDelegate, logDelegateFailure, logDelegateRejection } from '../util/promise-utils.js'
import * as tlv from '../util/tlv.js'
+import { debugChannel } from './diagnostics/debugChannels.js'
import { AudioBitrate } from './index.js'
+import { OperatingModePolicy } from './OperatingModePolicy.js'
+import { ProducerReferenceTimeWriter } from './recording/ProducerReferenceTimeWriter.js'
+import { isPictureSize, ResourceRequestReason } from './StreamingOptions.js'
const debug = createDebug('HAP-NodeJS:Camera:RecordingManagement')
const hksvDebug = createDebug('HAP-NodeJS:HKSV')
+// The channel of a camera's debug events under the management's debug name, which a camera with the capabilities block publishes its snapshots' events on.
+const RECORDING_MANAGEMENT_DEBUG = debugChannel('HAP-NodeJS:Camera:RecordingManagement')
+
+// A data event carries at most 256 KiB of a packet, inside the 1 KiB to 900 KiB a hub takes.
+const MAX_CHUNK = 0x40000
+
+// A stream that has sent all it has waits this long for the hub's ack or close before it closes itself as cancelled.
+const CLOSE_WAIT = 12000
+
+// The reason a snapshot open is refused with over the data stream for each cause the camera's snapshot gate answers.
+const SNAPSHOT_OPEN_REFUSALS: Readonly> = {
+ 'not allowed': HDSProtocolSpecificErrorReason.NOT_ALLOWED,
+ 'out of service': HDSProtocolSpecificErrorReason.BUSY,
+}
+
/**
- * Describes options passed to the {@link RecordingManagement}.
+ * Describes options passed to the {@link RecordingManagement}: the legacy recording configurations a camera offers for a HomeKit controller to select.
+ * A camera with the camera capabilities block gives none, recording from its camera buffer with no configuration selected.
*
* @group Camera
*/
@@ -62,12 +90,14 @@ export interface CameraRecordingOptions {
* which derives the {@link EventTriggerOption}s from application state.
*
* {@link EventTriggerOption}s are derived automatically as follows:
- * {@link EventTriggerOption.MOTION} is enabled when a {@link Service.MotionSensor} is configured (via {@link CameraControllerOptions.sensors}).
+ * {@link EventTriggerOption.MOTION} is enabled when a {@link Service.MotionSensor} is configured (via the `sensors` option of {@link CameraControllerOptions}).
* {@link EventTriggerOption.DOORBELL} is enabled when the {@link DoorbellController} is used.
*
* Note: This property is **ADDITIVE**. Meaning if the {@link CameraController} decides to add
* a certain {@link EventTriggerOption} it will still do so. This option can only be used to
* add **additional** {@link EventTriggerOption}s!
+ *
+ * The triggers are advertised in the supported recording configuration these options describe. A camera that gives no options advertises none.
*/
overrideEventTriggerOptions?: EventTriggerOption[]
@@ -320,7 +350,8 @@ type DataSendDataEvent = {
packets: {
data: Buffer
metadata: {
- dataType: PacketDataType
+ // A recording's packets carry their type, and a snapshot's carry none.
+ dataType?: PacketDataType
dataSequenceNumber: number
isLastDataChunk: boolean
dataChunkSequenceNumber: number
@@ -354,6 +385,37 @@ export interface RecordingManagementServices {
dataStreamManagement: DataStreamManagement
}
+/**
+ * What the camera controller hands the recording management of a camera with the camera capabilities block, whose recordings carry the library's
+ * producer reference time box.
+ * @private
+ */
+interface RecordingManagementCapabilities {
+ /**
+ * The recorder's decision on a recording open, asked once the open passes the management's own checks and before the open is answered: a refusal is
+ * the open's answer with its reason, and an admission's serving function serves the stream in place of the delegate's request. Without it, an open
+ * passing those checks is answered success and the stream asks the delegate.
+ */
+ readonly admit?: (streamId: number) => RecordingAdmission
+ /**
+ * The recordings the camera serves, which each recording stream adds to and the camera's HKSV3 clips upload from.
+ */
+ readonly feed: ServedRecordings
+ /**
+ * The camera's reporter, through which a failed call of the recording delegate, the library's own recorder, is the library's failure.
+ */
+ readonly reporter: CameraReporter
+ /**
+ * The camera's snapshots over the data stream: the cause for which its gate refuses one, read at each open with the request's reason and undefined
+ * where the gate lets it through, and the fetch of one picture at the size a hub asks, with the request's reason when it names one and the snapshot
+ * stream's signal, which every close of the stream aborts. Without it, a snapshot open meets the recording's checks as on any other camera.
+ */
+ readonly snapshot?: {
+ readonly refusal: (reason: ResourceRequestReason | undefined) => SnapshotRefusal | undefined
+ readonly fetch: (request: SnapshotFetchRequest & { readonly signal: AbortSignal }) => Promise
+ }
+}
+
/**
* @group Camera
*/
@@ -376,40 +438,51 @@ export interface RecordingManagementState {
selectedConfiguration?: string
/**
- * Service `CameraRecordingManagement`; Characteristic `Active`
+ * The operating mode of a layout that keeps it beside the recording state. `deserialize` reads these fields when the camera's state carries no
+ * operating-mode slice, and `serialize` never writes them.
*/
- recordingActive: boolean
+ recordingActive?: boolean
/**
- * Service `CameraRecordingManagement`; Characteristic `RecordingAudioActive`
+ * See {@link RecordingManagementState.recordingActive}.
*/
- recordingAudioActive: boolean
-
+ recordingAudioActive?: boolean
/**
- * Service `CameraOperatingMode`; Characteristic `EventSnapshotsActive`
+ * See {@link RecordingManagementState.recordingActive}.
*/
- eventSnapshotsActive: boolean
+ eventSnapshotsActive?: boolean
/**
- * Service `CameraOperatingMode`; Characteristic `HomeKitCameraActive`
+ * See {@link RecordingManagementState.recordingActive}.
*/
- homeKitCameraActive: boolean
+ homeKitCameraActive?: boolean
/**
- * Service `CameraOperatingMode`; Characteristic `PeriodicSnapshotsActive`
+ * See {@link RecordingManagementState.recordingActive}.
*/
- periodicSnapshotsActive: boolean
+ periodicSnapshotsActive?: boolean
+}
+
+// The camera, video and audio recording configurations a camera supports, each base64 TLV8 as its Supported characteristic carries it.
+interface SupportedRecordingConfiguration {
+ readonly audio: string
+ readonly camera: string
+ readonly video: string
}
/**
* @group Camera
*/
export class RecordingManagement {
- readonly options: CameraRecordingOptions
+ /**
+ * The legacy recording options the plugin gave, absent on a camera with the camera capabilities block, which records from its camera buffer.
+ */
+ readonly options?: CameraRecordingOptions
+
readonly delegate: CameraRecordingDelegate
private stateChangeDelegate?: StateChangeDelegate
- private readonly supportedCameraRecordingConfiguration: string
- private readonly supportedVideoRecordingConfiguration: string
- private readonly supportedAudioRecordingConfiguration: string
+ // The supported recording configurations the options describe. A management without options has none, which means it also has no selection for a hub to write,
+ // no configuration hash in its stored state and no open handler check that a configuration is selected.
+ private readonly supportedConfiguration?: SupportedRecordingConfiguration
/**
* 32 bit mask of enabled {@link EventTriggerOption}s.
@@ -420,6 +493,11 @@ export class RecordingManagement {
readonly operatingModeService: CameraOperatingMode
readonly dataStreamManagement: DataStreamManagement
+ /**
+ * The operating-mode policy this management binds its characteristics to and forwards its state-change delegate to.
+ */
+ private readonly operatingMode: OperatingModePolicy
+
/**
* The currently active recording stream.
* Any camera only supports one stream at a time.
@@ -445,18 +523,61 @@ export class RecordingManagement {
sensorServices: Service[] = []
/**
- * Defines if recording is enabled for this recording management.
+ * The recording state last reported to the delegate. A write that leaves it unchanged reports nothing.
*/
- private recordingActive = false
+ private reportedRecordingActive = false
+
+ // Whether each recording stream writes a producer reference time box before every fragment. It is on exactly for a camera with the capabilities block,
+ // and every other camera's recording goes out as its delegate yields it.
+ private producerReferenceTime: boolean
+
+ // The recordings a camera with the capabilities block serves. Each recording stream adds to them what its writer read.
+ private readonly feed?: ServedRecordings
+
+ // The recorder's decision a camera with the capabilities block asks before it answers a recording open, which carries the stream's serving function.
+ private readonly admit?: RecordingManagementCapabilities['admit']
+ // Where every guarded call of the delegate reports its failure, its stream's close among them: the camera's reporter on a camera with the capabilities
+ // block, whose delegate is the library's own recorder, and the console otherwise.
+ private readonly report: DelegateFailureReport
+
+ // The snapshots a camera with the capabilities block answers over the data stream, the camera's reporter, which the capabilities carry beside them and
+ // which every snapshot's debug event goes through, and each open snapshot stream.
+ private readonly snapshot?: RecordingManagementCapabilities['snapshot']
+
+ private readonly reporter?: CameraReporter
+
+ private readonly snapshotStreams = new Set()
+
+ // What destroy releases: every open snapshot stream, then the data stream management, then the open request handler. The characteristic handlers die
+ // with their service or are replaced by the next management over it, and the policy releases its subscriptions when it is disposed itself.
+ private readonly stack = new DisposableStack()
+
+ // The dataSend route of each data stream connection that has passed an open's checks, which leaves the table when its connection closes.
+ private readonly routes = new Map()
+
+ /**
+ * The camera controller alone constructs the management, which is why the constructor is left out of the documentation, along with the policy and the
+ * capabilities it takes.
+ * @hidden
+ */
constructor(
- options: CameraRecordingOptions,
+ options: CameraRecordingOptions | undefined,
delegate: CameraRecordingDelegate,
eventTriggerOptions: Set,
services?: RecordingManagementServices,
+ operatingMode: OperatingModePolicy = new OperatingModePolicy(),
+ capabilities?: RecordingManagementCapabilities,
) {
this.options = options
this.delegate = delegate
+ this.operatingMode = operatingMode
+ this.producerReferenceTime = capabilities !== undefined
+ this.feed = capabilities?.feed
+ this.admit = capabilities?.admit
+ this.report = capabilities?.reporter.sink('library-failure') ?? logDelegateFailure
+ this.snapshot = capabilities?.snapshot
+ this.reporter = capabilities?.reporter
const recordingServices = services || this.constructService()
this.recordingManagementService = recordingServices.recordingManagement
@@ -468,15 +589,66 @@ export class RecordingManagement {
this.eventTriggerOptions |= option // OR
}
- this.supportedCameraRecordingConfiguration = this._supportedCameraRecordingConfiguration(options)
- this.supportedVideoRecordingConfiguration = this._supportedVideoRecordingConfiguration(options.video)
- this.supportedAudioRecordingConfiguration = this._supportedAudioStreamConfiguration(options.audio)
+ if (options) {
+ const camera = this._supportedCameraRecordingConfiguration(options)
+ const video = this._supportedVideoRecordingConfiguration(options.video)
+ const audio = this._supportedAudioStreamConfiguration(options.audio)
+
+ this.supportedConfiguration = { audio, camera, video }
+ }
this.setupServiceHandlers()
+ this.stack.adopt(this.dataStreamManagement, dataStreamManagement => dataStreamManagement.destroy())
+
+ // Every open snapshot stream closes as cancelled, and a picture still being fetched is discarded with nothing sent.
+ this.stack.defer(() => {
+ for (const stream of this.snapshotStreams) {
+ stream.close(HDSProtocolSpecificErrorReason.CANCELLED)
+ }
+ })
hksvDebug('RecordingManagement created (eventTriggers=0x%s)', this.eventTriggerOptions.toString(16))
}
+ /**
+ * Reconciles the recording services of a restored service map. They form one set: the management is built over the saved services only when all of them
+ * are saved, and otherwise over a new set written under every key. A camera that does not record deletes each saved recording service.
+ * @param serviceMap - The camera's service map, changed in place.
+ * @param create - Builds the management over the given services, or over new ones when it is given none, and is absent for a camera that does not record.
+ * @returns Whether the map changed.
+ * @private
+ */
+ static reconcile(serviceMap: CameraControllerServiceMap, create?: (services?: RecordingManagementServices) => RecordingManagement): boolean {
+ if (!create) {
+ let modified = false
+
+ for (const key of ['cameraEventRecordingManagement', 'cameraOperatingMode', 'dataStreamTransportManagement'] as const) {
+ if (serviceMap[key]) {
+ delete serviceMap[key]
+ modified = true
+ }
+ }
+
+ return modified
+ }
+
+ const { cameraEventRecordingManagement, cameraOperatingMode, dataStreamTransportManagement } = serviceMap
+ if (cameraEventRecordingManagement && cameraOperatingMode && dataStreamTransportManagement) {
+ create({
+ recordingManagement: cameraEventRecordingManagement,
+ operatingMode: cameraOperatingMode,
+ dataStreamManagement: new DataStreamManagement(dataStreamTransportManagement),
+ })
+ return false
+ }
+
+ const management = create()
+ serviceMap.cameraEventRecordingManagement = management.recordingManagementService
+ serviceMap.cameraOperatingMode = management.operatingModeService
+ serviceMap.dataStreamTransportManagement = management.dataStreamManagement.getService()
+ return true
+ }
+
private constructService(): RecordingManagementServices {
const recordingManagement = new Service.CameraRecordingManagement('', '')
recordingManagement.setCharacteristic(Characteristic.Active, false)
@@ -498,66 +670,93 @@ export class RecordingManagement {
}
private setupServiceHandlers() {
- // update the current configuration values to the current state.
- this.recordingManagementService.setCharacteristic(Characteristic.SupportedCameraRecordingConfiguration, this.supportedCameraRecordingConfiguration)
- this.recordingManagementService.setCharacteristic(Characteristic.SupportedVideoRecordingConfiguration, this.supportedVideoRecordingConfiguration)
- this.recordingManagementService.setCharacteristic(Characteristic.SupportedAudioRecordingConfiguration, this.supportedAudioRecordingConfiguration)
-
- this.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration)
- .onGet(this.handleSelectedCameraRecordingConfigurationRead.bind(this))
- .onSet(this.handleSelectedCameraRecordingConfigurationWrite.bind(this))
- .setProps({
- adminOnlyAccess: [Access.WRITE],
- })
+ const { supportedConfiguration } = this
+
+ if (supportedConfiguration) {
+ // update the current configuration values to the current state.
+ this.recordingManagementService.setCharacteristic(Characteristic.SupportedCameraRecordingConfiguration, supportedConfiguration.camera)
+ this.recordingManagementService.setCharacteristic(Characteristic.SupportedVideoRecordingConfiguration, supportedConfiguration.video)
+ this.recordingManagementService.setCharacteristic(Characteristic.SupportedAudioRecordingConfiguration, supportedConfiguration.audio)
+
+ this.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration)
+ .onGet(this.handleSelectedCameraRecordingConfigurationRead.bind(this))
+ .onSet(this.handleSelectedCameraRecordingConfigurationWrite.bind(this))
+ .setProps({
+ adminOnlyAccess: [Access.WRITE],
+ })
+ } else {
+ // A service adopted from a camera that gave the options before drops the configuration characteristics, and the camera advertises no configuration
+ // it does not offer. Each removal raises the service's configuration change, which moves the accessory's configuration number at its next publish.
+ for (const type of [
+ Characteristic.SupportedCameraRecordingConfiguration,
+ Characteristic.SupportedVideoRecordingConfiguration,
+ Characteristic.SupportedAudioRecordingConfiguration,
+ Characteristic.SelectedCameraRecordingConfiguration,
+ ]) {
+ const characteristic = this.recordingManagementService.characteristics.find(candidate => candidate.UUID === type.UUID)
+
+ if (characteristic) {
+ this.recordingManagementService.removeCharacteristic(characteristic)
+ }
+ }
+ }
this.recordingManagementService.getCharacteristic(Characteristic.Active)
.onSet((value) => {
- if (!!value === this.recordingActive) {
+ const active = !!value
+ if (active === this.reportedRecordingActive) {
return // skip delegate call if state didn't change!
}
- this.recordingActive = !!value
- hksvDebug('Active onSet: recordingActive -> %s', this.recordingActive)
- this.delegate.updateRecordingActive(this.recordingActive)
- })
- .on(CharacteristicEventTypes.CHANGE, () => this.stateChangeDelegate?.())
- .setProps({
- adminOnlyAccess: [Access.WRITE],
+ hksvDebug('Active onSet: recordingActive -> %s', active)
+ // A write reports here rather than through reportRecordingActive, because a synchronous throw belongs to the write's handler, which answers HomeKit
+ // with the failure and stores nothing. The report is recorded before the delegate hears it, as reportRecordingActive records it: a delegate that
+ // writes Active from inside its call is told once. The catch puts back the report recorded before this write, and a retry of the same value
+ // reaches the delegate again. A rejection, which nothing awaits, goes to the management's failure report.
+ const previous = this.reportedRecordingActive
+ this.reportedRecordingActive = active
+ try {
+ logDelegateRejection(this.delegate.updateRecordingActive(active), 'CameraRecordingDelegate failed to update state at a write of Active', undefined,
+ this.report)
+ } catch (error) {
+ this.reportedRecordingActive = previous
+ throw error
+ }
})
- this.recordingManagementService.getCharacteristic(Characteristic.RecordingAudioActive)
- .on(CharacteristicEventTypes.CHANGE, () => this.stateChangeDelegate?.())
+ // The policy marks its admin-only fields as it binds them: every projection of a field carries the mark.
+ this.operatingMode.bindRecording(this.recordingManagementService, this.operatingModeService)
+ this.operatingMode.subscribe('homeKitCameraActive', (active) => {
+ for (const service of this.sensorServices) {
+ service.setCharacteristic(Characteristic.StatusActive, active)
+ }
- this.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive)
- .on(CharacteristicEventTypes.CHANGE, (change) => {
- for (const service of this.sensorServices) {
- service.setCharacteristic(Characteristic.StatusActive, !!change.newValue)
- }
+ if (!active && this.recordingStream) {
+ this.recordingStream.close(HDSProtocolSpecificErrorReason.NOT_ALLOWED)
+ }
+ })
- if (!change.newValue && this.recordingStream) {
- this.recordingStream.close(HDSProtocolSpecificErrorReason.NOT_ALLOWED)
- }
+ // A write that reaches Active around its onSet handler, a plugin's update among them, reports here, and the delegate hears each change once.
+ this.operatingMode.subscribe('recordingActive', (active) => {
+ if (active === this.reportedRecordingActive) {
+ return
+ }
- this.stateChangeDelegate?.()
- })
- .setProps({
- adminOnlyAccess: [Access.WRITE],
- })
+ hksvDebug('Active change: recordingActive -> %s', active)
+ this.reportRecordingActive(active, 'after an update of Active')
+ })
- this.operatingModeService.getCharacteristic(Characteristic.EventSnapshotsActive)
- .on(CharacteristicEventTypes.CHANGE, () => this.stateChangeDelegate?.())
- .setProps({
- adminOnlyAccess: [Access.WRITE],
- })
+ const open = this.handleDataSendOpen.bind(this)
- this.operatingModeService.getCharacteristic(Characteristic.PeriodicSnapshotsActive)
- .on(CharacteristicEventTypes.CHANGE, () => this.stateChangeDelegate?.())
- .setProps({
- adminOnlyAccess: [Access.WRITE],
- })
+ this.dataStreamManagement.onRequestMessage(Protocols.DATA_SEND, Topics.OPEN, open)
+ this.stack.defer(() => this.dataStreamManagement.removeRequestHandler(Protocols.DATA_SEND, Topics.OPEN, open))
+ }
- this.dataStreamManagement
- .onRequestMessage(Protocols.DATA_SEND, Topics.OPEN, this.handleDataSendOpen.bind(this))
+ // The report is recorded before the delegate hears it. A delegate that fails is told once, and callDelegate hands its failure to the management's
+ // failure report rather than letting it reach the caller that carried the change.
+ private reportRecordingActive(active: boolean, occasion: string): void {
+ this.reportedRecordingActive = active
+ callDelegate(() => this.delegate.updateRecordingActive(active), `CameraRecordingDelegate failed to update state ${occasion}`, this.report)
}
private handleDataSendOpen(connection: DataStreamConnection, id: number, message: HDSMessage) {
@@ -576,6 +775,11 @@ export class RecordingManagement {
return
}
+ if (this.snapshot && target === 'controller' && type === 'ipcamera.snapshot') {
+ this.handleSnapshotOpen(connection, id, message, this.snapshot, this.reporter!)
+ return
+ }
+
if (target !== 'controller' || type !== 'ipcamera.recording') {
debug('[HDS %s] Received data send with unexpected target: %s or type: %d. Rejecting...',
connection.remoteAddress, target, type)
@@ -585,16 +789,9 @@ export class RecordingManagement {
return
}
- if (!this.recordingActive) {
- hksvDebug('[HDS %s] rejecting DATA_SEND OPEN: recordingActive=false', connection.remoteAddress)
- connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, {
- status: HDSProtocolSpecificErrorReason.NOT_ALLOWED,
- })
- return
- }
-
- if (!this.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value) {
- hksvDebug('[HDS %s] rejecting DATA_SEND OPEN: HomeKitCameraActive=false', connection.remoteAddress)
+ if (!this.operatingMode.recordingAllowed()) {
+ hksvDebug('[HDS %s] rejecting DATA_SEND OPEN: recording is not allowed (recordingActive=%s HomeKitCameraActive=%s)',
+ connection.remoteAddress, this.operatingMode.recordingActive, this.operatingMode.homeKitCameraActive)
connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, {
status: HDSProtocolSpecificErrorReason.NOT_ALLOWED,
})
@@ -611,7 +808,8 @@ export class RecordingManagement {
return
}
- if (!this.selectedConfiguration) {
+ // A camera without the legacy options offers no configuration to select, and its recording is served with none selected.
+ if (this.supportedConfiguration && !this.selectedConfiguration) {
hksvDebug('[HDS %s] rejecting DATA_SEND OPEN: no selectedConfiguration (homebridge#3928)', connection.remoteAddress)
connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, {
status: HDSProtocolSpecificErrorReason.INVALID_CONFIGURATION,
@@ -619,16 +817,146 @@ export class RecordingManagement {
return
}
+ // A recording never takes a stream ID the connection's route holds, a snapshot's among them, and the held stream is left as it is.
+ if (this.routes.get(connection)?.holds(streamId)) {
+ debug('[HDS %s] Rejecting DATA_SEND OPEN of recording stream %d as the connection already runs a stream with that ID.', connection.remoteAddress, streamId)
+ connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, {
+ status: HDSProtocolSpecificErrorReason.BUSY,
+ })
+ return
+ }
+
+ // A camera with the capabilities block asks its recorder last, once every check of the management's own has passed. The plugin's shouldRecord is
+ // called only for an open nothing else refuses. The recorder decides once, before the answer: a refusal is the open's answer with its reason, which means no
+ // stream opens and no data event follows, and an admission carries the function the stream serves the recording through.
+ const admission = this.admit?.(streamId)
+
+ if (admission?.admitted === false) {
+ connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, {
+ status: admission.reason,
+ })
+ return
+ }
+
+ // A camera can pass every check above before the delegate hears that recording is active, a camera whose accessory has not reported its restore
+ // complete among them, which is why the first request it lets through tells the delegate first, before the recording it asks for starts.
+ if (!this.reportedRecordingActive) {
+ hksvDebug('[HDS %s] DATA_SEND OPEN: recordingActive -> true before the first recording', connection.remoteAddress)
+ this.reportRecordingActive(true, 'before a recording request')
+ }
+
debug('[HDS %s] HDS DATA_SEND Open with reason \'%s\'.', connection.remoteAddress, reason)
+ const route = this.routeOf(connection)
// eslint-disable-next-line ts/no-use-before-define
- this.recordingStream = new CameraRecordingStream(connection, this.delegate, id, streamId)
- this.recordingStream.on(CameraRecordingStreamEvents.CLOSED, () => {
+ const stream = new CameraRecordingStream(connection, this.delegate, id, streamId, this.producerReferenceTime, this.report, this.feed, admission?.serve)
+
+ // The stream joins its route and becomes the camera's recording before it starts: a close during its start, such as one a delegate's synchronous
+ // throw causes, clears both.
+ route.add(stream)
+ this.recordingStream = stream
+ stream.on(CameraRecordingStreamEvents.CLOSED, () => {
debug('[HDS %s] Removing active recording session from recording management!', connection.remoteAddress)
this.recordingStream = undefined
})
- this.recordingStream.startStreaming()
+ stream.startStreaming()
+ }
+
+ /* A snapshot open on a camera with the capabilities block, whose metadata names the picture's size and the request's reason, read once and handed to the
+ * camera's gate and its fetch alike. It is refused while the camera's gate refuses, as not allowed while streaming is not allowed or the kind its reason
+ * names is switched off and as busy while the camera is out of service, then as busy when it names a stream ID the connection's route holds, the held
+ * stream left as it is, and as an unexpected failure, the open's status for a fault no other status names, when its width or height is not a positive
+ * whole number. Otherwise a snapshot stream joins the route, answers the open and sends the picture its fetch brings.
+ */
+ private handleSnapshotOpen(
+ connection: DataStreamConnection,
+ id: number,
+ message: Record